简体   繁体   中英

How does Python interpreter actually interpret a program?

Take a sample program:

c = 10

def myfunc():
    print(c)

myfunc()

This prints 10 as expected, but if we look at another program:


c = 10

def myfunc():
    print(c)
    c = 1


myfunc()

It says: "local variable 'c' referenced before assignment"

Here, if the python interpreter is actually going line by line, shouldn't it print 10 before reaching the next line to conclude there's a local variable?

Python has a lexer, tokeniser and parser. Does it go through all the code, parse it before executing them line by line?

Is that why it's able to say there's a local varialbe down the function?

The problem is not the order of interpretation, which is top to bottom as you expect; it's the scope. In Python, when referencing a global variable in a narrower function scope, if you modify the value , you must first tell the code that the global variable is the variable you are referencing, instead of a new local one. You do this with the global keyword. In this example, your program should actually look like this:

c = 10

def myfunc():
    global c
    print(c)
    c = 1


myfunc()

Miles C. is correct. I'd guess though from your code you are coming over from a structured language such as C or C++. Python won't reference variables the same way C or C++ does it needs to be told to do so. The global keyword tells python you are looking for the variable outside of the function.

Before the interpreter takes over, Python performs three other steps: lexing, parsing, and compiling. Together, these steps transform the source code from lines of text into byte code containing instructions that the interpreter can understand. The interpreter's job is to take these code objects and follow the instructions.

在此处输入图像描述

So the error is produced by Python when it is translating the source code into byte code. Syntax errors will completely stop the execution and during this step, scope is also decided. This is because the byte code will need to reference the correct variable locations.

To answer your question:

Does it go through all the code, parse it before executing them line by line?

Yes, it does.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM