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?