模块在 Python 中有类型吗?

Do modules have types in Python?

我正在阅读 PEP338。有些词让我感到困惑:

If the module is found, and is of type PY_SOURCE or PY_COMPILED , then the command line is effectively reinterpreted from python <options> -m <module> <args> to python <options> <filename> <args> .

模块是否具有 Python 中的类型?

可以从不同的来源加载模块。作者提到了加载模块的 2 个具体来源,请参阅 imp module documentation:

imp.PY_SOURCE
The module was found as a source file.

[...]

imp.PY_COMPILED
The module was found as a compiled code object file.

[...]

imp.C_EXTENSION
The module was found as dynamically loadable shared library.

这些值用于 imp.get_suffixes() function 的 return 值等。

PEP 声明仅支持从源文件(.py 文件)和字节码缓存文件(.pyc)加载的模块; -m 开关不支持 C 扩展模块(通常是 .so.dll 动态加载的库)。

生成的模块对象仍然只是一个模块对象;您找到的文本中的 type 一词不是指 Python 的类型系统。

模块的类型表示存储模块的文件类型,因为python文件有一些可能的类型(和扩展名。

最常见的是已编译的 python 文件(pyc 扩展名)或常规 python 纯源文件(py).

还有许多其他 py 文件扩展名,请在此处查看(几乎)完整列表:。

引用自 link PEP338

Proposed Semantics The semantics proposed are fairly simple: if -m is used to execute a module the PEP 302 import mechanisms are used to locate the module and retrieve its compiled code, before executing the module in accordance with the semantics for a top-level module.

现在让我们参考imp(导入机制)的文档,确定可以导入的不同类型的模块 imp.get_suffixes()

imp.get_suffixes() Return a list of 3-element tuples, each describing a particular type of module. Each triple has the form (suffix, mode, type), where suffix is a string to be appended to the module name to form the filename to search for, mode is the mode string to pass to the built-in open() function to open the file (this can be 'r' for text files or 'rb' for binary files), and type is the file type, which has one of the values PY_SOURCE, PY_COMPILED, or C_EXTENSION, described below.

随后它解释了不同的类型是什么

imp.PY_SOURCE The module was found as a source file.

imp.PY_COMPILED The module was found as a compiled code object file.

imp.C_EXTENSION The module was found as dynamically loadable shared library.

因此,PEP 338 中提到的类型只不过是可以导入的模块类型,而这些类型中只有 PY_SOURCE 或 PY_COMPILED 是上述三种类型中仅有的两种类型命令行从 python -m 有效地重新解释为 python .