我想为模块(类“模块”)添加 (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
仍然是对类型的引用,就像 str
和 int
一样。不需要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 equivalentfrom ... import ... as ...
form.
可能是 PyCharm 还没有正确处理这种情况。
关于python - (任何)python 模块的类型提示是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53780735/