brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: Python's inspect.getsource shows the code behind any function

Python
~/tips/tip-python-inspect-getsource

import inspect, textwrap

Read the source of a function or class from the prompt without hunting for the file.

When a library function does something I didn’t expect, I want to read it. inspect can show me the code and tell me which file it came from.

import inspect, textwrap

print(inspect.getsource(textwrap.dedent))
print(inspect.getsourcefile(textwrap.dedent))
# /usr/lib/python3.12/textwrap.py  (path depends on your install)

getsource works on functions, classes, methods and whole modules. In an interactive session it’s quicker than opening an editor, especially inside a virtual environment where the package lives somewhere deep in site-packages.

getsourcefile answers a question that comes up surprisingly often: which copy of this module am I actually importing? If you have the same package installed twice, that’s how you find out the wrong one wins.

I also like inspect.signature(func) next to it, which prints the arguments with their defaults, handy when the docs are vague.

It only works when Python can find a .py file. Functions written in C, like len or most of math, raise a TypeError, and code typed straight into the plain REPL may raise OSError because there’s no file behind it.

Further reading: inspect.getsource

More Python tips import asyncio from enum import StrEnum, auto except* ValueError as eg: import pytest pytest --maxfail=2 All Python tips (107) All topics

Link