The scope of the Python learning variable

Source: Internet
Author: User
Tags variable scope

Study Address: http://www.jianshu.com/p/17a9d8584530

1. Scope of variable scope LEGB1.1 variable

creating, changing, and locating variable names in a Python program is done in a space where variable names are stored, which we call namespaces, also known as scopes. The scope of the Python is static, and the location of the variable name assigned to it in the source code determines the range to which 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.

1.2 Use of high-level languages for data types

In general, high-level languages have the following 4 procedures when using variables. Of course there are differences in different languages.

    1. Declaring variables: Let the editor know that a variable exists
    2. Defining variables: Allocating memory space for variables of different data types
    3. Initialize: Assign value, fill allocated memory space
    4. Reference: Invoking a Memory object (memory data) by referencing an object (variable name)
1.3 Generation of scopes

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

#!/usr/bin/env pythondef func():    variable = 100    print variableprint variable

The output of the code is:

NameError: name ‘variable‘ is not defined

Variables defined in the scope are generally valid only in scope. It is important to note that If-elif-else, For-else, while, try-except\try-finally, and so on, do not produce scopes in the statement blocks of the keywords. Look at the following code:

if True:    variable = 100    print (variable)print ("******")print (variable)

The output of the code is:

100******100

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

1.4 Types of scopes:

In Python, it is not strictly necessary to use a variable in advance to declare it, but before actually using it, it must be bound to a memory object (defined, assigned); The binding of the variable name will introduce a new variable in the current scope, while masking the same name variable in the outer scope.

L (local) local 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 that you define as few global variables as possible, because global variables 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 inside this function, and E is the local scope of the parent function that defines the previous level of the function. The main purpose is to implement Python's closures, while increasing the implementation.

G (Global) scope

That is, variables defined in the module hierarchy, each of which is a global scope. That is, the variables declared at the top level of the module file have global scope, from the outside, the module's global variables are the properties 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 variables that are predefined within the Builtin module.

1.5 Variable name resolution LEGB law

Priority of 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). Follow this search principle and stop at the first place found. If not found, it will depart Nameerror error.

Several examples:

1.

def func():    variable = 300    print variablevariable = 100func() #300print variable  #100

2.

variable = 300def test_scopt (): A local variable of print variable #variable是test_scopt (), but does not bind a memory object when printing. variable = #因为这里, so variable is changed to local variable test_scopt () print variable The above example will report an error, because the pre-compilation when executing the program can be in the test_scopt () Local variable variable (assigned to variable) is found in the Variable names are found in the local scope, so they are not upgraded to nested scopes to look for. However, when you print the variable variable using the PRINT statement, the local variable variable and has not been 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 parser determine the error. Therefore, before calling a variable, you need to assign a value to the variable (bind a Memory object).
Note: Why the error that is triggered in this example is unboundlocalerror instead of nameerror:name ' variable ' is not defined. Because the variable variable is not in 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 runs, so the compiler knows whether the binding of the variable name takes place in the scope. Although Python is a static-scoped language, variable name lookups occur dynamically, and only when the program runs does it discover scope issues

The scope of the Python learning variable

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.