In python, is there a setdefault() equivalent for getting object attributes?

Note that the currently accepted answer will, if the attribute doesn't exist already, have called hasattr(), setattr() and getattr(). This would be necessary only if the OP had done something like overriding setattr and/or getattr -- in which case the OP is not the innocent enquirer we took him for. Otherwise calling all 3 functions is gross; the setattr() call should be followed by return value so that it doesn't fall through to return getattr(....)

According to the docs, hasattr() is implemented by calling getattr() and catching exceptions. The following code may be faster when the attribute exists already:

def setdefaultattr(obj, name, value):
    try:
        return getattr(obj, name)
    except AttributeError:
        setattr(obj, name, value)
    return value

Python doesn't have one built in, but you can define your own:

def setdefaultattr(obj, name, value):
    if not hasattr(obj, name):
        setattr(obj, name, value)
    return getattr(obj, name)

Tags:

Python