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

ccl*_*uss 5 typing subtype isinstance python-3.x subtyping

如何在 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
    """
    try:  # Python 2
        return issubclass(type_, typeinfo)
    except TypeError:  # Python 3: "typing.List[str]".startswith("typing.List")
        return repr(type_).startswith(repr(typeinfo))
Run Code Online (Sandbox Code Playgroud)