I'm working with a dataclass which follows a marshmallow Schema, where this is the setup:
from marshmallow_dataclass import dataclass
import datetime
from typing import ClassVar, Type
import marshmallow
class BaseClass:
Schema: ClassVar[Type[marshmallow.Schema]] = marshmallow.Schema # For the type checker
@dataclass
class Test(BaseClass):
time: datetime.datetime
and I'm coming across a strange error. I get an error depending on how I load the dataclass. In the example below, I would expect method1
and method2
to work the same way:
inp = {"time":datetime.datetime.now()}
method1 = Test(**inp) # works fine
method2 = Test.Schema().load(inp)
# >>> marshmallow.exceptions.ValidationError: {'time': ['Not a valid datetime.']}
These two loading methods seem to be equivalent for all kinds of types, but datetimes seem to be one of the types that causes an exception. Could anyone know the reason why?
Marshmallow schemas don't accept deserialized (object) form as input when deserializing (loading). You would need to pass a serialized datetime, like dt.datetime.now().isoformat()
.
It works with simple types like int
/float
because serialized and deserialized form is the same type.
See discussion in https://github.com/marshmallow-code/marshmallow/issues/1415.