编译时检查和Python中主脚本字节码存储在哪里?

2024-04-24 09:02:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我是Python的新手,需要学习多个在线教程。其中一个是Google for Education。在

Google's tutorial中有一个部分:

Code Checked at Runtime

Python does very little checking at compile time, deferring almost all type, name, etc. checks on each line until that line runs. Suppose the above main() calls repeat() like this:

def main():
if name == 'Guido':
    print repeeeet(name) + '!!!'
else:
    print repeat(name)

The if-statement contains an obvious error, where the repeat() function is accidentally typed in as repeeeet(). The funny thing in Python ... this code compiles and runs fine so long as the name at runtime is not 'Guido'. Only when a run actually tries to execute the repeeeet() will it notice that there is no such function and raise an error. This just means that when you first run a Python program, some of the first errors you see will be simple typos like this. This is one area where languages with a more verbose type system, like Java, have an advantage ... they can catch such errors at compile time (but of course you have to maintain all that type information ... it's a tradeoff).

这一节中有一个很好的运行时检查示例,但没有编译时检查示例。在

我有兴趣了解编译时的小检查。在

我在网上找不到关于那条线的任何信息。每个可能的搜索都会返回有关编译python脚本和模块的信息,例如thisthisthis。在


编辑:

python myscript.py被编译(否则我们不会得到错误),然后解释为执行。那个么编译过程肯定会产生一个代码(可能是字节码)。代码是否存储在内存中,而不是作为.pyc存储在文件系统中?在


编辑2:

有关为什么主脚本字节码存储在内存中以及为什么要编译模块的详细信息,请参阅here。在


Tags: thenameyouanthattimeistype
1条回答
网友
1楼 · 发布于 2024-04-24 09:02:06
  1. 不确定python中确切的编译器过程。但是这里的“小检查”意味着在运行python文件时,它将检查使用/导入的所有模块是否存在并具有引用,但它不会检查变量或其类型。因为在python中我们不使用类型来声明变量。因此,所有此类类型错误在编译时都会被忽略,并且只在执行期间遇到

  2. 将为导入的模块创建一个pyc文件,并将它们放在包含py文件的同一目录中。然而。。。不会为程序的主脚本创建pyc文件。换句话说。。。如果你叫“python”myscript.py“在命令行上,没有myscript.py. 因为它是主脚本,所以编译后的pyc不可重用。。但是如果它是一个模块(没有main),那么无论何时导入它,都可以重用相同的pyc。

希望有用!在

相关问题 更多 >