Lesson · Introspection & Reflection
Dynamic Attribute Access
75 min readDynamic Attribute Access
Dynamic attribute access uses names computed at runtime with `getattr`, `setattr`, and related tools. It is useful for plugins and adapters, but it can obscure control flow if used where ordinary attributes would be clearer.
Learning goals
- Fetch a method whose name is stored in a variable and call it with no special syntax.
- Add and update attributes with
setattrand explain how it relates to writingobj.name = value. - Read, write, and presence-check attributes through string names, and say which functions perform each operation.
- Build a small dispatcher that validates a resolved name before invoking it.
- Explain what dynamic names cost static analysis and when the trade is worth making.
Mental model
Keeping the name as data until the last possible moment preserves static readability, and each check narrows a string into a trusted capability. The earlier a bad name can be rejected, the smaller the surface the rest of the code has to defend.
Mental model
read it top to bottom
name arrives as data (config, user input, registry key) ↓ getattr(obj, name, default): resolve or fall back ↓ hasattr / callable: confirm the capability ↓ obj is used through the resolved attribute
Core idea
Dynamic attribute access treats attribute names as data: getattr, setattr, and hasattr receive strings, so lookups can be driven by configuration, plugin registries, or user input. It is the mechanism behind adapters and plugin systems, and it is also the point where typos stop failing early and start failing at runtime, so validate names before trusting them.
Reading attributes by name
Reading by name resolves a string into an attribute at runtime, usually with getattr(obj, name). The lookup follows the normal attribute protocol (instance storage, class storage, descriptors), and a missing name raises AttributeError unless a default is passed, which turns the failure into a value your code must still handle.
Writing attributes dynamically
setattr(obj, name, value) assigns through a runtime name and is exactly obj.name = value with the name computed. It mutates the object, can be refused by properties, slots, or frozen dataclasses, and gives the object a new attribute whenever its storage allows one.
Plugin-like patterns
Plugin systems often discover names dynamically and then validate that the resolved object satisfies an expected protocol. Keep discovery separate from execution and validation.
Safety and maintainability concerns
Dynamic names cost the tools that read code: search and rename cannot follow a string, and type checkers treat getattr results as unknown unless the name is a literal. Validate names against a known set before use, keep fallbacks explicit, and confine dynamic access to the boundary where foreign names enter the program.
Walkthrough
method_name = "start"keeps the method name as data;getattr(plugin, method_name)returns the same bound method thatplugin.startwould, ready to be called with no arguments.print(method())calls it and printsstarted; the call site never namesstart, which is the flexibility and the risk of resolving attributes at runtime in one line.setattr(plugin, "name", "demo")writes through the instance, andplugin.namereads the value back from the instance dictionary, since the class declares no such attribute;hasattr(plugin, "stop")returns False.- Predict before running: all three printed values, and what changes when
method_nameis set to"stop".
Experiments to try
- Change
method_nameto"stop"and read theAttributeError; then resolve with a default (getattr(plugin, method_name, None)) and handle the None path. - Build a dictionary dispatcher (
{"start": plugin.start}) and compare calling through it with calling throughgetattr; the dictionary fails withKeyErrorfor unknown names whilegetattrfails withAttributeError. - Set
method_name = "__class__"and observe thatgetattrhappily returns the class object; decide whether a plugin loader should reject names like that before use. - Use
setattr(plugin, "stop", lambda: "dynamic")and confirmhasattr(plugin, "stop")flips to True and the new attribute can be called.
Common mistakes
- Forgetting the default in
getattrwhen absence is normal: the lookup raisesAttributeError, and catching it around unrelated code hides real bugs. - Building names with f-strings without validating them (
getattr(obj, f"do_{action}")): unknown input reaches lookups you never intended, including dunder attributes when the format allows it. - Assuming
hasattrproves callability: an attribute can exist and not be callable, so follow a presence check withcallablebefore invoking. - Duplicating knowledge of attribute names across config and code: the string in a settings file and the method name in the source drift apart, and only a runtime test notices.
Practice: Easy
- Run the worked example and note the three outputs; then change
method_nameto"stop"and read the traceback line that names the missing attribute. - Add
setattr(plugin, "count", 1)and read the value back, then remove it withdel plugin.countand confirmhasattrflips to False again. - Print
getattr(plugin, "name", "missing")before anysetattrcall; the default appears, showing the one-line difference between raising and defaulting.
Practice: Medium
- Write
invoke(plugin, name)that resolves withgetattr, checkscallable, and returnsNonefor anything missing; test it with"start", with"stop", and with"name"after adding the attribute. - Build a config mapping (
{"start": "start", "legacy": "start"}) from external names to method names, resolve through it, and state why an explicit mapping beats constructing names with f-strings. - Reach the same value through
plugin.__dict__["name"]and throughgetattr(plugin, "name"); the direct lookup misses inherited and class attributes whilegetattrfinds them.
Practice: Hard
- Build a plugin dispatcher where each plugin object maps command strings to methods; resolve with
getattr, validate withcallable, reject names starting with_, and define the error contract for unknown or rejected names. - Set up a failure lab with three broken expectations: an f-string built name that reaches a dunder attribute, a twice-fetched attribute around a check, and a
setattrblocked by a property without a setter; explain each from the lookup and write rules. - Refactor a known-name function into a dynamic dispatcher and list what got shorter and what got harder to trace; keep the dynamic version only where the name genuinely arrives as data.
Lesson checklist
- I can fetch, set, and test attributes through string names and say which function performs each operation.
- I can resolve a method from a variable, call it, and handle the missing case.
- I can build a dispatcher that validates names and rejects dunder or unknown entries.
- I can explain what dynamic access costs static readability and when the trade is justified.
Remember
Dynamic attribute access makes names into data: `getattr` reads, `setattr` writes, `hasattr` probes, and the same calls that power plugin systems also remove the early feedback of literal attributes. Keep the technique at the boundary where foreign names enter, validate before invoking, and fetch each attribute once.
Interview angles
What is the main purpose of **Reading attributes by name**?+
Reading by name resolves a string into an attribute at runtime, usually with getattr(obj, name). The lookup follows the normal attribute protocol (instance storage, class storage, descriptors), and a missing name raises AttributeError unless a default is passed, which turns the failure into a value your code must still handle.
What should you pay attention to when using **Writing attributes dynamically**?+
setattr(obj, name, value) assigns through a runtime name and is exactly obj.name = value with the name computed. It mutates the object, can be refused by properties, slots, or frozen dataclasses, and gives the object a new attribute whenever its storage allows one.
How does **Plugin-like patterns** fit into this lesson?+
Plugin systems often discover names dynamically and then validate that the resolved object satisfies an expected protocol. Keep discovery separate from execution and validation.
Why is `hasattr(obj, "run")` not enough before calling `getattr(obj, "run")()`?+
Presence does not imply callability: run can hold data rather than a method, and the call then fails with TypeError. Combine the check with callable, and fetch the attribute once so the object you checked is the object you call.