Python variable Scope

Source: Internet
Author: User
Tags variable scope

Python variable Scope

Variable Scope LEGB
1. Scope of variables
When you create, change, or find a variable name in a Python program, it is done in a space (namespace) that holds the variable name, which we call the scope. The scope of the Python is static, where the variable name is assigned in the source code to determine the scope that the variable can be accessed, that is, the scope of the Python variable is determined by the position in the source code where the variable resides.

2, the use of high-level language data type process
General high-level languages when using variables, there are 4 procedures, of course, different languages will also have a difference:

    • 1. Declaring variables: Let the compiler know the existence of this variable;
    • 2. Define variables: Allocate memory space for variables of different data types;
    • 3. Initialize: Assign value, fill the allocated memory space;
    • 4. Reference: Invoke the Memory object (memory data) by referencing the object (variable name);

3, the scope of the production
In terms of scope, Python differs greatly from C in that not all statement blocks in Python will have scope. Only when a variable is defined in module, Class (Class), Def (function), does it have the concept of scope. The following code:

def func():    =100    print(variable)print(variables)        # NameError: name ‘variables‘ is not defined,在pycharm中就会自动报错

Variables defined in the scope are generally valid only in scope. It is important to note that there is no scope in the statement block of keywords such as If-elif-else, For-else, while, try-except/try-finally, and the following code:

ifTrue:    =100    print(variable)     # 100print("*"*12)       # ************print(variable)     # 100

So, you can see that although the variable variable is defined in the IF statement, it can still be used outside of the IF statement.

4. Scope Type:
In Python, it is not strictly necessary to use a variable in advance to declare it, but before actually using it, he must be bound to a memory object (defined, assigned); The binding of this variable name introduces a new variable in the current scope, and the colleague masks the variable with the same name in the outer scope.
L (local) Local variables scope
Local variables: Included in the statement block defined by the DEF keyword, which is the variable defined in the function. A new local scope is created whenever the function is called. Python also has recursion, which calls itself, creating a new local namespace for each invocation. The declaration of a variable inside a function, unless specifically declared as a global variable, defaults to a local variable. There are situations where you need to define a global variable inside a function, you can use the Global keyword to declare that the scope of the variable is global. A local variable field is like a stack, just a temporary existence, dependent on whether the function that created the local scope is in the active state. Therefore, it is generally recommended to use as few global variables as possible, because the global variables will persist during the module file run, taking up memory space.
Note: If you need to assign a value to a global variable inside a function, you need to declare the variable as a global variable inside the function through the global statement.

E (enclosing) nesting scope
E is also included in the DEF keyword, where E and L are relative, and E is also l relative to the upper function. The difference from L is that, for a function, L is the local scope defined within this function, and E is the local scope of the parent function that defines the function, primarily to implement the Python closure, and the added implementation.

G (Global) scope
That is, variables defined in the module hierarchy, each of which is a global scope. That is, the variable declared at the top of the module file has a global scope, and externally, the module's global variable is the property of a Module object.
Note: The scope of the global scope is limited to a single module file.

B (built-in) built-in scopes
Variables defined within a fixed module in the system, such as those defined within the Builtin module.

5. Variable name resolution LEGB law
The priority of the search variable name: local scope, nested scope, global scope, built-in scope
LEGB rule: When an indeterminate variable name is used in a function, Python searches for 4 scopes in order of precedence to determine the meaning of the variable name. First, the local scope (L) is searched, followed by the nested scope (E) of the Def or lambda function in the previous nested structure, followed by the global scope (G), and finally the built-in scope (B). According to this search principle, the first place to find the stop, if not found, will throw a Nameerror exception. The following example:

def func():    =300    print(variable)     # 300=100func()print(variable)     # 100
variable =   +  def  test_scope (): print  (variable) # var Iable is a local variable of test_scope (), but does not bind a memory object when printing, so the error in pycharm  variable =  200  test_scope () print  (variable)  

The above example produces an error because the precompilation at the time of the execution of the program can find the local variable variable (assigned to the variable) in Test_scope (). The variable name is found in the local scope, so it is not upgraded to a nested scope to look for, but when you print the variable variable using print (), the local variable is not bound to a memory object (there is no definition and initialization, that is, there is no value assigned). In essence, the LEGB rule followed by Python's invocation of a variable and the compiler principle of the Python interpreter determine the occurrence of this error. Therefore, before calling a variable, you need to assign a value to the variable (bind a Memory object).
Note: the error that is triggered in this example is "unboundlocalerror:local variable ' variable ' referenced before assignment" instead of " Nameerror:name ' variable ' is not defined ". This is because the variable variable is not at the global scope. The module code in Python is not precompiled until it is executed, but the function body code inside the module is pre-compiled before it is run, so it can be known to the compiler regardless of where the variable name's binding occurs in the scope. Although Python is a static-scoped language, variable name lookups occur dynamically and are not discovered until the program is run.

Python variable Scope

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.