Python
source code
function
programming
code access

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.

Practice algorithms

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.

python
1import inspect
2
3
4def normalize_name(name: str) -> str:
5    cleaned = name.strip().lower()
6    return " ".join(cleaned.split())
7
8
9print(inspect.getsource(normalize_name))

This is usually enough for debugging, teaching, or generating documentation.

Related helpers are useful too:

python
1import inspect
2
3
4def area(width: float, height: float = 1.0) -> float:
5    return width * height
6
7
8lines, start = inspect.getsourcelines(area)
9print(start)
10print("".join(lines))
11print(inspect.signature(area))

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.

python
1import inspect
2import mymodule
3
4fn = mymodule.transform
5print(inspect.getmodule(fn).__name__)
6print(inspect.getsourcefile(fn))
7print(inspect.getsource(fn))

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.

python
1import inspect
2
3try:
4    print(inspect.getsource(len))
5except OSError as exc:
6    print(f"No Python source: {exc}")

For these cases, fall back to documentation, help, and signatures when available:

python
1import inspect
2
3print(help(len))
4print(inspect.signature(sorted))

Bytecode View as a Practical Fallback

If source text is missing but object behavior matters, disassembly can still help.

python
1import dis
2
3
4def discount(price: float, ratio: float) -> float:
5    if ratio < 0 or ratio > 1:
6        raise ValueError("ratio out of range")
7    return price * (1 - ratio)
8
9
10dis.dis(discount)

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:

python
1import inspect
2from app.math_utils import clamp
3
4
5def test_clamp_source_contains_guard():
6    src = inspect.getsource(clamp)
7    assert "if value < low" in src

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.getsource to work for built-in functions like len
  • Running introspection on objects generated dynamically with exec and no stable file context
  • Assuming decorators preserve original source shape without using functools.wraps
  • Catching only one exception type even though OSError and TypeError can 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.getsource for user-defined Python functions.
  • Use getsourcelines, signature, and getsourcefile for extra context.
  • Built-ins and C extension functions often have no Python source text.
  • Use help and dis as practical fallbacks when needed.
  • Keep important functions in importable modules for reliable inspection.

Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Basis Lab
No 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 course
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.

Practice algorithms