【问题标题】:What's wrong when use mypy to check type使用 mypy 检查类型时有什么问题
【发布时间】:2018-05-15 07:48:41
【问题描述】:
from typing import Dict, List, Any, AnyStr, TypeVar
def abc(xyz: str) -> Dict[AnyStr, Any]:
    return {"abc": 1}

我使用 mypy 来检查这个文件。它给出了一个错误。

以下是错误信息

“字典条目 0 具有不兼容的类型“str”:“int”;预期的“bytes”: "任何""

但我不知道为什么

【问题讨论】:

    标签: annotations python-3.5 type-hinting mypy


    【解决方案1】:

    问题在于AnyStr 实际上是类型变量的别名。这意味着你的程序实际上完全等同于写作:

    from typing import Dict, Any, AnyStr, TypeVar
    
    T = TypeVar('T', str, bytes)
    
    def abc(xyz: str) -> Dict[T, Any]:
        return {"abc": 1}
    

    然而,这给我们带来了一个问题:mypy 应该如何推断您想要 T 的两种可能替代方案中的哪一种?

    有三种可能的修复方法。你可以...

    1. 在你的类型签名中找到至少两次或多次使用AnyStr 的方法。例如,也许您认为这真的更符合您的意思?

      def abc(xyz: AnyStr) -> Dict[AnyStr, Any]:
          # etc
      
    2. 使用Union[str, bytes] 代替AnyStr

      from typing import Union, Dict, Any
      
      def abc(xyz: str) -> Dict[Union[str, bytes], Any]:
          # etc
      

      如果类型签名开始变得过长,您可以使用类型别名来缩短它:

      from typing import Union, Dict, Any
      
      # Note: this isn't a great type alias name, but whatever
      UnionStr = Union[str, bytes]
      
      def abc(xyz: str) -> Dict[UnionStr, Any]:
          # etc
      

    【讨论】:

      猜你喜欢
      • 2020-03-17
      • 2016-09-02
      • 2021-05-01
      • 2022-10-13
      • 1970-01-01
      • 2021-11-25
      • 1970-01-01
      • 2014-07-09
      • 1970-01-01
      相关资源
      最近更新 更多