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?
if/in/else
structure for these dictionary testing situations with default values. This time since the actual situation is actually much more intricate than my example, with a few other hasattrs flying around, I favored that "syntax" instead... which obviously doesn't work! I'll remember this gotcha from now on, thanks! – Historiography