EDIT: A possibly faster and thread safe alternative with proper mapping of KeyError
to AttributeError
:
_NO_DEFAULT = object() # so that None could be used as a default value also
def popattr(obj, name, default=_NO_DEFAULT):
try:
return obj.__dict__.pop(name)
except KeyError:
if default is not _NO_DEFAULT:
return default
raise AttributeError("no attribute '%s'" % name)
# or getattr(obj, name) to generate a real AttributeError
(previous answer)
Something like this should work:
def popattr(obj, name):
ret = getattr(obj, name)
delattr(obj, name)
return ret
Although obj.__dict__.pop(name)
also works but you'll get a KeyError
in case of non-existent attributes as opposed to AttributeError
, and I'd say the latter is semantically correct for object attribute access; KeyError
is used for dictionaries, but you're not really accessing a dictionary; the fact that you're using __dict__
is just an implementation detail of attribute popping and should be hidden, which is what popattr
does.