如何解决在任何地方使用`from __future__ import annotations` 有什么缺点吗?
从 PEP 563 来看,似乎应该有轻微的性能提升,因为它解决了
类型提示在模块导入时执行,这在计算上不是免费的。
那么...我可以/应该在我的包中的每个文件中包含 from __future__ import annotations
吗,或者是否有任何理由将其从某些文件中排除?
解决方法
TLDR:有些事情不适用于 from __future__ import annotations
。由于 Python 3.10 强制要求推迟评估,因此任何支持它的代码首先不应依赖这些功能。
由于 from __future__ import annotations
避免了类型提示的评估,任何依赖于评估类型提示的东西都必须 explicitly evaluate type hints。这在顶级模块或类范围之外通常是不可能的,除非明确处理 locals
。
例如,如果注释评估被推迟,functools.singledispatch
不能在函数内使用类型提示:
from __future__ import annotations
from typing import Type
from functools import singledispatch
def non_global_sdp(local_type: Type):
@singledispatch
def default(arg): print("default")
@default.register
def case_a(arg: local_type): print("case_a")
return default
cases = non_global_sdp(int) # NameError: name 'local_type' is not defined
由于自 Python 3.10 起必须推迟对注释的评估,因此任何打算与 Python 3.10 或更高版本一起使用的代码都应使用 from __future__ import annotations
以保持一致性。需要及时评估注释的功能在 Python 3.10+ 中根本无效,必须删除。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。