Why is the global keyword not required in this case?

后端 未结 1 472
慢半拍i
慢半拍i 2020-11-27 19:58
cache = {}
def func():
    cache[\'foo\'] = \'bar\'
print cache[\'foo\'] 

output

bar

Why does this work and why d

相关标签:
1条回答
  • 2020-11-27 20:04

    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.

    0 讨论(0)
提交回复
热议问题