For example, the following code
s = ' Foo ' d = {' A ': 1}def f (): s = ' bar ' d[' b '] = 2f () print Sprint D
Why would I change the value of dictionary d without first declaring it with the global keyword?
This is because,
- In s = ' bar ', it is "ambiguous"because it can either represent a reference to the global variable s or create a new local variable, so in Python, the default behavior is to create a local variable unless you explicitly declare global.
- In the d[' B ']=2, it is "explicit"because if D is considered a local variable, it will report keyerror, so it can only refer to global D, so it does not need to explicitly declare global by superfluous.
The above two sentence assignment statement is actually different behavior, one is rebinding, one is mutation.
But if it's the following,
D = {' A ': 1}def f (): d = {} d[' b '] = 2f () Print D
In d = {}, it is "ambiguous", so it is creating a local variable D instead of referencing global variable D, so d[' B ']=2 is also the local variable of the operation.
Pushed away, the essence of all this is "whether it is clear".
If you think about it, you will find that not only dict does not need global, all "clear" things do not need global. Because of the type of type STR, there is only one modification method, that is, x = y, which is exactly the method of creating the variable, so there is ambiguity, and I do not know whether to modify or create it. and dict/list/objects, etc., can be modified by dict[' x ']=y or List.append (), and do not conflict with the creation of variables, do not produce ambiguity, so do not have explicit global.
Flowy python-Why modify global dict variables without the global keyword