【问题标题】:How to use isinstance on a generic type in Python如何在 Python 中的泛型类型上使用 isinstance
【发布时间】:2021-04-03 04:42:20
【问题描述】:

我正在尝试检查参数是否是类声明中指定的泛型类型的实例。但是 Python 似乎不允许这样做。

T = TypeVar('T')
class MyTypeChecker(Generic[T]):
    def is_right_type(self, x: Any):
        return isinstance(x, T)

这给出了错误'T' is a type variable and only valid in type context

【问题讨论】:

  • 类型提示不是类型。在实际的python类型的意义上,没有“通用类型*”之类的东西。此外,如错误消息中所述,T 是一个类型变量.

标签: python mypy


【解决方案1】:

您可以使用__orig_class__ 属性,但请记住,这是一个实现细节,在answer 中有更详细的说明。

from typing import TypeVar, Generic, Any
T = TypeVar('T')


class MyTypeChecker(Generic[T]):
    def is_right_type(self, x: Any):
        return isinstance(x, self.__orig_class__.__args__[0])  # type: ignore


a = MyTypeChecker[int]()
b = MyTypeChecker[str]()

print(a.is_right_type(1))  # True
print(b.is_right_type(1))  # False
print(a.is_right_type('str'))  # False
print(b.is_right_type('str'))  # True

【讨论】:

    猜你喜欢
    • 2021-10-22
    • 1970-01-01
    • 2021-09-21
    • 2017-02-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-14
    相关资源
    最近更新 更多