Alex Lee
Alex Lee

Reputation: 337

How to express multiple inheritance in Python type hint?

In Java, C#, a generic method can have a type parameter with constraint to define the interfaces that must be implemented.

static <T extends Iterable<Integer> & Comparable<Integer>> void test(T p) {

}

In Python, If I want to use type hint to specify that a variable must inherit classes A and B, how can I do it? I checked the typing module, it only has a Union which means the type of the variable can be any of the hint, not all of the hint.

Creating a new class C which inherits A and B seems a solution, but looks cumbersome.

Upvotes: 30

Views: 10666

Answers (1)

Kuldeep Pal
Kuldeep Pal

Reputation: 47

That class definition is equivalent to:

class MyIter(Iterator[T], Generic[T]):
    ...

You can use multiple inheritance with Generic:

from typing import TypeVar, Generic, Sized, Iterable, Container, Tuple

T = TypeVar('T')

class LinkedList(Sized, Generic[T]):
    ...

K = TypeVar('K')
V = TypeVar('V')

class MyMapping(Iterable[Tuple[K, V]],
                Container[Tuple[K, V]],
                Generic[K, V]):
    ...

Subclassing a generic class without specifying type parameters assumes Any for each position. In the following example, MyIterable is not generic but implicitly inherits from Iterable[Any]:

from typing import Iterable

class MyIterable(Iterable):  # Same as Iterable[Any]
    ...

Generic metaclasses are not supported.

Upvotes: 3

Related Questions