Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python getattr equivalent for dictionaries?

Tags:

python

What's the most succinct way of saying, in Python, "Give me dict['foo'] if it exists, and if not, give me this other value bar"? If I were using an object rather than a dictionary, I'd use getattr:

getattr(obj, 'foo', bar) 

but this raises a key error if I try using a dictionary instead (a distinction I find unfortunate coming from JavaScript/CoffeeScript). Likewise, in JavaScript/CoffeeScript I'd just write

dict['foo'] || bar 

but, again, this yields a KeyError. What to do? Something succinct, please!

like image 249
Trevor Burnham Avatar asked Jun 21 '10 23:06

Trevor Burnham


People also ask

What is Getattr () in Python?

Python getattr() The getattr() method returns the value of the named attribute of an object. If not found, it returns the default value provided to the function.

What does __ Getattr __ do in Python?

__getattr__Called when an attribute lookup has not found the attribute in the usual places (i.e. it is not an instance attribute nor is it found in the class tree for self ). name is the attribute name. This method should return the (computed) attribute value or raise an AttributeError exception.

How many arguments Getattr () function receives in Python?

getattr() is one of the coolest built-in functions in Python. It takes three arguments: an object. name of the object's attribute but in the string format.

Is Getattr slow Python?

The getattr approach is slower than the if approach, reducing an insignificant ~3% the performance if bar is set and a considerable~35% if is not set.


2 Answers

dict.get(key, default) returns dict[key] if key in dict, else returns default.

Note that the default for default is None so if you say dict.get(key) and key is not in dict then this will just return None rather than raising a KeyError as happens when you use the [] key access notation.

like image 147
mikej Avatar answered Sep 19 '22 08:09

mikej


Also take a look at collections module's defaultdict class. It's a dict for which you can specify what it must return when the key is not found. With it you can do things like:

class MyDefaultObj:     def __init__(self):         self.a = 1  from collections import defaultdict d = defaultdict(MyDefaultObj) i = d['NonExistentKey'] type(i) <instance of class MyDefalutObj> 

which allows you to use the familiar d[i] convention.

However, as mikej said, .get() also works, but here is the form closer to your JavaScript example:

d = {} i = d.get('NonExistentKey') or MyDefaultObj() # the reason this is slightly better than d.get('NonExistent', MyDefaultObj()) # is that instantiation of default value happens only when 'NonExistent' does not exist. # With d.get('NonExistent', MyDefaultObj()) you spin up a default every time you .get() type(i) <instance of class MyDefalutObj> 
like image 39
ddotsenko Avatar answered Sep 21 '22 08:09

ddotsenko