PaxPrz
PaxPrz

Reputation: 1928

Python typing from List of classes

How to do python typing for list of classes.

Suppose I have following classes.

from dataclasses import dataclass

@dataclass
class A:
    name: str

@dataclass
class B:
   age: int

#...
CLASSES = [A, B]  #... more classes in list

Now I define a function that instantiate any one of the following class

def func(resource: Union[*CLASSES], value: Union[str, int]):
    return resource(value)

But type-hinting is not valid here. How to do type hinting from List?

Upvotes: 2

Views: 1585

Answers (1)

Grismar
Grismar

Reputation: 31389

This achieves what you want using a super-class that all the intended classes share:

from typing import Union
from dataclasses import dataclass


@dataclass
class MyDataMixin:
    pass


@dataclass
class A(MyDataMixin):
    name: str


@dataclass
class B(MyDataMixin):
    age: int


def func(resource: MyDataMixin, value: Union[str, int]):
    return resource

You can't use expansion in the type definition of the parameter like you were trying to do, that only works on variables at runtime.

As @Selcuk indicated in the comments, naming it MyDataMixin makes more sense, as the class is not intended to be used by itself. You could go further and ensure it's just an abstract class - but that's beyond the scope of the question.

Upvotes: 2

Related Questions