Python typing multiple inheritance as parameter

Viewed 1251

I want to explicitly type a function parameter, that needs to inherit from two classes. Example:

class SomeInterface:
    def first_function():
        pass

class SuperClass:
    def other_function():
        # implementation here
    # more function definitions

class C(A, B):
    # overrides first_function

def my_typed_function(param: Union[A,B]):
    param.first_function() # mypy: variant B does not have that function
    param.other_function() # mypy: variant A does not have that function

What can I use instead of Union to show that relationship? (Keep in mind that there can also be other implementations like C passed to this, so I cannot explicitly use C)

I also looked into typing protocols and defined A as a Protocol, but running into the same problem since B is an actual class and cannot be combined into the protocol.

1 Answers

I solved it by defining an intermediate abstract class:

class MyMixedType(A,B):
    pass

class C(MyMixedType):
    # very specific implementation

def my_typed_function(param: MyMixedType):
    ...

BUT this only works since I can have all classes implement MyMixedType and thus offloading the multiple inheritance to one level above.

Related: how to verify a type has multiple super classes (thanks @khelwood)
After looking into the question and numerous linked github issues, this seems to be an ongoing issue since ~2018. A solution would be called Intersection but is to the best of my knowledge still not implemented. PyCharm/IntelliJ seem to support it though with their in-editor type checking.

Related