代码之家  ›  专栏  ›  技术社区  ›  Adam Smith

递归类型注释

  •  0
  • Adam Smith  · 技术社区  · 7 年前

    我试图在适用的情况下将静态类型注释引入我的代码库。一种情况是,在读取JSON时,生成的对象将是一个由字符串键控的字典,其值为以下类型之一:

    • bool
    • str
    • float
    • int
    • list
    • dict

    列表

    1 回复  |  直到 7 年前
        1
  •  6
  •   user2357112    7 年前

    从MyPy0.641开始,mypy不支持您正在寻找的那种递归类型注释。自然语法:

    from typing import Union, Dict, List
    
    JSONVal = Union[None, bool, str, float, int, List['JSONVal'], Dict[str, 'JSONVal']]
    
    d: JSONVal = {'a': ['b']}
    

    $ mypy asdf.py
    asdf.py:3: error: Recursive types not fully supported yet, nested types replaced with "Any"
    

    mypy issue tracker thread 关于递归类型支持。

    现在,, Dict[str, Any]

    推荐文章