October 25, 2024
Chicago 12, Melborne City, USA
python

How to type hint a method returning a list of generic dataclass instances?


I was wondering if it was possible to get a Union return type for get_bars in this scenario:

from dataclasses import dataclass


@dataclass
class Bar[T]:
    a: T

@dataclass
class Foo:
    bars: list[Bar]

    def get_bars(self):
        return self.bars

I’m not sure on how to type bars in Foo (or which TypeVar pass to Foo), the idea would be that get_bars should return a Union of Bar[T] for instance

foo = Foo(bars=[Bar[int](a=1), Bar[str](a="bar")])
foo.get_bars()  # Should be inferred as a Union[Bar[int], Bar[str]]



You need to sign in to view this answers

Leave feedback about this

  • Quality
  • Price
  • Service

PROS

+
Add Field

CONS

+
Add Field
Choose Image
Choose Video