Because you are not assigning to cache
, you are changing the dictionary itself instead. cache
is still pointing to the dictionary, thus is itself unchanged. The line cache['foo'] = 'bar'
translates to cache.__setitem__('foo', 'bar')
. In other words, the value of cache
is a python dict
, and that value is itself mutable.
If you tried to change what cache
refers to by using cache = 'bar'
instead, you would be changing what cache
points to and then you need the global
keyword.
Perhaps this older answer of mine to a similar question helps you understand the difference: Python list doesn't reflect variable change.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…