【问题标题】:How to test for approximate equality of generic classes如何测试泛型类的近似相等性
【发布时间】:2019-10-09 08:49:51
【问题描述】:

我试图找出两个类是否等效,忽略类型参数。说我有

from typing import Generic, TypeVar

T = TypeVar('T')

class A(Generic[T]):
    pass

class B(Generic[T], A[T]):
    pass

class X:
    pass

我希望后面的每一行都是等价的

Generic, Generic[T]
A, A[T], A[str], A[int]
B, B[T], B[str], B[int]
X

is==isinstancetype__class__ 均无效。比较 __name__ 对于定义另一个具有相同名称的类的人来说是脆弱的。

对于奖励积分*,我还对另一种测试等效性的方法感兴趣

A, A[T], A[str], A[int], B, B[T], B[str], B[int]

*不是赏金:p

(上下文是我想查找除Generic之外的一个类的所有子类)

【问题讨论】:

    标签: python python-3.x generics equality python-typing


    【解决方案1】:

    要从A[T] 恢复A,您可以使用__origin__ 属性,对于A,该属性将为None

    def compare(a, b):
        if hasattr(a, "__origin__") and hasattr(b, "__origin__"):
            a_origin = a.__origin__ or a
            b_origin = b.__origin__ or b
            return a_origin == b_origin
        else:
            return a == b
    
    compare(A, A[int])  # True
    compare(A, B[int])  # False
    compare(A, A)  # True
    compare(X, X)  # True
    

    根据链接的评论,__origin__ 应该可用于UnionOptionalGenericCallableTuple

    值得注意的是,这是一个实现细节。使用它会使您面临实施更改而没有警告的风险。

    【讨论】:

      猜你喜欢
      • 2013-10-03
      • 1970-01-01
      • 2011-01-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-09-01
      相关资源
      最近更新 更多