Read named attributes, including dotted nested attributes.
What You Will Learn
attrgetter("field") returns an attribute accessor; attrgetter("a.b") traverses nested attributes, and multiple arguments return a tuple.
Step-by-Step Example
The example below makes the behavior visible with small input values that you can change safely.
from operator import attrgetter
from types import SimpleNamespace
person = SimpleNamespace(profile=SimpleNamespace(age=28))
print(attrgetter('profile.age')(person))
How the Example Works
- The imports provide the standard-library tools used in the demonstration: operator, types.
- The variable person holds the result of SimpleNamespace(profile=SimpleNamespace(age=28)). Later lines use that value or inspect how it changes.
- The print() calls make the return values or state visible so you can compare them with the explanation and check your prediction.
For the chosen input, the expression attrgetter('profile.age')(person) prints 28. Compare that result with the rule above before you change the argument.
Expected output from the example:
28
Another Example: Compare the Results
Try a second input and compare it with the first. Notice whether the result changes in type, value, order, or number of items.
from operator import attrgetter
from types import SimpleNamespace
people = [SimpleNamespace(name="Ben"), SimpleNamespace(name="Ada")]
print([p.name for p in sorted(people, key=attrgetter("name"))])
Expected output:
['Ada', 'Ben']
When You Would Use This
These tools are useful when composing small reusable functions, adapting callbacks, or eliminating repeated work. Pay attention to whether the operation returns a new object, updates state, or produces lazy results. Test a small success case and a boundary case before integrating it into an application.
Practice: Modify the Code
Sort named objects by a status or timestamp attribute.
Verify the changed output against the behavior described above, including the relevant invalid or boundary case.
For complete parameters and version details, consult the official Python documentation.
Common Beginner Mistakes
- Using attrgetter() on a dictionary key rather than an object attribute.
- Assuming the operation has the same behavior for missing values, empty inputs and regular inputs.
Key Takeaways
- Read named attributes, including dotted nested attributes.
- attrgetter("field") returns an attribute accessor; attrgetter("a.b") traverses nested attributes, and multiple arguments return a tuple.
- Apply this operation only after checking the assumptions and input conditions shown in the example.