Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python's hasattr on list values of dictionaries always returns false?

I have a dictionary that sometimes receives calls for non-existent keys, so I try and use hasattr and getattr to handle these cases:

key_string = 'foo' print "current info:", info print hasattr(info, key_string) print getattr(info, key_string, []) if hasattr(info, key_string):     array = getattr(info, key_string, []) array.append(integer) info[key_string] = array print "current info:", info 

The first time this runs with integer = 1:

current info: {} False [] current info: {'foo': [1]} 

Running this code again with integer = 2:

instance.add_to_info("foo", 2)  current info: {'foo': [1]} False [] current info: {'foo': [2]} 

The first run is clearly successful ({'foo': [1]}), but hasattr returns false and getattr uses the default blank array the second time around, losing the value of 1 in the process! Why is this?

like image 847
Chris Keele Avatar asked May 23 '12 17:05

Chris Keele


People also ask

What is Hasattr in Python?

Definition. Python hasattr() function is used to return value TRUE after checking whether the object has the given attribute, else return FALSE. The Python hasattr() built-in function is used to check if the specified object has the named attribute present within a class or not.

Can Python list have value dictionary?

It definitely can have a list and any object as value but the dictionary cannot have a list as key because the list is mutable data structure and keys cannot be mutable else of what use are they.

Which method will return a list of all the values in the dictionary?

values() method returns a view object that displays a list of all values in a given dictionary.

Can Python dictionaries hold lists?

Note that the restriction with keys in Python dictionary is only immutable data types can be used as keys, which means we cannot use a dictionary of list as a key . But the same can be done very wisely with values in dictionary. Let's see all the different ways we can create a dictionary of Lists.


2 Answers

hasattr does not test for members of a dictionary. Use the in operator instead, or the .has_key method:

>>> example = dict(foo='bar') >>> 'foo' in example True >>> example.has_key('foo') True >>> 'baz' in example False 

But note that dict.has_key() has been deprecated, is recommended against by the PEP 8 style guide and has been removed altogether in Python 3.

Incidentally, you'll run into problems by using a mutable class variable:

>>> class example(object): ...     foo = dict() ... >>> A = example() >>> B = example() >>> A.foo['bar'] = 'baz' >>> B.foo {'bar': 'baz'} 

Initialize it in your __init__ instead:

class State(object):     info = None      def __init__(self):         self.info = {} 
like image 167
Martijn Pieters Avatar answered Sep 19 '22 14:09

Martijn Pieters


A dictionary key is not the same as an object attribute

thing1 = {'a', 123} hasattr(thing1, 'a') # False class c: pass thing2 = c() thing2.a = 123 hasattr(thing2, 'a') # True 
like image 22
katzenversteher Avatar answered Sep 19 '22 14:09

katzenversteher