Python Glossary Русский

all Python 3inspectfunction

inspect.getfile()

source code

The name of the file where a module, class or function was defined. Raises TypeError for built-in objects.

Syntax

inspect.getfile(object)

It takes the name from the object's attributes and never checks that the file exists: code from exec() gives '<string>', an extension module gives a .so or .pyd path. Built-in modules like sys, functions like len and classes like int raise TypeError rather than returning None. When you need a readable .py, use getsourcefile(), which returns None if there is no source. The path is absolute and machine-specific.

Examples

import importlib, inspect, pathlib, sys
pathlib.Path('shapes.py').write_text('def area(r):\n    return 3.14 * r * r\n',
                                     encoding='utf-8')
sys.path.insert(0, '.')
importlib.invalidate_caches()
import shapes
print(inspect.getfile(shapes.area))  # → ? полный путь к shapes.py
print(pathlib.Path(inspect.getfile(shapes.area)).name)  # → shapes.py
import inspect, sys
namespace = {}
exec('def dyn(): pass', namespace)
print(inspect.getfile(namespace['dyn']))  # → <string> — файла нет, ошибки тоже
try:
    inspect.getfile(sys)
except TypeError as e:
    print(e)  # → <module 'sys' (built-in)> is a built-in module

See also

Open in the full glossarydocs.python.orgReport an inaccuracy