Explain Codes LogoExplain Codes Logo

Get all object attributes in Python?

python
object-attributes
python-attributes
getattr
Alex KataevbyAlex Kataev·Sep 14, 2024
TLDR

Simple way to get an object's attributes in Python: use dir(). Exclude special methods by filtering out names starting with '__':

obj = MyClass() # Assume MyClass is an intern at Hogwarts. # I solemnly swear that I am up to no good (getting attributes) print([attr for attr in dir(obj) if not attr.startswith('__')])

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:

attributes = dir(obj) # Mischief managed (attributes detected) details = {attr: getattr(obj, attr) for attr in attributes if not attr.startswith('__')} print(details)

Using getattr for dynamic attributes

Dynamic objects have attributes resolved at runtime. Here's the gameplan: employ getattr(obj, attr):

# And let the games begin! for attr in dir(obj): if not attr.startswith('__'): print(attr, getattr(obj, attr)) # GOAL! Attribute retrieved.

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__:

# Climbing the inheritance ladder inherited_attrs = [attr for cls in obj.__class__.__mro__ for attr in dir(cls) if not attr.startswith('__')]

The whole picture: dir() + __dict__

Paint a complete picture by marrying dir() and __dict__:

class AdvancedToolbox: hammer = True screwdriver = False def __init__(self): self.wrench = True # Aha! A wrench needed fixing. # Tools meet obj: a perfect union toolbox_attr = dir(AdvancedToolbox()) detailed_tools = {attr: getattr(AdvancedToolbox(), attr) for attr in toolbox_attr if not attr.startswith('__')}

This gives you every attribute, even those hidden in the deepest corners of the toolbox.

When your object comes with dynamic attribute resolution via __getattr__, the path requires careful steps:

try: # Treading cautiously on the dynamic path... dynamic_value = getattr(obj, 'dynamic_attr') except AttributeError: # Whoa! That was a close one. print('Attribute not found')