Lesson · Introspection & Reflection
Introspection
81 min readIntrospection
Introspection lets a program inspect types, attributes, call signatures, source metadata, and other runtime structure. It powers debuggers, serializers, frameworks, and diagnostic tools.
Learning goals
- Inspect an object's runtime class with
typeand test category membership withisinstance. - List what an object exposes with
dirand read its stored names withvars. - Fetch attributes by string with
getattr, write them withsetattr, and test presence withhasattr. - Read a callable's signature and annotations with
inspect.signatureand__annotations__. - Decide when runtime inspection belongs in a design and when it couples code to internals.
Mental model
The order is not mandatory, but it mirrors how a debugging session narrows down: identify, classify, enumerate, fetch, then inspect in detail.
Mental model
read it top to bottom
the object being inspected ↓ type(): which class is it? ↓ isinstance(): does it match this category? ↓ dir() and vars(): which names does it expose? ↓ getattr(): fetch one of those names ↓ inspect.signature(): what does that callable accept?
Core idea
Introspection means asking objects about themselves at runtime: their class, their categories, their attributes, and their call signatures. It is the machinery behind debuggers, REPLs, serializers, and frameworks, and it is also a coupling risk, because code that reads internal names breaks when those names change.
type
type normally returns an object's runtime class, but the type class is also the default metaclass that creates class objects. This dual role is central to Python's object model.
isinstance
isinstance(value, cls) answers whether a value is an instance of a class or of any class in a tuple, and it honors subclass relationships where type(value) is cls does not. It checks the runtime type only: annotations are metadata, so they never influence the result, while isinstance(True, int) is True because bool subclasses int.
dir
dir() returns a best-effort list of names available on an object or in a scope. It is primarily an interactive discovery aid rather than a strict serialization or reflection contract.
vars
vars(obj) returns the object's __dict__, mapping the names stored on that object to their values, and vars() with no argument returns the current local namespace. The mapping is the live storage, so writing to it writes the object, and types that use __slots__ or custom storage may not expose one.
getattr
getattr(obj, name) fetches an attribute whose name is a string known only at runtime, and the three-argument form getattr(obj, name, default) returns a fallback instead of raising. Missing names raise AttributeError, and the lookup runs the full attribute protocol, including properties and descriptors.
setattr
setattr(obj, name, value) assigns through a runtime name and behaves exactly like obj.name = value. It mutates the object and can fail with AttributeError on slotted classes or read-only properties, so validate the name before writing when it comes from outside the program.
hasattr
hasattr(obj, name) returns True when reading the attribute would succeed and False when the lookup raises AttributeError. Because it performs a real lookup, it triggers property code, and only AttributeError is swallowed, so a property that raises anything else makes hasattr propagate that exception.
callable
callable(obj) asks whether the object can be invoked, which is true whenever its type defines __call__; functions, classes, methods, and custom instances with __call__ all pass. It is a capability check rather than an exact type check, and it says nothing about the arguments a call accepts.
inspect
The inspect module exposes call signatures, frames, source information, members, and other runtime metadata. Frameworks use it heavily, but introspection can create coupling to implementation details.
Walkthrough
type(add)prints<class 'function'>; the function defined bydef add(a: int, b: int = 0) -> intis an ordinary object whose type and attributes are readable at runtime.inspect.signature(add)puts the parameters in declaration order, rendersbwith its default0, and includes the-> intreturn annotation, so the string reconstructs most of the def line.inspect.getmembers(add, predicate=callable)[:3]filters the function's attributes to the callable ones and keeps the first three names alphabetically;add.__annotations__returns a dict mapping"a","b", and"return"toint, which shows that annotations are stored metadata, not enforced types.- Predict before running: the exact signature string for
addand the keys you expect in__annotations__.
Experiments to try
- Call
inspect.signatureonprintand on a lambda; compare how a built-in and a user-defined function describe their parameters. - Remove the default from
band confirm the signature string drops= 0; then add*argsand watch where it lands in the display. - Print
callable(add),inspect.isfunction(add), andisinstance(add, int); state which introspection question each call answers. - Use
getattr(add, "__name__")andgetattr(add, "__call__")(1, 2); the first returns the stringadd, and the second still performs the addition.
Common mistakes
- Using
diras a stable contract: it is a best-effort list built for interactive discovery, it includes inherited names, and its ordering should never be relied on. - Trusting
hasattrto diagnose a broken property: if the getter raisesAttributeErrorinternally, the check reports False and hides the real failure. - Writing
type(x) == Cto test compatibility: exact-type equality rejects subclasses, whileisinstanceaccepts them, so use equality only when the exact type is genuinely required. - Reading the same attribute twice around a check: properties recompute on each access, so the checked value and the used value can differ; fetch once into a local name.
Practice: Easy
- Run the worked example and match each printed line to the introspection question it answers: type, signature, members, or annotations.
- Change
b's default to5and rerun; the signature string updates while__annotations__stays the same, because annotations record the annotation, not the default. - Attach a custom attribute with
setattr(add, "tag", "demo"), read it back withgetattr, and explain whydirnow lists one more name.
Practice: Medium
- Write
describe(value)that printstype(value).__name__,isinstance(value, (int, str)), andcallable(value); run it on2, on"s", and on theaddfunction, and read the three rows. - Create a class with a property whose getter raises
AttributeErroron purpose; runhasattr(instance, "value")andgetattr(instance, "value", None)and explain the False and None results using the lookup rule. - Print
varsfor a module and for an instance of a small class; identify one name that appears in both and one that appears only in the module.
Practice: Hard
- Build a
report(obj)inspector that returns a dict with the type name, a sorted subset ofdirfiltered bycallable, andinspect.signaturefor up to three callables; define what it does for objects without a signature. - Set up a failure lab with three broken expectations:
dirrelied on for ordering,hasattrhiding anAttributeErrorfrom a property, andtype(x) == Crejecting a subclass; explain each from the introspection semantics. - Design a plugin loader that validates candidates from a configuration list using
getattr(module, candidate, None)andcallable, and specify what happens for missing names and for non-callable matches.
Lesson checklist
- I can pick the right introspection tool for a question: type, category, names, one attribute, or signature.
- I can explain why
isinstanceand exact type equality answer different questions. - I can fetch an attribute by string and handle the missing case without a bare
try. - I can name one way introspection couples code to internals and a way to contain it.
Remember
Introspection gives running objects a voice: `type` and `isinstance` classify, `dir` and `vars` enumerate, `getattr` and `setattr` work with computed names, and `inspect.signature` opens up callables. The tools are strongest in diagnostic and framework code, where they read the shape of objects the author did not write, so keep those reads to what the public contract promises.
Interview angles
What is the main purpose of **type**?+
type normally returns an object's runtime class, but the type class is also the default metaclass that creates class objects. This dual role is central to Python's object model.
What should you pay attention to when using **isinstance**?+
isinstance(value, cls) answers whether a value is an instance of a class or of any class in a tuple, and it honors subclass relationships where type(value) is cls does not. It checks the runtime type only: annotations are metadata, so they never influence the result, while isinstance(True, int) is True because bool subclasses int.
How does **dir** fit into this lesson?+
dir() returns a best-effort list of names available on an object or in a scope. It is primarily an interactive discovery aid rather than a strict serialization or reflection contract.
Why can `hasattr` report False for an attribute that exists on the class?+
hasattr returns False whenever the lookup raises AttributeError, including when a property getter raises it internally. The attribute may exist and still be reported missing, so a False result is not proof of absence.