Iterating over Attributes of a Python Object

Today I needed to extract all attributes and their current value from a Python object. This is usually very handy for overriding __str__ or implementing a to_xml method. This should do the trick:

# functional style
def my_fancy_attribute_getter(self):
    attr_and_values = ((attr, getattr(self, attr)) for attr in dir(self) if not attr.startswith("__"))
    return [(attr, value) for attr, value in attr_and_values if not callable(value)]

# imperative style
def my_fancy_attribute_getter(self):
    result = []
    for attr in dir(self):
        if not attr.startswith("__"):
            value = getattr(self, attr)
            if not callable(value):
                result.append((attr, value))
    return result

Of course the line 4 can be changed to get method names too. All attributes beginning with “__” are considered to be private and should not be returned.

Edit:
There is another shorter way to do this. Every Python object has a __dict__ attribute which returns all attributes, methods and their values as dictionary:

def my_even_fancier_attribute_getter(self):
    return [(attr, value) for attr, value in self.__dict__.items() if not callable(value)]
Advertisements

0 Responses to “Iterating over Attributes of a Python Object”



  1. Leave a Comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s





%d bloggers like this: