lidatong / dataclasses-json

Easily serialize Data Classes to and from JSON
MIT License
1.34k stars 151 forks source link

[BUG] global configuration of encoder/decoder for type T is not used for Optional[T] field #465

Closed PJCampi closed 2 months ago

PJCampi commented 11 months ago

Description

Let's say I register a custom encoder/decoder for type T in the global_config. I would expect that a dataclass with a field of type Optional[T] to use the encoder/decoder registered. Instead I have to manually register the same encoder for the type Optional[T] for the encoder to be picked up. _user_overrides_or_exts does not unwrap the optional type.

Code snippet that reproduces the issue

from dataclasses import dataclass
from dataclasses_json import dataclass_json, global_config
from datetime import date
from typing import Optional

global_config.encoders[date] = date.isoformat
# global_config.encoders[Optional[date]] = date.isoformat

@dataclass_json
@dataclass
class DataClassWithIsoDatetime:
    created_at: Optional[date] = None

print(DataClassWithIsoDatetime(date.today()).to_json())

Describe the results you expected

{"created_at": "2023-08-08"}

Python version you are using

3.9

Environment description

dataclasses-json==0.5.14

george-zubrienko commented 11 months ago

Should be solved in v1, but I suggest we still fix this in v0

PJCampi commented 2 months ago

This is becoming a bigger problem for me (global configs are also not applied from collections or mappings) so I will try to see if I can fix this tomorrow. It should be relatively simple.

PJCampi commented 2 months ago

I have a fix for the bug. I can create a PR if someone can grant me write access to the repo.

george-zubrienko commented 2 months ago

@PJCampi tagged you in another issue - please fork the repo and create a PR, you do not need contributor access to the repo itself

PJCampi commented 2 months ago

here you go: https://github.com/lidatong/dataclasses-json/pull/524