If the function is from a source file available on the filesystem, then inspect.getsource(foo) might be of help:

If foo is defined as:

def foo(arg1,arg2):         
    #do something with args 
    a = arg1 + arg2         
    return a  

Then:

import inspect
lines = inspect.getsource(foo)
print(lines)

Returns:

def foo(arg1,arg2):         
    #do something with args 
    a = arg1 + arg2         
    return a                

But I believe that if the function is compiled from a string, stream or imported from a compiled file, then you cannot retrieve its source code.

Answer from Rafał Dowgird on Stack Overflow
🌐
Python
docs.python.org › 3 › library › inspect.html
inspect — Inspect live objects
Some callables may not be introspectable in certain implementations of Python. For example, in CPython, some built-in functions defined in C provide no metadata about their arguments. CPython implementation detail: If the passed object has a __signature__ attribute, we may use it to create the signature. The exact semantics are an implementation detail and are subject to unannounced changes. Consult the source code for current semantics. class inspect.Signature(parameters=None, *, return_annotation=Signature.empty)¶
🌐
Real Python
realpython.com › ref › stdlib › inspect
inspect | Python Standard Library – Real Python
Retrieving and displaying the source code of functions and classes ... Suppose you want to create a simple command-line tool that inspects functions within a module and displays their signatures and docstrings.
Discussions

How can I get the source code of a Python function? - Stack Overflow
I can get the name of the function using foo.func_name. How can I programmatically get its source code, as I typed above? ... You can get a lot of other things as well. ... This page has become a hot mess. I'd like to see this page evolve into a resource that can be read quickly to get a set of useful answers across different Python interactive environments (e.g. Python vs. IPython), using different libraries (e.g. inspect... More on stackoverflow.com
🌐 stackoverflow.com
Using the "inspect" module to print the source code of a function
Do you not use VS Code and extensions? You can just hover over functions to see source code, control click to jump to the function definition (and it will also display external source code definitions). More on reddit.com
🌐 r/pythontips
3
8
April 9, 2024
Python's introspection methods
I don't know of any "cheat sheet" as such, so you have to fall back to searching on things like "python introspection". Here's one hit that looks reasonable: https://devopedia.org/introspection-in-python That includes the builtin functions you mention and the inspect module . I've also found the traceback module useful for looking at the call stack. More on reddit.com
🌐 r/learnpython
4
2
June 12, 2024
How can I display the code for a Python method along with the code for its nested functions, specifying a particular depth?

Will you be ok to add a custom decorator to your functions? If yes I think it is pretty easy, in a file You can do this:

from inspect import getsource
import my_module

def code_printer(func):
    print(getsource(func))
    return func

if name == '__main__': ...

In my_module there is your functions. And your function, in my_module will look like:

from printer import code_printer

@code_printer
def custom_function():
     do something here

Printer is the name of the file that I created where the decorator code_printer is defined. The decorator does not change the function, since it just returns it, but allows you to print the function code even without executing the function.

What you think?

More on reddit.com
🌐 r/learnpython
6
1
December 17, 2023
🌐
GeeksforGeeks
geeksforgeeks.org › python › inspect-module-in-python
Inspect Module in Python - GeeksforGeeks
July 15, 2025 - Example 2: In this example, we are checking whether a given object is a module or not. We import the numpy module and then pass it to inspect.ismodule(). If the object passed is a module, the method returns True. ... Example 3: In this example, we check if an object is a user-defined function.
🌐
Python Module of the Week
pymotw.com › 2 › inspect
inspect – Inspect live objects - Python Module of the Week
Modules can contain classes and functions; classes can contain methods and attributes; and so on. import inspect import example for name, data in inspect.getmembers(example): if name == '__builtins__': continue print '%s :' % name, repr(data) This sample prints the members of the example module. Modules have a set of __builtins__, which are ignored in the output for this example because they are not actually part of the module and the list is long. $ python inspect_getmembers_module.py A : <class 'example.A'> B : <class 'example.B'> __doc__ : 'Sample file to serve as the basis for inspect examples.\n' __file__ : '/Users/dhellmann/Documents/PyMOTW/branches/inspect/example.pyc' __name__ : 'example' instance_of_a : <example.A object at 0xbb810> module_level_function : <function module_level_function at 0xc8230>
🌐
Python
docs.python.org › 3.8 › library › inspect.html
inspect — Inspect live objects — Python 3.8.20 documentation
For example, it can help you examine the contents of a class, retrieve the source code of a method, extract and format the argument list for a function, or get all the information you need to display a detailed traceback. There are four main kinds of services provided by this module: type checking, getting source code, inspecting classes and functions, and examining the interpreter stack.
🌐
Reddit
reddit.com › r/pythontips › using the "inspect" module to print the source code of a function
r/pythontips on Reddit: Using the "inspect" module to print the source code of a function
April 9, 2024 -

Suppose you have a function, and you want to print its source code.

You can do it like this:

import inspect


# Define a function
def my_function():
    x = 1
    y = 2
    z = x + y
    return z


# Print the source code of the function using inspect.getsource
source_code = inspect.getsource(my_function)
print(source_code)

The "inspect.getsource" function is used to get the source code of the "my_function" function. The "getsource" function takes a function object as its argument and returns a string that contains the source code of the function.

This trick is useful when you want to inspect the source code of a function, especially if the function is defined in a third-party library or module.

Find elsewhere
🌐
ArjanCodes
arjancodes.com › blog › how-to-analyze-python-classes-with-inspect-module
Inspect Module Guide for Python Classes | ArjanCodes
April 4, 2024 - For those seeking to take their introspection a step further, the inspect module is a treasure trove. It provides several functions to retrieve information about live objects, such as modules, classes, methods, functions, tracebacks, and the Python frame stack.
🌐
Reintech
reintech.io › blog › python-practical-applications-inspect-method-tutorial-for-developers
Python: Practical Applications of the inspect() Method | Reintech media
January 20, 2026 - This tutorial explores the practical applications of the inspect() method in Python. It covers retrieving information about objects, debugging code, dynamic analysis, and creating decorators. The inspect() method is a powerful tool for gaining deeper insights into code and optimizing it more effectively for performance and functionality.
🌐
W3Schools
w3schools.com › python › ref_module_inspect.asp
Python inspect Module
The inspect module provides several useful functions to help get information about live objects such as modules, classes, methods, functions, tracebacks, frame objects, and code objects.
🌐
Medium
elshad-karimov.medium.com › pythons-inspect-module-uncovering-the-secrets-of-your-code-4b8eef382e7a
Python’s inspect Module – Uncovering the Secrets of Your Code 🔍🐍 | by Elshad Karimov | Medium
March 26, 2025 - Have you ever wondered how Python debuggers, profilers, or even help() work under the hood? The answer lies in Python’s inspect module! The inspect module allows us to introspect functions, classes, and even stack frames at runtime.
🌐
Python
docs.python.org › 3.4 › library › inspect.html
29.12. inspect — Inspect live objects — Python 3.4.10 documentation
June 16, 2019 - For example, it can help you examine the contents of a class, retrieve the source code of a method, extract and format the argument list for a function, or get all the information you need to display a detailed traceback. There are four main kinds of services provided by this module: type checking, getting source code, inspecting classes and functions, and examining the interpreter stack.
🌐
TutorialsPoint
tutorialspoint.com › inspect-live-objects-in-python
Inspect live objects in Python
The inspect module in Python provides powerful functions to examine live objects such as modules, classes, methods, functions, and code objects. These functions perform type checking, retrieve source code, inspect classes and functions, and examine
🌐
Python Pool
pythonpool.com › home › blog › python inspect module and its applications with examples
Python Inspect Module and its Applications With Examples - Python Pool
March 10, 2022 - We can locate a Python module in our system by running this function. Let’s take the same logging module as our example. ... import logging import inspect # Returns system location of the python logging module inspect.getfile(logging) #### Output #### '/usr/lib/python3.7/logging/__init__.py'
🌐
AskPython
askpython.com › home › python inspect module
Python inspect module - AskPython
August 6, 2022 - Python’s inspect module provides the introspection of live objects and the source code of the same. It also provides the introspection of the classes and functions used throughout the program.
🌐
Martin Heinz
martinheinz.dev › blog › 82
All The Ways To Introspect Python Objects at Runtime | Martin Heinz | Personal Website & Blog
October 3, 2022 - There are a couple ways to do that - the best option is to use callable(), if you're however running Python 3.1, then you'd have to check for presence of __call__ attribute using hasattr function instead. Last option would be to use isfunction() from inspect module, be careful with that one though, as it will return False for builtin functions such as sum, len or range because these are implemented in C, so they're not Python functions.
🌐
Jython
jython.org › jython-old-sites › docs › library › inspect.html
26.10. inspect — Inspect live objects — Jython v2.5.2 documentation
For Python implementations without such types, this method will always return False. New in version 2.5. ... Get the documentation string for an object, cleaned up with cleandoc(). ... Return in a single string any lines of comments immediately preceding the object’s source code (for a class, function, or method), or at the top of the Python source file (if the object is a module).
🌐
GitHub
github.com › python › cpython › blob › main › Lib › inspect.py
cpython/Lib/inspect.py at main · python/cpython
"""Get useful information from live Python objects. · This module encapsulates the interface provided by the internal special · attributes (co_*, im_*, tb_*, etc.) in a friendlier fashion. It also provides some help for examining source code and class layout. · Here are some of the useful functions provided by this module: ·
Author   python
🌐
LabEx
labex.io › tutorials › inspect-the-internals-of-functions-132511
Python - Inspect the Internals of Functions
Explore function attributes, use the inspect module, and apply function inspection in classes to understand the internals of Python functions.