How can I return a default value for an attribute? [duplicate]

You should use the getattr wrapper instead of directly retrieving the value of id.

a = getattr(myobject, 'id', None)

This is like saying “I would like to retrieve the attribute id from the object myobject, but if there is no attribute id inside the object myobject, then return None instead.” But it does it efficiently.

Some objects also support the following form of getattr access:

a = myobject.getattr('id', None)

As per OP request, ‘deep getattr’:

def deepgetattr(obj, attr):
    """Recurses through an attribute chain to get the ultimate value."""
    return reduce(getattr, attr.split('.'), obj)
# usage: 
print deepgetattr(universe, 'galaxy.solarsystem.planet.name')

Simple explanation:

Reduce is like an in-place recursive function. What it does in this case is start with the obj (universe) and then recursively get deeper for each attribute you try to access using getattr, so in your question it would be like this:

a = getattr(getattr(myobject, 'id', None), 'number', None)

Leave a Comment