Today I learned you can embed images in your module docstrings and they'll be rendered in the tooltips inside your IDE.

Images in docstrings

As it turns out, VS Code (and likely other editors, too) render docstrings as Markdown. That means you can add images to your docstrings using Markdown syntax and they will be rendered.

I used uv init --package myproj to initialise a project and this is what I put at the top of the file src/myproj/__init__.py as the module docstring:

"""
Hey there!

![](https://mathspp.com/user/themes/myquark/images/rodrigo_256.png)
"""

Then, I created another file and typed import myproj at the top of the file. When I hovered over the import line, the tooltip showed my face:

Screenshot of VS Code showing a tooltip with the documentation for the module myproj that shows a static picture of my face.
A VS Code tooltip showing an image.

This works with GIFs and plain images, as long as you're pointing to a URL on the Internet. (It looks like it doesn't work with local files). It also works on other objects that can be documented with docstrings... For example, it also works with functions.

Here's a simple function I defined and documented inside src/myproj/__init__.py:

def two():
    """![](https://mathspp.com/blog/til/images-in-docstrings/_two.gif)"""
    return 2

When I used it in my other file and hovered over its name, I saw the GIF animation inside VS Code:

Screenshot of VS Code showing a tooltip with the documentation for the function myproj.two that includes a GIF of two celebreties, with the one on the right saying the word โ€œtwoโ€ while lifting their pointer and middle fingers in the typical gesture to represent the number two.
A VS Code tooltip showing a GIF.

This is pretty hilarious but a reasonable use case might be to include diagrams for complex functions...

Try it yourself!

Give it a go yourself! Open an arbitrary Python file and paste this code in:

def two():
    """![](https://mathspp.com/blog/til/images-in-docstrings/_two.gif)"""
    return 2

print(two())

Hover over the two() in the last line and you should see the โ€œTWO!โ€ GIF playing.

Hats off to โ€œMACE!!!โ€ who indirectly showed me this on BlueSky.

Become a better Python ๐Ÿ developer, drop by drop ๐Ÿ’ง

Get a daily drop of Python knowledge. A short, effective tip to start writing better Python code: more idiomatic, more effective, more efficient, with fewer bugs. Subscribe here.

References

Previous Post

Blog Comments powered by Disqus.