代码之家  ›  专栏  ›  技术社区  ›  Cameron Bieganek

确定对象类型是否与通过类型模块定义的嵌套类型匹配

  •  0
  • Cameron Bieganek  · 技术社区  · 7 年前

    打字 模块,可以指定任意嵌套类型,例如 List[str] Dict[str, Dict[str, float]] . 是否有方法确定对象的类型是否与此类类型匹配?有点像

    >>> from typing import List
    >>> isinstance(['a', 'b'], List[str])
    # Traceback (most recent call last):
    #   File "<stdin>", line 1, in <module>
    #   File "/home/cbieganek/anaconda3/lib/python3.6/typing.py", line 1162, in __instancecheck__
    #     return issubclass(instance.__class__, self)
    #   File "/home/cbieganek/anaconda3/lib/python3.6/typing.py", line 1148, in __subclasscheck__
    #     raise TypeError("Parameterized generics cannot be used with class "
    # TypeError: Parameterized generics cannot be used with class or instance checks
    

    我没想到 isinstance() 为了这个工作,但我想知道是否有其他公认的方法。

    1 回复  |  直到 7 年前
        1
  •  2
  •   schtsch    7 年前

    泛型作为类型的一部分出现在python中 hinting . 使用方便 列表[ STR ] 是变量或函数参数的类型提示:

    my_list: List[str] = ['1', '2']
    

    def do_something(strings: List[str])->None:
        ...
    

    大多数现代的IDE(如pycharm或athom)都有插件,它们支持对python代码进行静态类型检查,还可以查看 mypy . 如果需要严格的运行时类型检查,可以遍历列表并检查每个项类型,但这不是一个好的设计。

    推荐文章