python - (任何)python 模块的类型提示是什么?

标签 python python-3.x pycharm type-hinting python-typing

我想为模块(类“模块”)添加 (Python3) 类型提示。 typing 包没有提供,types.ModuleType() 是一个构造函数,它返回特定名称的模块对象。

例子:

import types
def foo(module: types.ModuleType):
   pass

至少在 PyCharm 中的结果是

"Cannot find reference ModuleType in types.pyi".

请注意 Python typing for module type没有回答我的问题,因为它没有解释 ModuleType 既是构造函数又是类型,如下所述。

最佳答案

and types.ModuleType() is a constructor.

那没关系。 types.ModuleType 仍然是对类型的引用,就像 strint 一样。不需要generic Module[typehint] 注释,所以 types.ModuleType 正是您需要在这里使用的。

比如官方Python typeshed project提供一个 type hint annotation for sys.modules作为:

from types import FrameType, ModuleType, TracebackType

# ...

modules: Dict[str, ModuleType]

不要被这里的名字搞糊涂了; types.ModuleType 是对模块类型的引用。它不是一个单独的工厂功能或其他东西。 CamelCase 名称遵循该模块的约定,您使用该引用是因为该类型对象不能作为内置对象使用。 types 模块 assigns the value of type(sys) to the name .

如果 PyCharm 在查找 types.ModuleType stub 时遇到问题,那么这可能是 PyCharm 本身的问题(错误),或者当前捆绑的 stub 已过时,或者您使用了不完整的类型 stub 集。请参阅 how to use custom stubs 上的 PyCharm 文档提供一个新的集合。

如果这不起作用,则可能是 PyCharm 中处理导出 类型提示概念的错误。当前输入 defines the ModuleType type hints in a separate module , 然后是 imported into the types.pyi stubfile使用 from module import name as name 语法。 PEP 484指出导入的类型提示不是 stub 的一部分除非您使用as 语法:

Modules and variables imported into the stub are not considered exported from the stub unless the import uses the import ... as ... form or the equivalent from ... import ... as ... form.

可能是 PyCharm 还没有正确处理这种情况。

关于python - (任何)python 模块的类型提示是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53780735/

相关文章:

python - Matplotlib 不同大小的子图

python-3.x - 如果文件不存在,则创建一个数据框

python - 在 python 上将文件读入列表中。怎样取出单词

python - pycharm:字节文字包含字符 > 255

python - 从鼠标单击事件获取行和列

Python2.7 日志级别的日志记录不起作用

python - 调试: Running Python Script from Windows task Manager

python - 通过装饰器注入(inject)类属性

Webfaction 上的 Django 站点 - 信息流如何工作,以及与 Pycharm 远程开发人员集成

python - 为什么 Python `NamedTemporaryFile` 不默认 `delete` 到 `False` ?