python - Why does some_dict['key'] = somevalue work if the key is not in some_dict? -


i know can add new key/value in python dict doing

some_dict['absent_key'] = somevalue 

but don't understand internals work.

i used think dictionaries behaved c++ maps. [] operator create element given key if not exist, return reference can assigned value in same line operator =.

but behavior in c++ has consequence if query map value key not exist, element created key, , default value value type returned instead of error. in python, throws keyerror.

so don't understand is: how, since [] operator must evaluated before = in python (i think?), behave differently depending if result read or assigned value (which should not know @ point of expression evaluation)?

is there difference in order in python evaluates expressions? or interpreter smarter since dictionaries hare hardcoded type knows more precisely how behaves, while std::map in 'library' compiler can assume less? or other reason?

the operations:

some_dict[key] 

and

some_dict[key] = value 

and

del some_dict[key] 

use different special methods of object: __getitem__, __setitem__ , __delitem__. it's not 1 operator ([]) implements them all.

maybe example can illustrate that:

class something(dict):  # subclassing dict     def __getitem__(self, key):         print('trying get', key)         return super().__getitem__(key)     def __setitem__(self, key, value):         print('trying set', key, 'to', value)         return super().__setitem__(key, value)     def __delitem__(self, key):         print('trying delete', key)         return super().__delitem__(key) 

test:

>>> s = something({'a': 1, 'b': 2}) >>> s['a'] trying 1  >>> s['c'] = 10 trying set c 10  >>> del s['b'] trying delete b 

so depends on how implemented. in plain python dicts __getitem__ returns value key or throws if it's not present.

but subclasses implement __missing__ method - in case want customize behavior if key wasn't present in dict (during lookup).


Comments

Popular posts from this blog

Is there a better way to structure post methods in Class Based Views -

performance - Why is XCHG reg, reg a 3 micro-op instruction on modern Intel architectures? -

jquery - Responsive Navbar with Sub Navbar -