【问题标题】:leverage mypy to annotate variables and return value利用 mypy 注释变量和返回值
【发布时间】:2021-07-03 21:50:31
【问题描述】:

安全获取嵌套 json 对象的常用函数。

def safe_get(dct, keys):
for key in keys.split("."):
    try:
        dct = dct[key]
    except:
        return None
return dct

利用 mypy 检查类型,如下所示。

    def safe_get(dct: dict, keys: str) -> Union[str,int,bool,None]:
    for key in keys.split("."):
        try:
            dct = dct[key]
        except:
            return None
    return dct

但是,当我在 strict 模式下运行 python3 -m mypy --follow-imports=silent --python-version ${PYTHON_VERSION} --strict --implicit-reexport ${SOURCES[@]} 时。它提示我

chalicelib/fly.py:31: error: Implicit generic "Any". Use "typing.Dict" and specify generic parameters
chalicelib/fly.py:37: error: Incompatible return value type (got "Dict[Any, Any]", expected "Union[str, bool, int, None]")
chalicelib/fly.py:40: error: Implicit generic "Any". Use "typing.Dict" and specify generic parameters
chalicelib/fly.py:41: error: Incompatible return value type (got "Union[str, int, None]", expected "str")
chalicelib/fly.py:44: error: Implicit generic "Any". Use "typing.Dict" and specify generic parameters
chalicelib/fly.py:45: error: Item "bool" of "Union[str, bool, int, None]" has no attribute "split"
chalicelib/fly.py:45: error: Item "int" of "Union[str, bool, int, None]" has no attribute "split"
chalicelib/fly.py:45: error: Item "None" of "Union[str, bool, int, None]" has no attribute "split"
chalicelib/fly.py:48: error: Implicit generic "Any". Use "typing.Dict" and specify generic parameters
chalicelib/fly.py:49: error: Incompatible return value type (got "Union[str, int, None]", expected "str")
chalicelib/fly.py:52: error: Implicit generic "Any". Use "typing.Dict" and specify generic parameters
chalicelib/fly.py:53: error: Incompatible return value type (got "Union[str, int]", expected "str")
chalicelib/fly.py:56: error: Implicit generic "Any". Use "typing.Dict" and specify generic parameters
chalicelib/fly.py:57: error: Incompatible return value type (got "Union[str, int]", expected "str")
chalicelib/fly.py:60: error: Implicit generic "Any". Use "typing.Dict" and specify generic parameters
chalicelib/fly.py:61: error: Incompatible return value type (got "Union[str, int, None]", expected "str")
chalicelib/fly.py:64: error: Implicit generic "Any". Use "typing.Dict" and specify generic parameters
chalicelib/fly.py:66: error: Item "str" of "Union[str, bool, int, None]" has no attribute "items"
chalicelib/fly.py:66: error: Item "bool" of "Union[str, bool, int, None]" has no attribute "items"
chalicelib/fly.py:66: error: Item "int" of "Union[str, bool, int, None]" has no attribute "items"
chalicelib/fly.py:66: error: Item "None" of "Union[str, bool, int, None]" has no attribute "items"
chalicelib/fly.py:78: error: Implicit generic "Any". Use "typing.Dict" and specify generic parameters
Found 23 errors in 1 file (checked 1 source file)

无论在哪里触发safe_get,它都可能返回strintboolNone。所以我使用 typing.Union 来聚合所有可能的类型。但是,mypy 似乎没有意义。任何人都可以建议在这种情况下如何注释返回值? 另外,请在下面找到mypy的配置。

[mypy]
python_version = 3.8
warn_unused_configs = True

[mypy-boto3.*]
ignore_missing_imports = True

[mypy-botocore.*]
ignore_missing_imports = True

[mypy-kubernetes.*]
ignore_missing_imports = True

【问题讨论】:

    标签: python-3.x mypy


    【解决方案1】:

    我认为您必须在输入中使用 Any 类型,因为循环类型定义很棘手:

    from typing import Any, Dict, Union
    
    def safe_get(dct: Dict[str, Any], keys: str) -> Union[str, int, bool, None]:
        d: Any = dct
        for key in keys.split("."):
            try:
                d = d[key]
            except KeyError:
                return None
        if isinstance(d, str) or isinstance(d, int) or isinstance(d, bool):
            return d
        return None
    

    【讨论】:

      猜你喜欢
      • 2017-11-22
      • 2019-02-15
      • 2023-04-02
      • 2020-08-24
      • 2012-05-20
      • 1970-01-01
      • 2023-03-23
      • 2021-10-20
      • 2022-01-12
      相关资源
      最近更新 更多