Python Glossary Русский

all Python 3inspectfunction

inspect.getsourcefile()

source code

The path to the .py file where an object is defined, or None if the source cannot be found.

Syntax

inspect.getsourcefile(object) -> str | None

There are two kinds of 'no': for a built-in module or a C function you get TypeError, and for an object without a file on disk (code from exec(), a module shipped only as .pyc) a silent None. The path is absolute and depends on the machine and the virtual environment, so never compare it as a string in tests. For a package it is the path to __init__.py.

Examples

import inspect, json, sys
def f():
    pass
print(inspect.getsourcefile(f))  # → ? путь к example.py
print(inspect.getsourcefile(json).endswith('__init__.py'))  # → True
ns = {}
exec('def z(): pass', ns)
print(inspect.getsourcefile(ns['z']))  # → None
try:
    inspect.getsourcefile(sys)
except TypeError as e:
    print(e)  # → <module 'sys' (built-in)> is a built-in module

See also

Common errors

Open in the full glossarydocs.python.orgReport an inaccuracy