Python's setdefault allows you to get a value from a dictionary, but if the key doesn't exist, then you assign the based on parameter default
. You then fetch whatever is at the key in the dictionary.
Without manipulating an object's __dict__
Is there a similar function for objects?
e.g.
I have an object foo
which may or may not have attribute bar
. How can I do something like:
result = setdefaultattr(foo,'bar','bah')
To check if an object in python has a given attribute, we can use the hasattr() function. The function accepts the object's name as the first argument 'object' and the name of the attribute as the second argument 'name. ' It returns a boolean value as the function output.
The setdefault() method returns the value of the item with the specified key. If the key does not exist, insert the key, with the specified value, see example below.
The setdefault() method returns the value of a key (if the key is in dictionary). If not, it inserts key with a value to the dictionary. The syntax of setdefault() is: dict.setdefault(key[, default_value])
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With