#Lift up the global and nonlocal keywords under the scope of Python# Python

Posted by Niyati_1984 on Tue, 28 Dec 2021 14:49:40 +0100

global and nonlocal scopes

This part involves the knowledge of Python variable scope. Variable scope refers to the effective scope of variables. It is directly understood that variables in Python can not be accessed at any location with restrictions.

In general, the scope of variables varies from block level, function, class, module, package, etc., and the level reaches from small to small. There is no block level scope in Python, so when we write code, the following code is correct.

if True:
    x = "hello world"
# Because there is no block level scope, the variable x in the if code block can be accessed externally
print(x)

Common block level scopes in Python include if statement, for statement, while statement and with context statement.

Scope in Python

As mentioned above, the scope is the scope where Python programs can directly access a variable. There are four kinds of scopes in Python, as follows:

  1. L (Local): the innermost layer, including Local variables, such as the interior of a function (method);
  2. E (Enclosing): contains nonlocal or non global variables. In nested functions, function A contains function B. in B, you can access the variables in A. the scope is nonlocal. Frankly, it is understood as the variables in functions outside the closure function;
  3. G (Global): outermost layer of code, Global variable;
  4. B (build in): contains Built-in variables.

A classic case is as follows:

# Built in scope build in
x = int(5/2)

# Global scope Global
global_var = 0

def outer():
    # Enclosing in a function other than a closure function
    out_var = 1

    def inner():
        # Local scope
        inner_var = 2

In Python, the order of variable search is from inside to outside, first local, then external, and then global. This rule is called LEGB rule.

To make the following learning interesting, you can study how the variables in the following code change.

len = len([])
def a():
    len = 1
    def b():
        len = 2
        print(len)
    b()
a()

global keyword

Variables defined inside the function have a local scope, and variables defined outside the function have a global scope.

Local variables can only be accessed inside the declared function, while global variables can be accessed throughout the program.

# global variable
x = 0
def demo():
    # x in this case is a local variable
    x = 123
    print("Functions are local variables x = ", x)

demo()
print("Outside the function is a global variable x= ", x)

The output result is 123 inside the function and 0 outside the function.

If you want to modify the variables of the external scope inside the function (internal scope), you need to use the global keyword.

# global variable
x = 0

def demo():
    # x in this case is the global variable
    global x
    x = 123
    print("Functions are local variables x = ", x)

demo()
print("Outside the function is a global variable x= ", x)

At this time, the output is 123. Another thing to note is that if you want to modify the value of the global variable in the function content, the global keyword must be written before the variable operation.

def demo():
    # x in this case is the global variable

    x = 123
    global x
    print("Functions are local variables x = ", x)

Syntax errors occur in this Code:

SyntaxError: name 'x' is assigned to before global declaration

In addition to the above knowledge, remember to use a variable inside the function. Without modifying the value, there is no declaration. By default, the value of the global variable is obtained.

x = "global variable"

def demo():
    print(x)

demo()

There is also a real interview question in the global variable, which often appears. What is the running result of the following code.

x = 10

def demo():
    x += 1
    print(x)

demo()

The conclusion is an error. The reason is that when the demo function runs, x+1 will be calculated first. Declaration and assignment are required before variable calculation, but x is not initialized inside the function, so an error is reported.

nonlocal keyword

If you want to modify variables in a nested scope (Enclosing scope), you need the nonlocal keyword. The test code is as follows:

def outer():
    num = 10

    def inner():
        # nonlocal keyword
        nonlocal num
        num = 100
        print(num)
    inner()
    print(num)

outer()

Test the output results by yourself. Note that the nonlocal keyword must be Python 3 X + version, python 2 Syntax error in version x:

 nonlocal num
         ^
SyntaxError: invalid syntax`

Nonlocal cannot replace global. For example, the following code comments out the variable declaration of the outer function. At this time, SyntaxError: no binding for nonlocal 'num' found error will appear.

num = 10
def outer():
    # Comment out the line
    # num = 10

    def inner():
        # nonlocal keyword
        nonlocal num
        num = 100
        print(num)

    inner()
    print(num)

outer()

In multiple nesting, nonlocal will only go up one layer. If there is no previous layer, it will continue to go up. You can comment and view the results separately in the following code.

num = 10
def outer():

    num = 100

    def inner():

        num = 1000
        def inner1():
            nonlocal num
            num = 10000
            print(num)
        inner1()
        print(num)

    inner()
    print(num)

outer()

The specific local variables and global variables can be obtained through the two built-in functions of locals() and globals().

x = "global variable"

def demo():
    y = "local variable"
    print(locals())
    print(x)

demo()
print(globals())
print(locals())

Summary of this blog

This blog explains the scope of Python and learns the global and nonlocal keywords. I hope it will help you.

Topics: Python Back-end