Python variables and scopes

Source: Internet
Author: User

1. Scope
In python, the scope is divided into four situations: L: local, local scope, that is, the variables defined in the function;
E: enclosing: The local scope of nested parent functions, that is, the local scope of the upper-level functions that contain this function, but not global;
G: globa, global variable, which is defined at the module level; B: built-in, variable in the system fixed module, such as int and bytearray. The priority order of search variables is: local scope> outer scope> global in the current module> python built-in scope, that is, LEGB.

x = int(2.9)  # int built-ing_count = 0  # globaldef outer():    o_count = 1  # enclosing    def inner():        i_count = 2  # local
Of course, local is relative to enclosing, And the enclosing variable is also local relative to the upper layer.
2. Scope generation
In Python, only modules, classes, and functions (def, lambda) introduce new scopes, and other code blocks (such as if, try, and) will not introduce new scopes, as shown in the following code:
if True:    x = 1;print(x)# 1
This is correct. if a new scope is not introduced, x is still in the current scope and can be used later in the code.
def test():    x2 = 2print(x2)# NameError: name 'x2' is not defined
Def, class, and lambda can introduce new scopes.
3. Variable Modification
A variable not in the local scope is read-only by default. If you try to bind a new value to it, python considers it to be creating a new variable in the current local scope, that is to say, in the current local scope, if a variable in the external scope is used directly, the variable is read-only and cannot be modified, for example:
count = 10def outer():    print(count)      count = 100     print(count)outer()#UnboundLocalError: local variable 'count' referenced before assignment

Here, the count in the external scope is used in the first print, so that the count in the latter refers to the count in the external scope, and an error will be reported after the modification. If you do not use this variable and assign a value directly, it will be considered as a newly defined variable. At this time, it will overwrite the variables in the external scope, such:
count = 10def outer():    count = 100       print(count)outer()#100
The internal scope directly declares count = 100, and the subsequent use of count is the internal scope.
4. global keywords
When the internal scope wants to modify the variables of the external scope, the global and nonlocal keywords are used. When the modified variables are in the global scope, use global to declare the Code as follows:
count = 10def outer():    global count    print(count)      count = 100     print(count)outer()#10#100

5. nonlocal keywords
The variables declared by the global keyword must be in the global scope and cannot be in the nested scope. What should I do if I want to modify the variables in the nested scope (enclosing scope, the outer layer is not in the global scope, in this case, the nonlocal keyword is required.
def outer():    count = 10    def inner():        nonlocal count        count = 20        print(count)    inner()    print(count)outer()#20#20


6. Summary
(1) Variable Search sequence: LEGB, local scope> outer scope> global in the current module> python built-in scope; (2) Only modules, classes, and functions can be introduced into new scopes; (3) For a variable, the internal scope will overwrite the external variables first, and the variables in the external scope will be used without being declared and used directly. (4) when the value of an external scope variable is to be modified in the internal scope, the global keyword is used for the global variable, and the nonlocal keyword is used for the nested scope variable. Nonlocal Is The New Keyword of python3. With this keyword, closure can be perfectly implemented.

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.