Python program structure [3], variable/variable, LEGB law

Source: Internet
Author: User

legb rule /LEGB rule LEGB variable search order

----from the Python Learning manual/ learning python Page 419----

Python's variable name resolution mechanism is called the LEGB rule.

L–local: local scope;

E–enclosing: The local scope of def or lambda in the previous layer structure;

G–global: global scope;

B–build-in: Built-in scope.

LEGB Scope Lookup Principle : When referencing a variable, Python looks in the following order: from the local variable , in the scope of any upper function , in the global scope , and finally in the built-in scope find in. The first to complete the search is even successful. The position where the variable is assigned in the code usually determines its scope. In Python3.0, a nonlocal declaration can also force a name to be mapped to a scope inside the function, regardless of whether or not it is assigned a value. These rules are valid only for simple variable names.

The following is a code example to illustrate this lookup principle.

""" Python LEGB rule:local, enclosing, global, built-in """
L Find

Defining three functions for testing the Local search, the correct function makes a global declaration prior to calling a, calls the Globals variable A, and the error function does not make a global declaration before the call. Use the Try/except statement to capture the error. The Correct_2 function assigns a value to a before it is called, because there is no global declaration where a is a local variable a, and assigning a value to it does not affect the globals variable A.

1 #Local--L2A = 73 deferrorfunclocal ():4     Print('\ n-------------func:errorfunclocal----------------')  5     Try:  6         Print('The global value of A is%d'%A)7     exceptNameerror:8         Print('Function <errorFuncLocal> raises a nameerror')  9A = 6Ten        One defcorrectfunclocal (): A     Print('\ n-------------func:correctfunclocal------------')   -     GlobalA -     Try:   the         Print('The global value of A is%d'%A) -     exceptNameerror: -         Print('Function <correctFuncLocal> raises a nameerror')   -     #A = 6 +        - defcorrectfunclocal_2 (): +     Print('\ n-------------func:correctfunclocal_2------------')   AA = 5 at     Try:   -         Print('The local value of A is%d'%A) -     exceptNameerror: -         Print('Function <correctFuncLocal> raises a nameerror')

Note: in the errorfunclocal function, you need to operate the variable a in the local variable, otherwise there is no operation of the variable A, the L search cannot find a, and a is found in the G search, which introduces global variable A, and cannot throw the Na of the local variable A. Meerror.

1 if __name__ ' __main__ ' :   2     errorfunclocal ()  3    correctfunclocal ()  4     correctfunclocal_2 ()   5     Print ('theglobal value of a is%d' % a)  

Run the above code to get the output as,

-------------func:errorfunclocal----------------<errorFuncLocal> raises a nameerror------ -------func:correctfunclocal------------Global is 7-------------func:correctfunclocal _2------------ is 5Global is 7

can see that

The errorfunclocal function does not have a global declaration and assigns a value to the variable A, resulting in an error exception.

The global Declaration was made in the correctfunclocal function, so no error was generated,

correctfunclocal_2 function, defines a is actually a local variable, you can see that within the function of a is 5, but the outside of the function of the global variable A is still 7, when using the L search first found is a local variable.


E Find

Then define two functions for testing enclosing search,

1 #enclosing--E2A = 73 deferrorfuncenclosing ():4     Print('\ n-------------func:errorfuncenclosing-----------')  5     deffoo ():6         Print('The enclosing value of A is%d'%A)7     Try:  8 foo ()9A = 6Ten     exceptNameerror: One         Print('Function <errorFuncEnclosing> raises a nameerror')   A        - defcorrectfuncenclosing (): -     Print('\ n-------------func:correctfuncenclosing-----------')   the     deffoo (): -         Print('The enclosing value of A is%d'%A) -     Try:   -A = 6 + foo () -     exceptNameerror: +         Print('Function <errorFuncEnclosing> raises a nameerror')

Run function

1 if __name__ ' __main__ ' :   2     errorfuncenclosing ()  3    correctfuncenclosing ()  4     Print('theglobal value of a is%d' % a)  

The result of the final output is as follows, because a is defined in the outer layer function before the inner function of the correct function calls a, so the nameerror is not thrown, and the error function assigns a value to a after the inner function calls a, enclosing searches for the variable A in the outer layer function , but no assignment was made before the call, so a nameerror is raised.

-------------func:errorfuncenclosing-----------<errorFuncEnclosing> raises a nameerror--- ----------func:correctfuncenclosing----------- is 6Global is 7

G Find

Define a function to validate the global variable lookup,

1 # Global--G   2 A = 734def  Correctfuncglobal ():  5     Print ('\ n-------------func:correctfuncglobal-----------')   6     Print ('theglobal value of a is%d' % a)  

Call a directly inside the function, because the LE search did not find the variable a, and the G search found, so at this time the variable A is a global variable.

-------------func:correctfuncglobal-----------Global is 7

B Find

Finally, the B lookup search is the built-in variable lookup, and for the built-in variables such as __name__, the LEG search is not found after enabling the B-search to find the built-in variables, so you can directly reference the built-in variables.

1 #Built-in--B2 defCorrectfuncbuildin ():3     Print('\ n-------------func:correctfuncbuildin-----------')  4     Print('The value of built-in variable __name__ is:',__name__) 5 6 if __name__=='__main__':  7Correctfuncbuildin ()

The results are as follows

-------------Func:correctfuncbuildin-----------Thevalue of build-in__name__is  __main__

Reference Links

Http://www.jb51.net/article/84206.htm

Python program structure [3], variable/variable, LEGB law

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.