Get all object attributes in Python?
Simple way to get an object's attributes in Python: use dir(). Exclude special methods by filtering out names starting with '__':
Key concept: Get a cleaner, refined attribute list by filtering out special methods from dir().
A deeper dive with __dict__
dir() gives a good picture, but complement it with __dict__ for an object's attribute dictionary:
Using getattr for dynamic attributes
Dynamic objects have attributes resolved at runtime. Here's the gameplan: employ getattr(obj, attr):
Beware the __dir__ override
Just like a plot twist in a story, a __dir__ method can override what dir() returns. Keep that in mind!
The inheritance trail with __mro__
Uncover inherited attributes by traversing __mro__:
The whole picture: dir() + __dict__
Paint a complete picture by marrying dir() and __dict__:
This gives you every attribute, even those hidden in the deepest corners of the toolbox.
Navigate the minefield of dynamic attributes
When your object comes with dynamic attribute resolution via __getattr__, the path requires careful steps:
Was this article helpful?