cache = {}
def func():
cache['foo'] = 'bar'
print cache['foo']
output
bar
Why does this work and why doesn't it require use of the global keyword?
cache = {}
def func():
cache['foo'] = 'bar'
print cache['foo']
output
bar
Why does this work and why doesn't it require use of the global keyword?
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.