Accessing Python source code and bytecode
Display the bytecode of a function
The Python interpreter compiles code to bytecode before executing it on the Python's virtual machine (see also What is python bytecode?.
Here's how to view the bytecode of a Python function
Display the source code of an object
Objects that are not built-in
To print the source code of a Python object use
inspect. Note that this won't work for built-in objects nor for objects defined interactively. For these you will need other methods explained later.
Here's how to print the source code of the method
randint from the
To just print the documentation string
Print full path of the file where the method
random.randint is defined:
Objects defined interactively
If an object is defined interactively
inspect cannot provide the source code but you can use
The source code for Python's built-in functions is written in c and can only be accessed by looking at the Python's source code (hosted on Mercurial or downloadable from https://www.python.org/downloads/source/).
Exploring the code object of a function
CPython allows access to the code object for a function object.
__code__object contains the raw bytecode (
co_code) of the function as well as other information such as constants and variable names.