How can I get the source code of a Python function?
Data Structures & Algorithms practice on Codemia
Step through 300+ coding interview problems with animated visualisers that show the data structure changing as the code runs. The Blind 75 are free.
Introduction
Python lets you inspect many objects at runtime, including the source code of user-defined functions. The standard inspect module handles most use cases and is the best first option. When source is unavailable, you can still use bytecode and metadata tools to understand behavior.
Use inspect.getsource for Normal Functions
For functions defined in a .py file, inspect.getsource returns the original source text.
This is usually enough for debugging, teaching, or generating documentation.
Related helpers are useful too:
getsourcelines gives you the starting line number, which is helpful for editor links and static analysis reports.
Source File and Module Context
You can locate where a function came from before loading its source.
This is useful in large codebases where function names may exist in multiple modules.
Handling Built-ins and C Extensions
Some objects do not have Python source available, such as built-ins or functions implemented in C. Attempting inspect.getsource raises an exception.
For these cases, fall back to documentation, help, and signatures when available:
Bytecode View as a Practical Fallback
If source text is missing but object behavior matters, disassembly can still help.
Bytecode is not as readable as source, but it reveals control flow and operations.
Retrieving Source in Interactive Sessions
Interactive shells and notebooks can be tricky because some definitions are not backed by stable source files. A reliable approach is to define important functions in modules and import them. If you must work interactively, keep notebook cells simple and versioned so source retrieval remains predictable.
In test suites, this pattern is common:
This makes introspection deterministic and avoids notebook-specific limitations.
Building Tooling on Top of Introspection
Once you can retrieve source reliably, you can build practical tooling such as auto-documentation checks, API diff scripts, and test coverage mappers that link functions back to source lines. The key is to treat introspection output as diagnostic data, not executable input. Storing function signatures, source hashes, and module paths gives you a lightweight way to track behavior drift across releases without introducing heavy static analysis dependencies.
Common Pitfalls
- Expecting
inspect.getsourceto work for built-in functions likelen - Running introspection on objects generated dynamically with
execand no stable file context - Assuming decorators preserve original source shape without using
functools.wraps - Catching only one exception type even though
OSErrorandTypeErrorcan occur - Treating bytecode output as a full replacement for high-level source
When introspection fails, verify object type, module origin, and implementation language before choosing a fallback.
Summary
- Start with
inspect.getsourcefor user-defined Python functions. - Use
getsourcelines,signature, andgetsourcefilefor extra context. - Built-ins and C extension functions often have no Python source text.
- Use
helpanddisas practical fallbacks when needed. - Keep important functions in importable modules for reliable inspection.
Related reading
- How can I get the version defined in setup.py setuptools in my package?
- How can I implement a tree in Python?
- How can I import a module dynamically given its name as string?
- How can I import a module dynamically given the full path?
- How can I increase the accuracy of my Linear Regression model?machine learning with python
- How can I Install a Python module with Pip programmatically from my code?
- How can I install from a git subdirectory with pip?
- How can I install packages using pip according to the requirements.txt file from a local directory?
System design interview problems on this topic
- Design a Web Crawler: solution and walkthrough
- Design a Task Scheduler: solution and walkthrough
- Design a URL Shortener (TinyURL): solution and walkthrough
- Design an API Rate Limiter: solution and walkthrough
.png&w=3840&q=75)
Tackling System Design Interview Problems
A short course that equips you with the skills to approach system design interviews methodically.
Start the free courseNo course covers this one yet
Basis Lab writes one for you from a sentence about what you want to be able to do, then teaches it and checks you understood. Your first course is free.
Build my courseData Structures & Algorithms practice on Codemia
Step through 300+ coding interview problems with animated visualisers that show the data structure changing as the code runs. The Blind 75 are free.