繁体   English   中英

Python 版本相关类型注解

[英]Python version dependent type annotations

问题:

我想对collections.deque使用类型注释,但是由于我们必须支持旧的 python 版本(确切地说是 3.4 和 3.5 - 并且它们不受官方支持并不重要),我希望我的代码有效在我们必须支持的所有 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模块在所有需要的版本上都可用,请保护导入

     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模块可以作为backport添加到 pre-3.5 版本。

  • 不支持所有必需类型功能的版本的一般解决方案是pyi存根文件

     # 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]
    

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM