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

What is the type hint for a (any) python module?

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

示例:

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

至少 PyCharm 结果

"Cannot find reference ModuleType in types.pyi".

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

and types.ModuleType() is a constructor.

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

比如官方Python typeshed project provides a 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 存根时遇到问题,那么这可能是 PyCharm 本身的问题(错误),或者当前捆绑的存根已过时,或者您使用了一组不完整的存根类型。请参阅 how to use custom stubs 上的 PyCharm 文档以提供新的集合。

如果这不起作用,可能是 PyCharm 处理 导出 类型提示概念的错误。 Typeshed 当前 defines the ModuleType type hints in a separate module, which are then imported into the types.pyi stubfile using the from module import name as name syntax. PEP 484 声明导入的类型提示不是存根的一部分 除非 您使用 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还没有正确处理这种情况。