Eraser, a new series of fun Internet advanced webworms, let’s Be More Pythonic together.

Global and nonlocal scopes

Variable scope is the effective scope of a variable. A variable in Python is not accessible anywhere.

In general, the scope of variables is block level, function, class, module, package, etc., and the level is 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"
Since there is no block-level scope, the variable x in the if code block can be accessed externally
print(x)
Copy the code

Common block-level scopes in Python are if statements, for statements, while statements, and with context statements.

10.1 Scopes in Python

As mentioned above, a scope is the scope of a variable that a Python program can access directly. There are four types of Python scopes:

  1. L (Local) : the innermost layer, which contains Local variables, such as the inside of a function (method);
  2. If you want additional recommendations on this. If you want additional recommendations on this. If you want additional recommendations on this, you want additional recommendations on variables that are neither local nor global.
  3. G (Global) : outermost layer of code, Global variable;
  4. B (built-in) : contains built-in variables.

A classic case is as follows:

# built-in scope built-in
x = int(5/2)

# Global scope
global_var = 0

def outer() :
    Enclosing functions on closure functions
    out_var = 1

    def inner() :
        # Local scope Local
        inner_var = 2
Copy the code

The order of variable searches in Python is from inside out, local first, then external, global, and built in. This rule is called the LEGB rule.

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

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

10.2 Global keyword

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

Local variables can only be accessed inside the function they declare, whereas global variables can be accessed throughout the program.

# global variables
x = 0
def demo() :
    X is a local variable
    x = 123
    print("Inside the function is the local variable x =", x)

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

The output is 123 inside the function, 0 outside the function.

If you want variables in the outer scope to be modified inside a function (the inner scope), use the global keyword.

# global variables
x = 0

def demo() :
    X is the global variable
    global x
    x = 123
    print("Inside the function is the local variable x =", x)

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

If you want to change the value of a global variable, the global keyword must be written before the variable operation.

def demo() :
    X is the global variable

    x = 123
    global x
    print("Inside the function is the local variable x =", x)
Copy the code

This code has a syntax error:

SyntaxError: name 'x' is assigned to before global declaration
Copy the code

In addition to the above knowledge, remember that when you use a variable inside a function, you get the value of the global variable by default without declaring it.

x = "Global variable"

def demo() :
    print(x)

demo()
Copy the code

Global variables also exist an interview question, often appear, please ask the following code run results.

x = 10

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

demo()
Copy the code

The result is an error. The reason is that when the demo function is running, it will calculate x+1 first. Before calculating variables, it needs to declare and assign values, but there is no internal initialization operation for x, so the error is reported.

10.3 Nonlocal Keyword

If you want to modify variables in the Enclosing scope, you need the nonlocal keyword. This is the code you want to test:

def outer() :
    num = 10

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

outer()
Copy the code

Python3.X+; python3. X+; python2. X;

 nonlocal num
         ^
SyntaxError: invalid syntax`
Copy the code

SyntaxError: No binding for nonlocal ‘num’ found SyntaxError: No binding for nonlocal ‘num’ found

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

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

    inner()
    print(num)

outer()
Copy the code

In multiple nesting, nonlocal is only traced back to one layer, and if the previous layer is not, it continues to be traced back. You can comment the following code separately to see the result.

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()
Copy the code

Local and global variables are available from the built-in functions locals() and globals().

x = "Global variable"

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

demo()
print(globals())
print(locals())
Copy the code

10.4 Summary of this blog

This blog has explained Python’s scope and studied the global and nonlocal keywords.

Blogger ID: Dream eraser, hope you like, comment, favorites.