问题描述
我正在尝试了解 python 3 的较低级别的实现.子进程模块使用了一个名为 _posixsubprocess 的模块.我试图在我的系统中找到这个模块的位置,发现它是一个存根文件.
I am trying to understand the lower level implementations of python 3. There is one module named _posixsubprocess used by the subprocess module. I tried to find the location of this module in my system and found that it's a stub file.
由于我不知道存根文件是什么以及它们如何在较低级别实现,因此有人可以指导我吗?
Could someone guide me as I have no idea about what are the stub files and how are they implemented at the lower level?
推荐答案
_posixsubprocess
您引用的文件是用 C 编写的 Python 模块.它不是存根"文件.真正的实现可以在 Modules/_posixsubprocess 的标准库中找到.c
.您可以通过查看 构建 C 和 C++ 来了解如何编写 C/C++ 扩展扩展.这应该有助于您理解 _posixsubprocess.c
中的代码.
_posixsubprocess
The file you are referencing is a Python module written in C. It's not a "stub" file. The real implementation can be found in the stdlib at Modules/_posixsubprocess.c
. You can see how writing a C/C++ extension is written by having a look at Building C and C++ Extensions. This should help you understanding the code in _posixsubprocess.c
.
为了将类型提示添加到该文件(它是用 C 编写的扩展模块"),类型提示被添加到扩展名为 .pyi 的存根"文件中代码>.
In order to add type-hints to that file (which is an "Extension Module" as it is written in C), the type hints are added to a "stub" file with the extension .pyi
.
该文件可以在 typeshed 中找到这是存根文件的集合.typeshed 还包含第三方模块的存根,这是一个历史遗留问题.由于 PEP-561 已被采用,因此不再需要.
That file can be found in the typeshed which is a collection of stub files. The typeshed also contains stubs for third-party modules which is a historical remnant. That is no longer needed since PEP-561 has been adopted.
存根文件包含普通 Python 模块的类型提示信息.完整的官方文档可以在关于 PEP 中的存根文件部分找到-484.
Stub files contain type-hinting information of normal Python modules. The full official documentation can be found in the section about stub-files in PEP-484.
例如,如果你有一个 Python 模块 mymodule.py
像这样:
For example, if you have a Python module mymodule.py
like this:
def myfunction(name):
return "Hello " + name
然后您可以通过存根文件 mymodule.pyi
添加类型提示.请注意,这里的省略号 (...
) 是语法的一部分,因此下面的代码块确实显示了完整的文件内容:
Then you can add type-hints via a stub-file mymodule.pyi
. Note that here the ellipsis (...
) is part of the syntax, so the code-block below really shows the complete file contents:
def myfunction(name: str) -> str: ...
它们看起来与 C 头文件非常相似,因为它们只包含函数签名,但它们的使用完全是可选的.
They look very similar to C header files in that they contain only the function signatures, but their use is purely optional.
您也可以直接在 .py
模块中添加类型提示,如下所示:
You can also add type hints directly in the .py
module like the following:
def myfunction(name: str) -> str:
return "Hello " + name
但在某些情况下,您希望将它们分开存放在存根中:
But there are some cases where you want to keep them separate in stubs:
- 您希望保持您的代码与 Python 2 兼容并且不喜欢
# 类型:...
注释语法 - 您将函数注释用于其他用途,但仍想使用类型提示
- 您正在将类型提示添加到现有代码库中,并希望将现有文件中的代码搅动降至最低
这篇关于python中存根文件(.pyi)的用途是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!