gpt4 book ai didi

python - 编译时检查以及主要脚本字节码存储在 Python 中的什么位置?

转载 作者:行者123 更新时间:2023-11-28 18:20:53 24 4
gpt4 key购买 nike

我是 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 脚本和模块的信息,例如 this , thisthis .


编辑:

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


编辑 2:

关于为什么主脚本字节码存储在内存中以及为什么模块被编译可以找到here .

最佳答案

  1. 不确定 python 中的确切编译过程。但是这里的“小检查”意味着在运行 python 文件时它将检查所有使用/导入的模块是否存在并具有引用但它不会检查变量或其类型。因为在 python 中我们不使用类型来声明变量。所以所有这些类型错误在编译时都会被忽略,只会在执行时遇到

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

希望有用!

关于python - 编译时检查以及主要脚本字节码存储在 Python 中的什么位置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45158191/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com