A detailed description of the scope rules in Python

Source: Internet
Author: User
Python is a static-scoped language, although it is itself a dynamic language. In other words, the scope of the variable in Python is determined by its position in the source code, which is somewhat similar to C, but the difference between Python and C in scope is very obvious.

Next, we'll talk about Python's scope rules, which will also explain the difference between Python and C in scope.

In Python 2.0 and earlier, Python supported only 3 scopes, the local scope, the global scope, the built-in scope, and in Python 2.2, Python formally introduced a new scope---nested scope; in Python 2.1, Nested scopes can be opened as an option, the introduction of nested scopes, essentially python implementation of the closure of the support, about the closure of the knowledge, there are many explanations on the Internet, here is not detailed deployment. Accordingly, the variable lookup order is changed from the previous LGB to LEGB (l:local,e:enclosing,g:global,b:built-in).

In Python, not every block of code can introduce a new scope, which differs greatly from C:

The code is as follows:


#include
int main () {
if (2 > 0) {
int i = 0;
}
printf ("I =%d", i);
return 0;
}

In this code, if clause introduces a local scope, the variable i exists in this local scope, but is not visible externally, so the next reference to the variable i in the printf function throws a compilation error.

However, this is not the case in Python:

The code is as follows:


If True:
i = 0
Print I

In this code, the IF clause does not introduce a local scope, and the variable i is still in the global scope, so the variable i is visible to the next print statement.

In fact, in Python, only modules, classes, and functions introduce new scopes, and other blocks of code do not introduce new scopes.

In Python, you do not have to declare it before using a variable, but before you actually use it, it must already be bound to an object, and the name binding will introduce a new variable in the current scope, masking the same name variable in the outer scope, regardless of where in the current scope the name binding occurs.

The code is as follows:


def f ():
Print I
F ()

The result of the operation will be displayed: Nameerror:global name ' I ' is not defined. Python first finds the variable i in the local scope of function f, finds the failure, then finds the variable I in the global scope and the built-in scope, still fails, and eventually throws the Nameerror exception.

The code is as follows:


i = 0
def f ():
i = 8
Print I
F ()
Print I

The results of the operation show: 8 and 0. i = 8 is a name binding operation that introduces a new variable i in the local scope of function f, shielding the global variable I, so the print statement inside F sees the local variable i,f the outer print statement sees the global variable I.

The code is as follows:


i = 0
def f ():
Print I
i = 0
F ()

The running results show: unboundlocalerror:local variable ' i ' referenced before assignment. In this example, the variable i in function f is a local variable, but when the print statement uses it, it is not bound to any object, so throws an exception.

The code is as follows:


Print I
i = 0


Whether it is running interactively or as a script file, the results are displayed: Nameerror:name ' I ' is not defined. The output here is different from the previous example because it is in the top-level scope (module scope). For module code, the code is not preprocessed before it executes, but for the function body, the code is preprocessed before it runs, so it can be perceived regardless of where the name binding occurs in the scope. Although Python is a static-scoped language, the name lookup does occur dynamically, so it is not until it runs that the name problem is discovered.

In Python, the name binding introduces a new variable in the owning scope and binds to an object. The name binding occurs under the following conditions:

1. Parameter declaration: The parameter declaration introduces a new variable in the local scope of the function;
2. Assignment operation: The initial assignment of a variable introduces a new variable in the current scope, and subsequent assignment will rebind the variable;
3. Class and function definitions: class and function definitions introduce the class name and function name as variables into the current scope, and the class body and function body will form another scope;
4.import statement: The import statement introduces a new variable in the current scope, typically in the global scope;
5.for statement: The For statement introduces a new variable (loop variable) in the current scope;
6.except statement: The except statement introduces a new variable (exception object) in the current scope.

In Python, the scope introduced by the class definition is not visible to member functions, which is very different from C + + or Java, so in Python, the member function wants to refer to a variable defined by the class body, which must be referenced by self or by the class name.

The addition of nested scopes can result in some code compiling but may result in different running results, where the Python interpreter will help you identify the areas that might be causing the problem and give a warning.

The locals function returns all local variables, but does not return the variables in the nested scope, and virtually no function returns the variables in the nested scope.

  • 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.