Python Glossary Русский

all Python 3inspectfunction

inspect.getsource()

source code

Returns the source text of a module, class, function or method as one string, reading the file the object was loaded from.

Syntax

inspect.getsource(object) -> str

The source is read from the file at call time, so there is none in the REPL, in exec() or for C functions: OSError 'could not get source code', or TypeError for built-ins. For a decorated function getsource follows __wrapped__ and shows the original function with its decorator line, not the wrapper's code. A lambda comes back as the whole line it sits on, and a file edited after import shows the new text, not the running one. Under the hood getsource uses the undocumented helpers findsource, getblock and BlockFinder; do not rely on them.

Examples

import functools, inspect
def logged(fn):
    @functools.wraps(fn)
    def wrapper(*args):
        return fn(*args)
    return wrapper
@logged
def total(xs):
    return sum(xs)
print(inspect.getsource(total), end='')  # → @logged / def total(xs): / return sum(xs)
import inspect
ns = {}
exec('def z():\n    return 1\n', ns)
try:
    inspect.getsource(ns['z'])
except OSError as e:
    print(e)  # → could not get source code
try:
    inspect.getsource(len)
except TypeError as e:
    print(type(e).__name__)  # → TypeError

See also

Common errors

Open in the full glossarydocs.python.orgReport an inaccuracy