1

I have been using the following function to inspect function source code while working with Jupyter lab/notebook:

def source(function):
    print(inspect.getsource(function))

For shorter codes this is fine, but at some point code highlighting would be handy. Thus I looked into using Pygments:

def source2(function):
    from IPython.core.display import HTML, display
    from pygments import highlight
    from pygments.lexers import PythonLexer
    from pygments.formatters import HtmlFormatter
    code = inspect.getsource(function)
    html = highlight(code, PythonLexer(), HtmlFormatter(style='colorful'))
    display(HTML(html))

While this seems to produce intermediate HTML code and display it properly the code stays plain (no highlighting). The intermediate string variable "html" has the following content.

'<div class="highlight">
 <pre><span>
 </span><span class="k">def</span>
 <span class="nf">source</span>
 <span class="p">(</span>
 <span class="n">function</span>
 <span class="p">):</span>\n
 <span class="k">print</span>
 <span class="p">(</span>
 <span class="n">inspect</span>
 <span class="o">.</span>
 <span class="n">getsource</span>
 <span class="p">(</span>
 <span class="n">function</span>
 <span class="p">))</span>\n
 </pre></div>\n'

I believe I might simply be missing a CSS file?

Bonus question (might split this off later): is there a way to use this on a function through the right-click context menu or a short cut/hotkey in Jupyter lab/notebook?

Konsta
  • 347
  • 4
  • 18

2 Answers2

0

This answer to this question suggests adding the following display call to insert the styles:

display(HTML("""
<style>
{pygments_css}
</style>
""".format(pygments_css=HtmlFormatter().get_style_defs('.highlight'))))
Aaron
  • 1
0

For the TL:DR folk like myself who are just after a snippet, both the Q and main A both provide the code required to display a the source code colourfully:

def display_source(non_builtin_object):
    import inspect
    from IPython.display import HTML, display
    from pygments import highlight
    from pygments.lexers import PythonLexer
    from pygments.formatters import HtmlFormatter
    code = inspect.getsource(non_builtin_object)
    html = highlight(code, PythonLexer(), HtmlFormatter(style='colorful'))
    stylesheet = f"<style>{HtmlFormatter().get_style_defs('.highlight')}</style>"
    display(HTML(f"{stylesheet}{html}"))
Matteo Ferla
  • 2,128
  • 1
  • 16
  • 27