8

Mypy produce an error with this dataclass inheritance:

import dataclasses
import datetime

import typing


@dataclasses.dataclass
class Crud:
    creation_datetime: typing.Optional[datetime.datetime] = dataclasses.field(init=False)

    def __post_init__(self) -> None:
        self.creation_datetime = getattr(self, "creation_datetime", datetime.datetime.utcnow())


@dataclasses.dataclass
class MyFoo(Crud):
    name: str
t.py:17: error: Attributes without a default cannot follow attributes with one

Does exist a way to supress this error or design the code differently to avoid mypy error ?

bux
  • 7,087
  • 11
  • 45
  • 86
  • A technical explanation and a workaround are provided here: https://stackoverflow.com/questions/51575931/class-inheritance-in-python-3-7-dataclasses. It does not really answer to *why* though. – Joël Jan 26 '21 at 09:30

1 Answers1

-4

For information, this error can be avoided with # type: ignore

@dataclasses.dataclass
class MyFoo(Crud):
    name: str  # type: ignore
bux
  • 7,087
  • 11
  • 45
  • 86