Python解释器实际上是如何解释程序的?

Kee*_*san 3 python interpreter python-internals

举一个示例程序:

c = 10

def myfunc():
    print(c)

myfunc()
Run Code Online (Sandbox Code Playgroud)

这按预期打印 10,但如果我们看另一个程序:


c = 10

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


myfunc()
Run Code Online (Sandbox Code Playgroud)

它说:local variable 'c' referenced before assignment

在这里,如果 python 解释器实际上是逐行运行的,那么它不应该10在到达下一行之前打印以得出存在局部变量的结论吗?

Python 有词法分析器、分词器和解析器。它是否会遍历所有代码,在逐行执行之前对其进行解析?

这就是为什么它能够说函数下面有一个局部变量吗?

krm*_*ogi 7

介绍

在解释器接管之前,Python 会执行另外三个步骤:词法分析、解析和编译。这些步骤共同将源代码从文本行转换为包含解释器可以理解的指令的字节代码。解释器的工作是获取这些代码对象并遵循说明。

在此输入图像描述

为什么?

所以这个错误是Python在将源代码翻译成字节码时产生的。在此步骤中,范围也被确定。这是因为字节码需要引用正确的变量位置。但是,在这种情况下,它现在连接到引用范围中未定义的变量,从而导致运行时错误。

例子

在这段代码中,没有语法错误,也没有范围错误。

c = 10

def myfunc():
    print(c)

myfunc()
Run Code Online (Sandbox Code Playgroud)

在此程序中,c = 1隐式使变量成为本地变量。然而, this 是在 which的范围内尚未定义之后定义的。print(c)

c = 10

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

myfunc()
Run Code Online (Sandbox Code Playgroud)

所以如果你这样做:

c = 10

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


myfunc()
Run Code Online (Sandbox Code Playgroud)

或者

c = 10

def myfunc():
    global c # Changes the scope of the variable to make it accessible to the function
    print(c)
    c = 1


myfunc()
Run Code Online (Sandbox Code Playgroud)

该代码可以正常工作。

结论

回答你的问题:

它是否会遍历所有代码,在逐行执行之前对其进行解析?

是的,它确实。