0

With frozen dataclasses we have something which resembles immutability. But when creating one such instance, I want to be sure that the init data is actually valid. Example:

from dataclasses import dataclass, field
import datetime 

@dataclass(frozen=True)
class Employee:
    employeeId: str # should never be None
    name: str # should never be None or empty
    dateOfBirth: datetime.date # could be None if unknown

Is there a way to specify these conditions (probably through annotations) so that we get a ValueError if the condition is not met?

Arne
  • 17,706
  • 5
  • 83
  • 99
Philipp
  • 4,659
  • 9
  • 48
  • 69
  • The last field could be specified as `dateOfBirth: Optional[datetime.date]` to indicate that `None` is an acceptable value. Still no checking though. – Philipp Apr 21 '20 at 14:56
  • 1
    @Arne Yes! Given that `None` is a separate type, this works for none-checking. For other value checks (e.g string not empty) we can use __post_init__() – Philipp Apr 26 '20 at 06:05

0 Answers0