Global and nonlocal in Python

Source: Internet
Author: User

In Python, the scope range of a variable is divided into 4 parts from small to large:Local scope(also can be considered as the scope of the current function formation),Enclosing Scope (simply, the scope of the outer function formation),Global Scope(that is, the scope of the current file formation),Builtins Scope(simply, Is the python built-in variable located at the top level of scope). When Python starts looking for an unqualified variable name (like attr in Obj.attr, it is a qualified variable name, which is limited to the Obj object, and the normal variable name is not qualified), always starting at the scope of the current variable name, Follow the scope chain mentioned above to start looking up, once found will not go up and continue to find, if you find a complete scope chain or not found, Python will error.

The variable name lookup sequence mentioned above can be simply recorded as LEGB(the first letter of each scope), while global and nonlocal can change the order of lookups.

Global

Variables declared in a file automatically become global, and if you want to declare a global variable inside a function, you need to use the Global keyword:

Global var1, var2, ...     # multiple variables separated by commas

For the global keyword, the following points need to be noted:

1 when Python sees a variable declared by the global variable, the scope to begin looking for is not from the scope where the variable is currently located, but from global scope, and if global scope is not found, it will continue to builtins Scope Lookup;

2 The object declared by the Global keyword allows assignment, if the variable does not exist before, then the assignment is to create a global variable, and if the variable exists before, then this assignment changes the value of the global variable:

def Test ():     Global x     = 1    #  x does not exist before, so a global variable x= 1def  Test ()     is created in global scope: Global x     =    #  x before it already exists in global scope, so here is the value of change x

3 A variable that is declared by the Global keyword will be a global variable, if the variable is not a global variable, and if there is a variable with the same name in global scope, the variable declared by global will replace the variable with the same name:

x = 99defTest (): x= 88GlobalX#In doing so, Python generates a warning: syntaxwarning:name ' x ' is assigned to before global declaration>>>Print(x)#The first access is a global variable x>>>99>>>test ()#before executing the test function, the local variable x inside the original function becomes the global variable and replaces the original global variable>>>Print(x)#now you are accessing the superseded global variable x, and the value becomes>>>88#in the case of an example, joining begins without defining a global variable xdefTest (): x= 88GlobalX#the same warning will still be generated>>>Test ()>>>Print(x)#Print result is 88!!! >>>88

Nonlocal

Nonlocal is the keyword that Python 3.X joins in, not in Python 2.X. In Python, nested functions are variables that can access external functions ( at least in the version of >python 2.2, in versions prior to Python 2.2, the lookup of variables starts with the current function and then goes directly to global scope,builtins Scope, skipping the outer function ), but can not change the value of the external function variable, if it does change, use the nonlocal variable to declare:

Nonlocal var1, var2,...   # supported only in Python 3.X, with multiple variables separated by commas

For the nonlocal keyword, the following points need to be noted:

The 1 nonlocal keyword is only supported in Python 3.X, and Python 2.X does not have this keyword;

2 nonlocal keyword can only be used inside the function, the use of other places will be error;

3 the variable declared by the nonlocal must already exist (and exists in the external function), and if the variable is not present, the variable is assigned a value, which is not the same as the Global keyword:

# variable exists in global Scopex = Testdef  ():    nonlocal           x#  error: Syntaxerror:name ' X ' is a assigned to before nonlocal declaration#  variable exists in the current function def  Test ():    =    nonlocal x           #  Error: Syntaxerror:name ' x ' is assigned to before Nonlocal Decl Aration

4 for variables declared by nonlocal, only the variables are found in the external function and are not found in the global scope and Builtins scope

Global and nonlocal in Python

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.