在 python 3.7 中,如何检查 x=typing.List[str] 是“of”typing.List?

jba*_*sko 7 typing python-3.7

我将类型信息存储在变量中x

x = typing.List[str]
Run Code Online (Sandbox Code Playgroud)

稍后,它x与 一起传递x_value,我想根据是否x 为 ​​来 typing.List切换逻辑。我知道typing不应该与 一起使用isinstanceissubclass因此我说is of。是否有任何标准的、面向未来的(和 Python 3.6 证明)方法可以做到这一点issubtype

import sys
from typing import List


def issubtype(sub_type, parent_type):
    if sys.version_info >= (3, 7):
        if not hasattr(sub_type, '__origin__') or not hasattr(parent_type, '__origin__'):
            return False

        if sub_type.__origin__ != parent_type.__origin__:
            return False

        if isinstance(parent_type.__args__[0], type):
            return sub_type.__args__ == parent_type.__args__

        return True

    else:
        if not hasattr(sub_type, '__extra__') or not hasattr(parent_type, '__extra__'):
            return False

        if sub_type.__extra__ != parent_type.__extra__:
            return False

        if not parent_type.__args__ or parent_type.__args__ == sub_type.__args__:
            return True

    return False


assert issubtype(List[str], List[str])
assert issubtype(List[str], List)
assert issubtype(List[int], List[int])
assert not issubtype(List[int], List[str])
Run Code Online (Sandbox Code Playgroud)

当尝试实现这个时,我意识到任何好的解决方案都必须递归地检查参数(我的尝试没有这样做,但对我来说,只知道一个东西是否是一个列表就足够了)。