dataclasses-json icon indicating copy to clipboard operation
dataclasses-json copied to clipboard

Encoder/Decoder example from readme is broken

Open RevanthRameshkumar opened this issue 3 years ago • 1 comments

from dataclasses import dataclass, field
from dataclasses_json import dataclass_json, config
from datetime import datetime
from marshmallow import fields

@dataclass_json
@dataclass
class DataClassWithIsoDatetime:
    created_at: datetime = field(
        metadata=config(
            encoder=datetime.isoformat,
            decoder=datetime.fromisoformat,
            mm_field=fields.DateTime(format='iso')
        )
    )

p = DataClassWithIsoDatetime(created_at='2013-10-29T09:14:03.895210')

the type of p.created_at is still a string, not a datetime. I made a customer decoder to check this, and it turns out the call is never made

RevanthRameshkumar avatar Feb 16 '21 18:02 RevanthRameshkumar

Hi @RevanthRameshkumar,

There is this line in the docs:

Note that these hooks will be invoked regardless if you're using .to_json/dump/dumps and .from_json/load/loads.

Therefore, when you instantiate the object via the class constructor, you have to give the proper types yourself, in this case, a datetime object, as show here:

created_at: datetime = field(...)

I've just tested the example, by using the following and it works:

serialised = '{"created_at": "2013-10-29T09:14:03.895210"}'
deserialised = DataClassWithIsoDatetime.from_json(serialised)
assert isinstance(deserialised.created_at, datetime)

mcteo avatar Mar 12 '21 12:03 mcteo