Python Glossary Русский

all Python 3inspectfunction

inspect.getsourcelines()

source code

Returns a pair: the list of the object's source lines (with line endings) and the number of its first line in the file.

Syntax

inspect.getsourcelines(object) -> tuple[list[str], int]

Line numbers start at 1, while a module gets 0, which is how the function marks the whole file. The lines already contain '\n', so print them with ''.join(), not '\n'.join(), or blank lines appear. The first line of a decorated function is the decorator line, and like getsource() it follows __wrapped__. The errors are the same: OSError without a file and TypeError for built-in objects. The undocumented getlineno and indentsize are its internal helpers.

Examples

import inspect, sys
def area(w, h):
    return w * h
lines, start = inspect.getsourcelines(area)
print(start, len(lines))  # → 2 2
print(lines[0], end='')  # → def area(w, h):
print(inspect.getsourcelines(sys.modules[__name__])[1])  # → 0

See also

Common errors

Open in the full glossarydocs.python.orgReport an inaccuracy