Python Introspection: hasattr, Class Metadata, and Attribute Lookup
Introduction
Python introspection reveals an object’s type, directly stored state, and reachable attributes. Those are different views: hasattr(plugin, "run") may find an inherited method that is absent from plugin.__dict__. A successful lookup also does not prove that a method can be called with a particular signature.
This lesson covers objective 4.4 and the dictionary inspection in 4.2 of PCAP-31-03 Object-Oriented Programming (34% of the score, 12 of 40 items). You will read class metadata, compare hasattr with getattr, and keep lookup failures separate from errors inside a method.
Learning objectives
After this lesson you can:
- Use
hasattr()to test for an attribute, and predict its result for instance variables, class variables, methods and missing names. - Read and explain
__name__,__module__and__bases__on classes. - Explain which of these attributes can be read through an instance and which cannot.
- Use
type(),obj.__class__andisinstance()to find the class of an object. - Use
getattr()andsetattr()for dynamic attribute access, and__dict__to confirm results. - Write a diagnostic function that reports the capabilities of an object without assuming its shape.
hasattr(): does the attribute exist?
hasattr(obj, "name") performs an attribute lookup. It returns True if the lookup succeeds and False if it raises AttributeError. Other exceptions propagate. Properties and custom lookup hooks can execute code during this operation. The attribute name is given as a string.
class Plugin:
version = "1.0"
def __init__(self, label):
self.label = label
def run(self):
return f"{self.label} running"
p = Plugin("exporter")
print(hasattr(p, "label")) # True, instance variable
print(hasattr(p, "version")) # True, class variable seen through the instance
print(hasattr(p, "run")) # True, methods are attributes too
print(hasattr(p, "stop")) # False, does not exist
print(hasattr(Plugin, "label")) # False, instance variables are not on the class
print(hasattr(Plugin, "run")) # TrueFor these plain attributes, hasattr finds instance values or class attributes through the MRO. More generally it uses normal attribute access, including descriptors and custom hooks. This is why the instance reports version although it was never assigned on the instance, and why the class does not report label, which only exists once an object has been initialised.
Two details are often tested:
- The name must be a string:
hasattr(p, label)without quotes would use the value of the variablelabel, andhasattr(p, 5)raisesTypeError. hasattrtests existence, not usefulness. It returnsTruefor an attribute whose value isNone,0or an empty string.
p.cache = None
print(hasattr(p, "cache")) # True
print(bool(p.cache)) # FalseAttributes added dynamically
Attributes are created by assignment, so hasattr can change its answer during the run:
q = Plugin("importer")
print(hasattr(q, "debug")) # False
q.debug = True
print(hasattr(q, "debug")) # True
del q.debug
print(hasattr(q, "debug")) # FalseThis is the reason to test before reading when objects of the same class might not all have the same attributes.
Related built-ins: getattr, setattr, delattr
Reading and writing by string name is the natural companion of hasattr.
| Call | Meaning | If the attribute is missing |
|---|---|---|
getattr(obj, "x") |
Same as obj.x |
AttributeError |
getattr(obj, "x", default) |
Value or default |
Returns default |
setattr(obj, "x", v) |
Same as obj.x = v |
Creates it only if the object permits that assignment |
delattr(obj, "x") |
Same as del obj.x |
AttributeError |
hasattr(obj, "x") |
Tests existence | Returns False |
print(getattr(p, "label")) # exporter
print(getattr(p, "timeout", 30)) # 30
setattr(p, "timeout", 45)
print(p.timeout) # 45
print(getattr(p, "run")()) # exporter runningThe last line fetches the bound method as a value and calls it, the technique behind plugin systems and command dispatch: getattr(handler, "on_" + event).
The identity of a class: __name__, __module__, __bases__
Classes carry descriptive metadata. The table describes the ordinary user-defined classes shown here. An instance can have an explicitly assigned __name__, and types using __slots__ may lack an instance dictionary; the names are not universally forbidden or available on every instance.
| Attribute | What it contains | Available on the class | Available on an instance |
|---|---|---|---|
__name__ |
The name of the class as a string | yes | no |
__module__ |
The name of the module where the class was defined | yes | yes (found through the class) |
__bases__ |
A tuple of the direct parent classes | yes | no |
__class__ |
The class of the object | yes: its metaclass, normally type |
yes |
__dict__ |
The attributes stored in the object or class | yes | yes |
print(Plugin.__name__) # Plugin
print(Plugin.__module__) # __main__
print(Plugin.__bases__) # (<class 'object'>,)
print(p.__class__) # <class '__main__.Plugin'>
print(p.__class__.__name__) # Plugin
print(p.__module__) # __main__Three points need care.
The class name is metadata on the class object. In this example p.__name__ raises AttributeError: the class name is supplied through type rather than an ordinary Plugin.__dict__ entry inherited by p. To get the name from an instance, go through its class: type(p).__name__ or p.__class__.__name__.
__module__ shows where the class was defined. When the file is run directly, the module is called "__main__". If the same class is imported from a file called plugins.py, the value is "plugins". Because instances find __module__ through their class, p.__module__ works.
__bases__ is a tuple. A class that names no parent derives from object, so you see (<class 'object'>,). With explicit parents you see them in the order written:
class Reader:
pass
class Writer:
pass
class Pipe(Reader, Writer):
pass
print(Pipe.__bases__)
# (<class '__main__.Reader'>, <class '__main__.Writer'>)
print(Reader.__bases__)
# (<class 'object'>,)
print([b.__name__ for b in Pipe.__bases__]) # ['Reader', 'Writer']__bases__ lists only the direct parents. It does not include grandparents; chapter 10 explains how to see the whole chain.
Finding the class of an object
Three tools answer the question "what is this object?", with slightly different meaning.
print(type(p)) # <class '__main__.Plugin'>
print(type(p) is Plugin) # True
print(isinstance(p, Plugin)) # True
print(isinstance(p, object)) # True, everything derives from object
print(isinstance(5, (int, float))) # True, a tuple means "any of these"type(obj) returns the exact class. isinstance(obj, Class) is True for the class and for any class derived from it, which makes it the right choice for validating input. issubclass(Child, Parent) asks the same question about two classes. Inheritance examples in the next chapter contrast type(x) is Parent (false for a child) with isinstance(x, Parent) (true).
Instances versus classes: what each one holds
A frequent exam trap is to ask for an attribute at the wrong level. Compare what the instance dictionary and the class dictionary contain:
print(sorted(p.__dict__)) # ['cache', 'label', 'timeout']
print("version" in Plugin.__dict__) # True
print("label" in Plugin.__dict__) # False
print("run" in Plugin.__dict__) # TrueThe instance dictionary holds the values assigned on this object. The class dictionary holds methods and class variables. hasattr(p, "version") is True although "version" is not in p.__dict__: hasattr follows the lookup chain, whereas __dict__ shows only one level.
| Question | Tool | Looks at |
|---|---|---|
Does this lookup avoid AttributeError? |
hasattr(obj, "x") |
normal lookup, including descriptors and hooks |
Is x stored directly in this object? |
"x" in obj.__dict__ |
instance only |
Is x defined in this class itself? |
"x" in Cls.__dict__ |
that class only |
| What class is this object? | type(obj) or obj.__class__ |
exact class |
| Is it this class or a child? | isinstance(obj, Cls) |
class tree |
Listing what an object offers
__dict__ shows one level, and hasattr answers one name at a time. Two more built-ins help when you want a wider view, although they are less central to the syllabus.
class Sensor:
unit = "C"
def __init__(self, ident):
self.ident = ident
def read(self):
return 21.5
s = Sensor("T-1")
print(vars(s)) # {'ident': 'T-1'}, same as s.__dict__
names = [n for n in dir(s) if not n.startswith("__")]
print(names) # ['ident', 'read', 'unit']vars(obj) returns obj.__dict__ when available and otherwise raises TypeError. dir(obj) normally collects names from the instance, class, and bases, but a custom __dir__ can change the list. This example includes special names, which is why the example filters the ones that start with two underscores. The result mixes data and methods, so dir is a tool for exploring in a console rather than for program logic. For logic, hasattr and getattr are more precise.
A common use is to separate the data from the behaviour of an object:
data = {}
for name in dir(s):
if name.startswith("__"):
continue
value = getattr(s, name)
if not callable(value):
data[name] = value
print(data) # {'ident': 'T-1', 'unit': 'C'}Here callable excludes the bound method read, and the inherited class variable unit is included although it is absent from vars(s). Each attribute is read once, which matters if a property computes a result. This is an exploration example, not a passive inspection guarantee for arbitrary objects. Reading the two outputs side by side is a good way to check that you understand the difference between "stored in the object" and "reachable from the object".
Missing attributes and precise diagnostics
When an interface accepts objects with optional capabilities, define which missing attributes are normal and which errors should propagate. See choosing a precise exception handler for the importance of that boundary. Compare two strategies:
Look before you leap, using hasattr:
def describe(obj):
if hasattr(obj, "run"):
return f"{type(obj).__name__} can run"
return f"{type(obj).__name__} cannot run"Ask forgiveness, using the exceptions you learned in chapter 4:
def start(obj):
try:
return obj.run()
except AttributeError:
return "no run capability"The second form has a subtle weakness: an AttributeError raised inside run() for an unrelated reason is swallowed and reported as "no run capability". For a precise invocation boundary, fetch the attribute once inside a narrow try, then call it outside. This propagates errors raised by the method body. Lookup can itself raise AttributeError through a descriptor, so define that case as unavailable under this interface contract:
def start(obj):
try:
run = getattr(obj, "run")
except AttributeError:
return "no run capability"
if not callable(run):
raise TypeError("run must be callable")
return run()See bound Python methods for why the fetched value can retain an instance. callable(run) does not validate its argument signature.
Worked example: a capability report for plugins
Statement. A monitoring tool loads objects from several modules. Each should offer name, run() and optionally stop(). Write the output of the program below and explain each line.
class Base:
kind = "generic"
def __init__(self, name):
self.name = name
def run(self):
return f"{self.name} run"
class Worker(Base):
def stop(self):
return f"{self.name} stop"
class Broken:
pass
def report(obj):
cls = type(obj)
lines = [cls.__name__ + " <- " + ", ".join(b.__name__ for b in cls.__bases__)]
for attr in ("name", "kind", "run", "stop"):
lines.append(f"{attr}: {hasattr(obj, attr)}")
return lines
for item in (Worker("w1"), Base("b1"), Broken()):
print(*report(item), sep=" | ")Step 1: what report computes. For each object it takes the class, builds a first line with the class name and the names of its direct bases, then tests four attributes with hasattr.
Step 2: Worker("w1"). The class is Worker, whose base is Base. name exists on the instance, kind and run are found on Base through inheritance, and stop is defined in Worker: all four are True.
Step 3: Base("b1"). Its base is object. name, kind and run exist; stop does not.
Step 4: Broken(). The class has no parent written, so the base is object. Nothing is found: all four tests are False.
Worker <- Base | name: True | kind: True | run: True | stop: True
Base <- object | name: True | kind: True | run: True | stop: False
Broken <- object | name: False | kind: False | run: False | stop: FalseWhy other readings fail. Expecting kind: False for Worker forgets that hasattr follows inheritance and not only the instance dictionary. Expecting Worker <- object mistakes the full ancestry for the direct bases. Using obj.__name__ inside report instead of type(obj).__name__ would raise AttributeError on the first object, because instances do not have __name__.
Common pitfalls and exam tips
| Pitfall | What happens | Remedy |
|---|---|---|
instance.__name__ |
AttributeError |
Use type(instance).__name__ |
instance.__bases__ |
AttributeError |
Use type(instance).__bases__ |
hasattr(obj, name) with an unquoted name |
Uses the variable's value, or NameError |
The attribute name is a string |
Expecting hasattr(Class, "attr") to be true for instance variables |
They exist only after __init__ ran |
Test on an instance |
Treating __bases__ as the full ancestry |
Only direct parents are shown | Remember the word "direct" |
Catching AttributeError around a method body |
Can hide an internal failure | Fetch the method in a narrow block, then invoke outside it |
Reading __module__ as the file name |
It is the module name, __main__ for a script |
Know both values |
Exam tip. For the plain classes shown here, class metadata and instance storage answer different questions. Check for custom attributes, metaclasses, or missing __dict__ before generalizing the table.
Exam tip. The string printed by print(SomeClass) has the shape <class 'module.ClassName'>; the module is __main__ in a standalone script.
Exam tip. hasattr returns True for methods, class variables, instance variables and inherited attributes. It returns False on AttributeError; a different lookup exception propagates.
End-of-lesson case study
Situation. A data-export tool accepts "exporter" objects. A colleague wrote the logging portion of a function intended to process exporters. It logs a class name and whether export can be retrieved. Predict the output and say what is wrong with the logging.
class CsvExporter:
def export(self):
return "csv"
class NullExporter:
pass
def run_all(items):
for obj in items:
print(obj.__name__, hasattr(obj, "export"))
run_all([CsvExporter(), NullExporter(), CsvExporter])Solution, commented. The first loop iteration receives an instance of CsvExporter. obj.__name__ raises AttributeError immediately, because these instances have no __name__ attribute, so nothing is printed and the program stops. The author mixed up instances and classes. The third list element is a class, not an instance, and for it __name__ would work: it would print CsvExporter True, since hasattr(CsvExporter, "export") is True for the function stored on the class.
The corrected function should use the class of the object: print(type(obj).__name__, hasattr(obj, "export")). For the list above it prints CsvExporter True, NullExporter False, then, for the third element, the class itself: type(CsvExporter).__name__ is type, so the third line is type True. If the function is meant to accept classes as well, it can test isinstance(obj, type) and choose obj.__name__ in that case.
Key terms
- Introspection: examining the type and content of objects while the program runs.
hasattr(obj, "name"): returnsTrueif the attribute can be read.- Class
__name__: class-name metadata; usetype(instance).__name__to retrieve it from an instance. __module__: the name of the module where the class was defined.__bases__: the tuple of direct parent classes.__class__/type(): the class of an object.isinstance(): tests membership of an object in a class or its descendants.getattr/setattr: read and write attributes by string name.
Summary checklist
- I can predict
hasattrfor instance variables, class variables, methods and missing names. - I know
__name__and__bases__are read from classes, not from instances. - I can obtain a class name from an instance with
type(obj).__name__. - I know
__module__is"__main__"in a standalone script. - I know
__bases__is a tuple of the direct parents. - I can use
getattr,setattrand__dict__to confirm where data lives. - I prefer a precise test over a broad
except AttributeError.
Official sources
-
Python Institute, PCAP-31-03 exam syllabus (objective 4.4): https://pythoninstitute.org/pcap-31-03-exam-syllabus (opens in a new tab)
-
Python documentation, built-in functions (
hasattr,getattr,isinstance,type): https://docs.python.org/3.14/library/functions.html (opens in a new tab) -
Python documentation, special attributes of classes: https://docs.python.org/3.14/reference/datamodel.html (opens in a new tab)
-
Descriptor behavior during introspection: https://docs.python.org/3.14/howto/descriptor.html (opens in a new tab)
