0

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?

  • I am not very familiar with the `marshmallow-dataclass` package, but it seems strange to do `Test.Schema().load(inp)` since `Test.Schema` is just an empty schema with no fields defined whatsoever (unlike `Test` itself). I don't understand how that would even validate anything at all. – Daniil Fajnberg May 03 '23 at 08:18
  • @DaniilFajnberg can't say I fully understand how the `Schema=marshmallow.Schema` attribute works either, but if you test this setup with values like `int`, `str`, etc. then you'll find that it loads according to the schema just fine (ofc it breaks with `datetimes` though..) – Steinn Hauser Magnússon May 03 '23 at 11:35

1 Answers1

0

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.

Jérôme
  • 13,328
  • 7
  • 56
  • 106