小编ccl*_*uss的帖子

Python 3:类型错误:下标泛型不能与类和实例检查一起使用

如何在 Python 2 和 Python 3 中测试子类型?

在 Python 2.7.18 中:

>>> import typing
>>> type_ = typing.List[str]
>>> issubclass(type_, typing.List)
True
Run Code Online (Sandbox Code Playgroud)

但在 Python 3.9.10 中,我得到:

TypeError: Subscripted generics cannot be used with class and instance checks

以下内容适用于我的情况,但它是一个黑客!最好在未来版本的 Python 中看到更强大的实现作为内置函数。

def _issubtype(type_, typeinfo):
    """
    Python 3 workaround for:
    TypeError: Subscripted generics cannot be used with class and instance checks

    Does not deal with typing.Union and probably numerous other corner cases.
    >>> _issubtype(typing.List[str], typing.List)
    True
    >>> _issubtype(typing.Dict[str, str], typing.List)
    False
    """ …
Run Code Online (Sandbox Code Playgroud)

typing subtype isinstance python-3.x subtyping

5
推荐指数
0
解决办法
3559
查看次数

标签 统计

isinstance ×1

python-3.x ×1

subtype ×1

subtyping ×1

typing ×1