Display the source code of an object

suggest change

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 random module:

import random
import inspect

print(inspect.getsource(random.randint)) 
# Output:
#    def randint(self, a, b):
#        """Return random integer in range [a, b], including both end points.
#        """
#
#        return self.randrange(a, b+1)

To just print the documentation string

print(inspect.getdoc(random.randint))
# Output:
# Return random integer in range [a, b], including both end points.

Print full path of the file where the method random.randint is defined:

print(inspect.getfile(random.randint))
# c:\Python35\lib\random.py
print(random.randint.__code__.co_filename) # equivalent to the above
# c:\Python35\lib\random.py

Objects defined interactively

If an object is defined interactively inspect cannot provide the source code but you can use dill.source.getsource instead

# define a new function in the interactive shell
def add(a, b):
   return a + b
print(add.__code__.co_filename) # Output: <stdin> 

import dill
print dill.source.getsource(add)
# def add(a, b):
      return a + b

Built-in objects

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/).

print(inspect.getsource(sorted)) # raises a TypeError
type(sorted) # <class 'builtin_function_or_method'>

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


Accessing Python source code and bytecode:
* Display the source code of an object

Table Of Contents
2 Filter
3 List
7 Loops
22 Reduce
27 Classes
31 Set
42 Tuple
45 Enum
62 Sockets
89 urllib
92 Idioms
104 Stack
105 Profiling
109 Logging
111 os module
117 Accessing Python source code and bytecode
118 Mixins
120 ArcPy
126 Arrays
132 2to3 tool
135 Unicode
138 Neo4j
140 Curses
141 Templates
145 heapq
146 tkinter
154 Audio
155 pyglet
157 ijson
160 Flask
161 Groupby
163 pygame
165 hashlib
166 Gzip
167 ctypes
185 pyaudio
186 shelve