I'm looking to check if two variables are of the same type in python 3.x. What is the most ideal way to do this?
Take the following example:
class A():
def __init__(self, x):
self.x = x
class B(A):
def __init__(self, x):
x += 5
super(B, self).__init__(x)
Ideally, I'd like to return True
if two variables of type A
and B
are compared against one another. Here are some potential solutions that don't work:
>>> a = A(5)
>>> b = B(5)
>>>
>>> type(a) is type(b)
False
>>> isinstance(a, type(b))
False
>>> isinstance(b, type(a))
True
The last one isn't ideal because, as seen in the middle example, if the type being checked against is a subclass of the variable's type, False
is returned.
The only solution I've tried that can cover all bases here is:
>>> isinstance(a, type(b)) or isinstance(b, type(a))
True
Is there a better way?