Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 976
Alex Lee Avatar asked Sep 04 '25 02:09

Alex Lee


1 Answers

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.

like image 95
Kuldeep Pal Avatar answered Sep 07 '25 07:09

Kuldeep Pal