Elegant python and elegant python
For example, the following code
s = 'foo'd = {'a':1}def f(): s = 'bar' d['b'] = 2f()print sprint d
Why do we need to declare the value of dictionary d without the global keyword?
This is because,
- In the sentence s = 'bar', it is"Ambiguous"Because it can both represent referencing the global variable s or creating a new local variable, in python, the default action is to create a local variable, unless you explicitly declare global.
- In the sentence d ['B'] = 2, it is"Clear"If we regard d as a local variable, it will report KeyError, so it can only reference global d, so we do not need to explicitly declare global.
The above two assignment statements are actually different actions. One isRebinding, One isMutation.
However
d = {'a':1}def f(): d = {} d['b'] = 2f()print d
In the sentence d = {}, it is "ambiguous", so it creates a local variable d instead of referencing the global variable d, therefore, d ['B'] = 2 is also the local variable of the operation.
The essence of all these phenomena is"Is it clear".
If you think about it, you will find that not only dict does not need global, but all "Explicit" things do not need global. There is only one modification method for int-type 'str', that is, 'x' = Y'. This modification method is also the method for creating variables, which leads to ambiguity, I don't know whether to modify or create it. Dict/list/object can be used through dict ['X'] = y or list. modifications such as append () do not conflict with the creation variable, and do not produce ambiguity, so no explicit global is required.