该typing
模块导出两个类io
和re
作为“伪子模块”,如下所示。通过__all__
将它们添加并添加到模块中,使它们看起来像模块的目的是什么sys.modules
?
我理解的理由背后来自排除他们__all__
:让from typing import *
不会掩盖io
和re
如果这些都是进口的。
但是,为什么加'typing.re'
和'typing.io'
来sys.modules
?
来自的片段typing.py
:
import re as stdlib_re
# The pseudo-submodules 're' and 'io' are part of the public
# namespace, but excluded from __all__ because they might stomp on
# legitimate imports of those modules.
# ...
class io:
"""Wrapper namespace for IO generic classes."""
__all__ = ['IO', 'TextIO', 'BinaryIO']
IO = IO
TextIO = TextIO
BinaryIO = BinaryIO
io.__name__ = __name__ + '.io'
sys.modules[io.__name__] = io
Pattern = _alias(stdlib_re.Pattern, AnyStr)
Match = _alias(stdlib_re.Match, AnyStr)
class re:
"""Wrapper namespace for re type aliases."""
__all__ = ['Pattern', 'Match']
Pattern = Pattern
Match = Match
re.__name__ = __name__ + '.re'
sys.modules[re.__name__] = re
最初的目的是键入模块将在标准库中累积许多类的“类型化版本”,例如,诸如Pattern
in中typing.re
的BinaryIO
类型或in中的类型typing.io
。
在那种情况下,为了组织目的,尝试将这些“幻像类型”命名为子模块式的东西是有意义的。因此,例如,typing.re.Pattern
它将是该Pattern
类型的规范家,并且typing.Pattern
为了方便起见,将其重新导出。
在实践中,这种愿景从未真正实现:我怀疑这部分是因为PEP 484类型检查器的类型推断功能足够复杂,可以使您避免在很多情况下必须明确提供类型提示,部分原因是因为它终止了只是将这些类型直接包含typing
在与相关标准库模块相对应的存根中或包含在其中更加方便。
因此,决定(实际上相当近期)决定不赞成使用这两个模块:请参阅https://github.com/python/typing/issues/589和https://github.com/python/cpython/pull / 10173。总之,这个文档上周刚刚进行了更新,从来不提typing.io
和typing.re
-新的建议是直接从导入相关类型的typing
模块来代替。
可能在将来的Python版本中,这些模块将被完全删除,尽管由于向后兼容的原因它们可能会停留一些时间。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句