Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

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')
like image 212
Ross Rogers Avatar asked Dec 15 '09 01:12

Ross Rogers


People also ask

How do you check attributes of an object in Python?

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.

What is Setdefault in Python?

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.

What is Setdefault () method in dictionary?

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])


1 Answers

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
like image 180
John Machin Avatar answered Oct 05 '22 03:10

John Machin