如何解决Python 版本依赖类型注解
问题:
我想对 collections.deque
使用类型注释,但由于我们必须支持较旧的 Python 版本(确切地说是 3.4 和 3.5 - 而且它们不是官方并不重要 em> 支持),我希望我的代码在我们必须支持的所有 Python 版本中都有效。
我的原始代码:
from collections import deque
from typing import Deque
a = deque() # type: Deque[int]
它在 3.7 中运行良好,但在 3.5 中,我得到 ImportError: cannot import name 'Deque'
。
我的尝试:
所以我想像这样修改它:
from typing import Sequence
try:
from typing import Deque
except ImportError:
Deque = Sequence
from collections import deque
a = deque() # type: Deque[int]
但后来出现错误:
$ mypy . --pretty
a.py:5: error: Cannot assign multiple types to name "Deque" without an explicit "Type[...]" annotation
Deque = Sequence
^
a.py:5: error: Incompatible types in assignment (expression has type "Type[Sequence[Any]]",variable has
type "Type[deque[Any]]")
Deque = Sequence
^
Found 2 errors in 1 file (checked 1 source file)
问题:
有没有办法让相同的代码即使在 python3.4 和 python3.5 中也有效,同时具有双端队列的类型注释?
注意:
是的,我知道 3.4 和 3.5 不受官方支持。但这个事实对我一点帮助都没有。请不要告诉我升级。
解决方法
类型检查器使用自己版本的 typing
功能,无论运行时 typing
库是否支持它们。诸如 Deque[int]
之类的类型可以自由用于检入任何版本,只要它不在运行时使用即可。
-
如果
typing
模块适用于所有需要的版本,guard the imports:from collections import deque from typing import TYPE_CHECKING if TYPE_CHECKING: # not entered at runtime from typing import Deque # only happens during static type checking a = deque() # type: Deque[int]
typing
模块可以作为 a backport 添加到 3.5 之前的版本中。 -
不支持所有必需类型功能的版本的通用解决方案是
pyi
stub files。# a.py from collections import deque a = deque()
# a.pyi from typing import Deque a: Deque[int] = ...
也许这(或它的变体)会起作用
import sys
if sys.version_info[:2] >= (3,7):
from typing import Deque
else:
from typing import Sequence as Deque
from collections import deque
a = deque() # type: Deque[int]
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。