Daniel
Daniel

Reputation: 131

Matching an instance most specific class in python

Lets say I have three classes A, B and C, C extends B, and B extends A.

@dataclass
class A:
    value: int

class B(A):
    pass

class C(B):
    pass

In python 3.10 with the match feature introduced, I thought about changing isinstance-elif statements into a match-case statement. But i cant quite find the right syntax for it...

What I have tried so far...

match instance.__class__.__name__:
    case A.__name__:
        print('A')
    case B.__name__:
        print('B')

But what if two classes have the same __name__ prop. Here even a C instance wont match any case.

Next syntax... this one is better

match instance:
    case A():
        print('A')
    case B():
        print('B')

This syntax works quite good, except that a B instance will match the first case, so I will need to topologyically sort the classes in my match-case statement.

Additional Question: Is this a special syntax where no params are needed ?

Question: What other choices do I have ?

Upvotes: 2

Views: 784

Answers (1)

Maximilian Wolf
Maximilian Wolf

Reputation: 83

If you want to get the parent of the instance you could do instance.__class__.__bases__[0] __bases__ returns a tuple with the parent classess.


I tried that with the match statement but get the following warning:

match instance.__class__.__bases__[0]:
    case A:  # makes remaining clause unreachable
        print('A')
    case ...

Using A().__class__ instead, yields yet another error.. "Unexpected tokens"


Nevertheless, C().__class__.__bases__[0] == B yields True.

Upvotes: 4

Related Questions