Please someone correct me if am wrong, but I believe dataclasses does not force type. datetime.datetime in your example is (almost) merely an annotation, apart from two implementation details. Check the documentation. Specifically,
The dataclass() decorator examines the class to find fields. A field is defined as class variable that has a type annotation. With two exceptions described below, nothing in dataclass() examines the type specified in the variable annotation.
The two exceptions have nothing to do with forcing data types:
Class variables
One of two places where dataclass() actually inspects the type of a field is to determine if a field is a class variable as defined in PEP 526. It does this by checking if the type of the field is typing.ClassVar. If a field is a ClassVar, it is excluded from consideration as a field and is ignored by the dataclass mechanisms. Such ClassVar pseudo-fields are not returned by the module-level fields() function.
Init-only variables
The other place where dataclass() inspects a type annotation is to determine if a field is an init-only variable. It does this by seeing if the type of a field is of type dataclasses.InitVar. If a field is an InitVar, it is considered a pseudo-field called an init-only field. As it is not a true field, it is not returned by the module-level fields() function. Init-only fields are added as parameters to the generated __init__()
method, and are passed to the optional __post_init__()
method. They are not otherwise used by dataclasses.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…