Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

128
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda