The Python interpreter. The sequence in which the code is executed. Namespace and Scope Features

I apologize for the noob question, but after searching the Internet, I could not find a complete answer to the intersex question. I can't understand how the following example works out:

x = 10

def func():
    print(x)

func()

Here the code works without an error. Because the perm x is not in the local namespace, so the interpreter looks into the global space, finds it there and calmly displays it on the screen.

x = 10

def func():
    print(x)
    x = 20

func()

In the same example, I will get UnboundLocalError. The error occurs because the interpreter knows that there is a variable x in the local namespace, but the value is assigned after it is called.

I understand that before executing the code, the interpreter runs through the code and FIRST forms a namespace. That is, before executing this code, a space is first formed with the variable x and the function fucn.

Question!

When the function is called, before executing the function, the interpreter also first runs through the function body and forms a local namespace? or does it start executing the function body line by line?

Also, please correct me if I made any mistakes in my explanations and guesses. I really want to thoroughly understand how the Python interpreter behaves and, in general, the syntax and features of this language.

Author: insolor, 2019-11-26

2 answers

The name resolution scheme in Python is sometimes called the LEGB rule, the name of which consists of the first letters of the names of the scopes:

  • When an unknown name is accessed inside a function, the interpreter tries to find it in four scopes – in the local (local, L), then in the local scope of any enclosing def statement (enclosing, E) or in a lambda expression, then in the global (global, G) and finally, in the built-in (built-in, B).

Learning Python, 4th edition. Mark Lutz (c. 477)

Func, after going through local and enclosing namespaces, will search further in global, and in the first example it will find there. in the second case, it will find the variable in local, but since the statement calling it is declared before initializing the variable itself,it will throw an error.

 6
Author: finally, 2019-11-26 09:22:02

When calling a function, the interpreter works within this function, and if you try to pass the value of x to the print() function before it was declared,you will naturally get an error. If you do not declare x as a local variable in this function, the program will read the value of x from the global namespace.

 0
Author: Тимофей Черненко, 2019-11-26 08:13:15