Python introspection
last modified November 16, 2026 Python 3.15
In this article we show how to do introspection in Python.
Introspection is the ability of a program to examine the type and
the properties of objects at run time. Everything in Python is an object:
numbers, strings, functions, classes, and modules. Every object has a type,
an identity, and attributes, and Python lets us query all of them. The basic
tools are built-in functions such as dir, type,
isinstance, getattr, and vars; the
inspect module adds functions for signatures, members, source
code, and stack frames.
Introspection is used by debuggers, test frameworks, serializers, dependency injection containers, and command line parsers that build their interface from function signatures.
The dir function
The dir function returns a sorted list of the attribute names of
an object. The list includes many special dunder names such as
__init__ or __len__, so we usually filter them out.
class User:
def __init__(self, name):
self.name = name
def greet(self):
return f'Hello, {self.name}'
u = User('Lucy')
print([a for a in dir(u) if not a.startswith('__')])
print([a for a in dir(()) if not a.startswith('__')])
print([a for a in dir(str) if not a.startswith('_')][:10])
print(len(dir(str)))
We list the attributes of a custom object, a tuple, and the str
class.
print([a for a in dir(u) if not a.startswith('__')])
The list of a User instance contains both the
name instance attribute and the greet method, which
is defined in the class.
print(len(dir(str)))
Including the dunder names, the str class has 81 attributes.
$ python dir_fun.py ['greet', 'name'] ['count', 'index'] ['capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map'] 81
The names in the current scope
Without arguments, dir returns the names in the current local
scope.
print(dir())
import math
x = 10
print(dir())
def demo(a, b=2):
c = a + b
print(dir())
demo(1)
At the module level, we first see only the names that Python defines for
every module. After the import and the assignment, the math
and x names are added. Inside a function, dir
returns the local variables, including the parameters.
$ python dir_scope.py ['__builtins__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__'] ['__builtins__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'math', 'x'] ['a', 'b', 'c']
The type function
The type function returns the type of an object. The type is
itself an object; classes are instances of type.
import sys
def function():
pass
class User:
pass
u = User()
values = [1, 1.5, 'abc', [], {}, (), {1}, None, function, len, User, u, sys,
type]
for v in values:
print(type(v))
The example prints the types of various objects. Functions written in Python
have the function type, while built-in functions such as
len are of the builtin_function_or_method type. Both
the User class and type itself are instances of
type.
$ python type_fun.py <class 'int'> <class 'float'> <class 'str'> <class 'list'> <class 'dict'> <class 'tuple'> <class 'set'> <class 'NoneType'> <class 'function'> <class 'builtin_function_or_method'> <class 'type'> <class '__main__.User'> <class 'module'> <class 'type'>
isinstance and issubclass
The isinstance function checks if an object is an instance of a
class or of any of its subclasses. The issubclass function does
the same check for two classes.
class Animal:
pass
class Dog(Animal):
pass
d = Dog()
print(type(d) is Dog)
print(type(d) is Animal)
print(isinstance(d, Animal))
print(isinstance(d, (int, Dog)))
print(isinstance(True, int), type(True) is int)
print(issubclass(Dog, Animal), issubclass(Animal, Dog))
print(issubclass(Dog, Dog))
print(Dog.__mro__)
print(Dog.__bases__, Animal.__subclasses__())
Comparing types with type(d) is Dog ignores inheritance, so it
is usually better to use isinstance. The second argument may be a
tuple of classes. Note that bool is a subclass of
int, so isinstance(True, int) is true.
print(Dog.__mro__) print(Dog.__bases__, Animal.__subclasses__())
The __mro__ attribute holds the method resolution order, the
sequence of classes searched for attributes. The __bases__
attribute contains the direct base classes, and the
__subclasses__ method returns the direct subclasses.
$ python type_vs_isinstance.py True False True True True False True False True (<class '__main__.Dog'>, <class '__main__.Animal'>, <class 'object'>) (<class '__main__.Animal'>,) [<class '__main__.Dog'>]
The id function
The id function returns the identity of an object, an integer
that is unique among the objects alive at the same time. In CPython, it is the
memory address of the object. The is operator compares
identities.
a = [1, 2, 3]
b = a
c = [1, 2, 3]
print(id(a) == id(b), a is b)
print(id(a) == id(c), a is c)
print(a == c)
b.append(4)
print(a, c)
for n in ('100', '1000', '5000'):
print(n, int(n) is int(n), int(n) == int(n))
The a and b variables refer to the same list, so a
change made through b is visible through a. The
c list is equal to a but it is a different object.
for n in ('100', '1000', '5000'):
print(n, int(n) is int(n), int(n) == int(n))
CPython keeps a cache of small integers, so the same number may be one shared
object. The cached range is an implementation detail: it was -5 to 256 up to
Python 3.14 and is -5 to 1024 in Python 3.15. Numbers must always be compared
with ==, never with is.
$ python id_fun.py True True False False True [1, 2, 3, 4] [1, 2, 3] 100 True True 1000 True True 5000 False True
Reading and setting attributes
The hasattr, getattr, setattr, and
delattr functions work with attributes whose names are known only
at run time, as strings.
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
p = Point(3, 4)
print(hasattr(p, 'x'), hasattr(p, 'z'))
print(getattr(p, 'y'))
print(getattr(p, 'z', 0))
setattr(p, 'z', 5)
print(p.z)
delattr(p, 'z')
print(hasattr(p, 'z'))
for name in ('x', 'y'):
print(name, getattr(p, name))
try:
getattr(p, 'w')
except AttributeError as e:
print(e)
The getattr function takes an optional default value, which is
returned instead of raising AttributeError when the attribute
does not exist. The loop reads attributes by their names, which is how
generic code such as serializers accesses fields.
$ python attrs.py True False 4 0 5 False x 3 y 4 'Point' object has no attribute 'w'
The vars function and __dict__
Instance attributes are normally stored in a dictionary, available as the
__dict__ attribute. The vars function returns this
dictionary.
class Point:
dims = 2
def __init__(self, x, y):
self.x = x
self.y = y
class Slotted:
__slots__ = ('x', 'y')
def __init__(self, x, y):
self.x = x
self.y = y
p = Point(3, 4)
print(vars(p))
print(p.__dict__ is vars(p))
print('dims' in vars(p), 'dims' in vars(Point))
p.__dict__['x'] = 10
print(p.x)
s = Slotted(1, 2)
print(hasattr(s, '__dict__'))
print(Slotted.__slots__)
try:
vars(s)
except TypeError as e:
print(e)
The vars(p) call returns the instance dictionary itself, not a
copy, so writing to it changes the object. Class attributes such as
dims live in the class dictionary, not in the instance one.
class Slotted:
__slots__ = ('x', 'y')
A class with __slots__ stores its attributes in fixed slots and
its instances have no __dict__, so vars fails.
$ python vars_fun.py
{'x': 3, 'y': 4}
True
False True
10
False
('x', 'y')
vars() argument must have __dict__ attribute
The callable function
The callable function checks if an object can be called.
Functions, methods, and classes are callable, and so are instances of classes
that define the __call__ method.
class Car:
def set_name(self, name):
self.name = name
class Counter:
def __init__(self):
self.n = 0
def __call__(self):
self.n += 1
return self.n
def fun():
pass
c = Car()
counter = Counter()
print(callable(fun), callable(c.set_name), callable(Car))
print(callable(counter), counter(), counter())
print(callable([]), callable(1), callable(c))
The Counter instance is callable because its class defines
__call__; each call increments the counter. A Car
instance, a list, and a number are not callable.
$ python callable_fun.py True True True True 1 2 False False False
Names, qualified names, and modules
Functions, classes, and modules have a __name__ attribute.
Functions and classes also have __qualname__, the dotted path
from the module level, and __module__, the name of the module in
which they were defined.
import json
class Shop:
class Item:
def price(self):
return 0
def outer():
def inner():
pass
return inner
for obj in (len, json, json.dumps, Shop, Shop.Item, Shop.Item.price, outer(),
lambda: 0):
print(obj.__name__, '|', getattr(obj, '__qualname__', '-'), '|',
getattr(obj, '__module__', '-'))
The qualified name shows where a nested class, a method, or a local function
was defined. Modules have no __qualname__, so we use
getattr with a default value.
$ python names.py len | len | builtins json | - | - dumps | dumps | json Shop | Shop | __main__ Item | Shop.Item | __main__ price | Shop.Item.price | __main__ inner | outer.<locals>.inner | __main__ <lambda> | <lambda> | __main__
Documentation strings
A string literal at the start of a function, class, or module body becomes its
docstring, stored in the __doc__ attribute.
import inspect
def area(width, height):
"""Return the area of a rectangle.
Both sides are given in metres.
"""
return width * height
def noop():
pass
print(repr(area.__doc__))
print(inspect.getdoc(area))
print(noop.__doc__)
print(len.__doc__)
Since Python 3.13, the compiler removes the common leading indentation from
docstrings, so __doc__ no longer contains the indentation of the
function body. The inspect.getdoc function also strips the
leading and trailing blank lines. A function without a docstring has
None in __doc__.
$ python docs.py 'Return the area of a rectangle.\n\nBoth sides are given in metres.\n' Return the area of a rectangle. Both sides are given in metres. None Return the number of items in a container.
The sys module
The sys module gives access to the interpreter: its version,
platform, search path, limits, and loaded modules.
import sys
print(sys.version_info)
print(sys.version_info >= (3, 14))
print(sys.implementation.name, sys.implementation.cache_tag)
print(sys.platform, sys.byteorder)
print(sys.executable)
print(sys.argv)
print(sys.path[0])
print(sys.maxsize == 2 ** 63 - 1)
print(sys.getrecursionlimit())
print(sys.getsizeof(0), sys.getsizeof(2 ** 100), sys.getsizeof([]))
print('json' in sys.modules)
import json
print('json' in sys.modules)
The version_info tuple can be compared with tuples to check the
interpreter version. The executable attribute holds the path to
the interpreter, argv the command line arguments, and
path[0] the directory of the script.
print(sys.getsizeof(0), sys.getsizeof(2 ** 100), sys.getsizeof([]))
The getsizeof function returns the size of an object in bytes.
It does not count the objects referenced by a container.
print('json' in sys.modules)
import json
print('json' in sys.modules)
The sys.modules dictionary maps the names of the imported modules
to the module objects.
$ python sys_info.py sys.version_info(major=3, minor=15, micro=2, releaselevel='final', serial=0) True cpython cpython-315 linux little /home/user/.local/bin/python3.15 ['sys_info.py'] /home/user/python True 1000 28 40 56 False True
Function signatures
The inspect.signature function returns a Signature
object describing the parameters and the return annotation of a callable.
import inspect
def connect(host, port=5432, *args, timeout: float = 3.0, **opts) -> bool:
return True
sig = inspect.signature(connect)
print(sig)
print(sig.return_annotation)
for p in sig.parameters.values():
print(f'{p.name:8} {p.kind.name:22} {p.default!r}')
ba = sig.bind('db.local', timeout=5)
ba.apply_defaults()
print(ba.arguments)
try:
sig.bind(port=1)
except TypeError as e:
print(e)
We print the signature, the return annotation, and the name, kind, and default
value of each parameter. Parameters without a default have the special
inspect.Parameter.empty value.
ba = sig.bind('db.local', timeout=5)
ba.apply_defaults()
print(ba.arguments)
The bind method maps arguments to parameters the way a real call
would, without calling the function. It raises TypeError when
the arguments do not match the signature.
$ python signature.py
(host, port=5432, *args, timeout: float = 3.0, **opts) -> bool
<class 'bool'>
host POSITIONAL_OR_KEYWORD <class 'inspect._empty'>
port POSITIONAL_OR_KEYWORD 5432
args VAR_POSITIONAL <class 'inspect._empty'>
timeout KEYWORD_ONLY 3.0
opts VAR_KEYWORD <class 'inspect._empty'>
{'host': 'db.local', 'port': 5432, 'args': (), 'timeout': 5, 'opts': {}}
missing a required argument: 'host'
Inspecting members
The inspect.getmembers function returns the
(name, value) pairs of an object's attributes, optionally
filtered by a predicate such as inspect.ismethod or
inspect.isfunction.
import inspect
class Account:
rate = 0.02
def __init__(self, owner, balance=0):
self.owner = owner
self.balance = balance
def deposit(self, amount):
self.balance += amount
@classmethod
def empty(cls, owner):
return cls(owner)
@staticmethod
def check(amount):
return amount > 0
@property
def interest(self):
return self.balance * self.rate
acc = Account('Paul', 100)
print([n for n, _ in inspect.getmembers(acc, inspect.ismethod)])
print([n for n, _ in inspect.getmembers(Account, inspect.isfunction)])
for name in ('rate', 'deposit', 'empty', 'check', 'interest'):
print(f'{name:9} {type(inspect.getattr_static(Account, name)).__name__}')
print(inspect.isclass(Account), inspect.isfunction(Account.deposit))
print(inspect.ismethod(acc.deposit), inspect.ismodule(inspect))
On an instance, methods and class methods are bound methods. On the class, regular methods and static methods are plain functions.
for name in ('rate', 'deposit', 'empty', 'check', 'interest'):
print(f'{name:9} {type(inspect.getattr_static(Account, name)).__name__}')
The getattr_static function reads an attribute without running
descriptors, so we see the classmethod,
staticmethod, and property objects as they are
stored in the class.
$ python members.py ['__init__', 'deposit', 'empty'] ['__init__', 'check', 'deposit'] rate float deposit function empty classmethod check staticmethod interest property True True True True
Source code
The inspect.getsource function returns the source code of a
function, class, or module, and getsourcefile returns the file
it was loaded from.
import inspect
import json
def square(x):
return x * x
print(inspect.getsource(square), end='')
print(inspect.getsourcefile(json.dumps))
lines, start = inspect.getsourcelines(json.dumps)
print(start, lines[0].strip())
try:
inspect.getsource(len)
except TypeError as e:
print(e)
We print the source of our own function and locate the json.dumps
function in the standard library. Built-in functions written in C, such as
len, have no Python source.
$ python source.py
def square(x):
return x * x
/usr/lib/python3.15/json/__init__.py
184 def dumps(obj, *, skipkeys=False, ensure_ascii=True, check_circular=True,
module, class, method, function, traceback, frame, or code object was expected, got builtin_function_or_method
Stack frames
The inspect.stack and inspect.currentframe functions
give access to the frames of the call stack, so a function can find out who
called it.
import inspect
def log(msg):
caller = inspect.stack()[1]
print(f'{caller.function}:{caller.lineno}: {msg}')
def show_locals():
frame = inspect.currentframe().f_back
print(frame.f_code.co_name, frame.f_locals)
def process(data):
total = sum(data)
log('processing')
show_locals()
return total
process([1, 2, 3])
The log function reads the name of the calling function and the
line number of the call from the frame at index 1 of the stack. The
show_locals function reads the local variables of its caller
through f_back. Logging libraries use this technique to report
where a message came from.
$ python frames.py
process:16: processing
process {'data': [1, 2, 3], 'total': 6}
Annotations
Since Python 3.14, annotations are evaluated lazily, only when they are
requested. The annotationlib module reads them in different
formats; inspect.get_annotations is a wrapper of
annotationlib.get_annotations.
import annotationlib
import inspect
class Position:
x: int
y: int
def move(dx: int, dy: int) -> 'Position':
pass
def later(p: Undefined) -> None:
pass
print(inspect.get_annotations(Position))
print(annotationlib.get_annotations(move))
try:
annotationlib.get_annotations(later)
except NameError as e:
print(e)
ann = annotationlib.get_annotations(later,
format=annotationlib.Format.FORWARDREF)
print(type(ann['p']).__name__, ann['p'].__forward_arg__, ann['return'])
print(annotationlib.get_annotations(later,
format=annotationlib.Format.STRING))
The later function refers to a name that does not exist. The
function is defined without errors, because the annotation is not evaluated
at that time. Requesting the annotations in the default VALUE
format raises NameError.
ann = annotationlib.get_annotations(later,
format=annotationlib.Format.FORWARDREF)
The FORWARDREF format replaces undefined names with
ForwardRef objects, and the STRING format returns
the annotations as source code strings.
$ python annotations_demo.py
{'x': <class 'int'>, 'y': <class 'int'>}
{'dx': <class 'int'>, 'dy': <class 'int'>, 'return': 'Position'}
name 'Undefined' is not defined
ForwardRef Undefined None
{'p': 'Undefined', 'return': 'None'}
Source
inspect – Inspect live objects
Built-in functions – Python documentation
annotationlib – Functionality for introspecting annotations
In this article we have examined Python objects at run time with built-in
functions and the inspect module. See also
Python modules and
Python functions.
Author
List all Python tutorials.