Flowy python-Why modify global dict variables without the global keyword

Source: Internet
Author: User

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.