Details about the scope rules in Python and the python domain rules

Source: Internet
Author: User

Details about the scope rules in Python and the python domain rules

Python is a static scope language, although it is a dynamic language. That is to say, in Python, the scope of a variable is determined by its position in the source code. This is similar to C, but the difference in scope between Python and C is very obvious.

Next we will talk about the scope rules of Python, and it will also explain the differences between Python and C in terms of scope.

In Python 2.0 and earlier versions, Python only supports three scopes: local scope, global scope, and built-in scope. In Python 2.2, python officially introduces a new scope-nested scope. In Python 2.1, the nested scope can be enabled as an option; the introduction of nested scope, essentially, Python implements the support for closures. There are many explanations on the Internet about closures, which will not be detailed here. Correspondingly, the variable search sequence changes from the previous LGB to LEGB (L: Local, E: Enclosing, G: Global, B: Built-in ).

In Python, not any code block can introduce new scopes, which is very different from C:

Copy codeThe Code is as follows:
# Include <stdio. h>
Int main (){
If (2> 0 ){
Int I = 0;
}
Printf ("I = % d", I );
Return 0;
}

In this Code, the if clause introduces a local scope, and variable I exists in this local scope, but it is invisible to the outside. Therefore, next, the reference to variable I in the printf function will cause a compilation error.

However, this is not the case in Python:

Copy codeThe Code is as follows:
If True:
I = 0
Print I

In this Code, the if clause does not introduce a local scope, and variable I is still in the global scope. Therefore, variable I is visible to the next print statement.

In Python, only modules, classes, and functions introduce new scopes. Other code blocks do not introduce new scopes.

In Python, you do not need to declare a variable before using it, but before using it, it must have been bound to an object; the name binding will introduce new variables in the current scope, and shield variables with the same name in the outer scope, regardless of the location where the name binding takes place in the current scope.
Copy codeThe Code is as follows:
Def f ():
Print I
F ()

The running result is: NameError: global name 'I' is not defined. Python first searches for variable I in the local scope of function f and fails to find it. Then, it searches for variable I in the global scope and built-in scope. It still fails and finally throws a NameError exception.
Copy codeThe Code is as follows:
I = 0
Def f ():
I = 8
Print I
F ()
Print I

The running result is 8 and 0. I = 8 is a name binding operation. It introduces a new variable I in the local scope of function f, shielding the global variable I, therefore, the print statement inside f shows the local variable I, and the print statement outside f shows the global variable I.
Copy codeThe Code is as follows:
I = 0
Def f ():
Print I
I = 0
F ()

The running result shows: UnboundLocalError: local variable 'I' referenced before assignment. In this example, variable I in function f is a local variable, but when the print statement uses it, it is not bound to any object, so an exception is thrown.
Copy codeThe Code is as follows:
Print I
I = 0

Whether it is run in interactive mode or in script file mode, the results show: NameError: name 'I' is not defined. The output result here is different from the previous example because it is in the top-level scope (module scope. For the module code, the code has not undergone any preprocessing before execution, but for the function body, the Code has undergone a preprocessing before running, therefore, no matter where the name binding occurs in the scope, it can perceive it. Although Python is a static scope language, Name Lookup does occur dynamically, so it will not be found when running.

In Python, name binding introduces new variables in the scope and binds them to an object. Name binding takes place in the following situations:

1. Parameter Declaration: the parameter declaration introduces new variables in the local scope of the function;
2. Assignment operation: a new variable will be introduced in the current scope when a variable is assigned for the first time, and the variable will be re-bound in subsequent assignment operations;
3. Class and Function Definition: class and Function Definition introduce the class name and function name as variables into the current scope. The class body and function body form another scope;
4. import Statement: The import Statement introduces new variables in the current scope, generally in the global scope;
5. for statement: The for statement introduces new variables (Cyclic variables) in the current scope );
6. Explain t statement: introduce new variables (abnormal objects) in the current scope of the statement ).

In Python, the scope introduced by class definitions is invisible to member functions, which is different from C ++ or Java. Therefore, in Python, to reference a variable defined by the class body, a member function must reference it by self or class name.

The addition of nested scopes may lead to code compilation failures or different running results. Here, the Python interpreter will help you identify these problems and give warnings.

The locals function returns all local variables, but does not return variables in the nested scope. In fact, no function returns variables in the nested 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.