Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

126
Views
Annotate dataclass class variable with type value

We have a number of dataclasses representing various results with common ancestor Result. Each result then provides its data using its own subclass of ResultData. But we have trouble to annotate the case properly.

We came up with following solution:

from dataclasses import dataclass
from typing import ClassVar, Generic, Optional, Sequence, Type, TypeVar


class ResultData:
    ...


T = TypeVar('T', bound=ResultData)


@dataclass
class Result(Generic[T]):
    _data_cls: ClassVar[Type[T]]
    data: Sequence[T]

    @classmethod
    def parse(cls, ...) -> T:
        self = cls()
        self.data = [self._data_cls.parse(...)]
        return self

class FooResultData(ResultData):
    ...

class FooResult(Result):
    _data_cls = FooResultData

but it stopped working lately with mypy error ClassVar cannot contain type variables [misc]. It is also against PEP 526, see https://www.python.org/dev/peps/pep-0526/#class-and-instance-variable-annotations, which we missed earlier.

Is there a way to annotate this case properly?

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

As hinted in the comments, the _data_cls attribute could be removed, assuming that it's being used for type hinting purposes. The correct way to annotate a Generic class defined like class MyClass[Generic[T]) is to use MyClass[MyType] in the type annotations.

For example, hopefully the below works in mypy. I only tested in Pycharm and it seems to infer the type well enough at least.

from dataclasses import dataclass
from functools import cached_property
from typing import Generic, Sequence, TypeVar, Any, Type


T = TypeVar('T', bound='ResultData')


class ResultData:
    ...


@dataclass
class Result(Generic[T]):
    data: Sequence[T]

    @cached_property
    def data_cls(self) -> Type[T]:
        """Get generic type arg to Generic[T] using `__orig_class__` attribute"""
        # noinspection PyUnresolvedReferences
        return self.__orig_class__.__args__[0]

    def parse(self):
        print(self.data_cls)


@dataclass
class FooResultData(ResultData):
    # can be removed
    this_is_a_test: Any = 'testing'


class AnotherResultData(ResultData): ...


# indicates `data` is a list of `FooResultData` objects
FooResult = Result[FooResultData]

# indicates `data` is a list of `AnotherResultData` objects
AnotherResult = Result[AnotherResultData]

f: FooResult = FooResult([FooResultData()])
f.parse()
_ = f.data[0].this_is_a_test  # no warnings

f: AnotherResult = AnotherResult([AnotherResultData()])
f.parse()

Output:

<class '__main__.FooResultData'>
<class '__main__.AnotherResultData'>

And of course, here is proof that it seems to be working on my end:

enter image description here

over 4 years ago · Santiago Trujillo Report

0

At the end I just replaced the variable in _data_cls annotation with the base class and fixed the annotation of subclasses as noted by @rv.kvetch in his answer.

The downside is the need to define the result class twice in every subclass, but in my opinion it is more legible than extracting the class in property.

The complete solution:

from dataclasses import dataclass
from typing import ClassVar, Generic, Optional, Sequence, Type, TypeVar


class ResultData:
    ...


T = TypeVar('T', bound=ResultData)


@dataclass
class Result(Generic[T]):
    _data_cls: ClassVar[Type[ResultData]]  # Fixed annotation here
    data: Sequence[T]

    @classmethod
    def parse(cls, ...) -> T:
        self = cls()
        self.data = [self._data_cls.parse(...)]
        return self

class FooResultData(ResultData):
    ...

class FooResult(Result[FooResultData]):  # Fixed annotation here
    _data_cls = FooResultData
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!