Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[BUG] encoders / decoders don't apply to list / dict of the class #512

Open
noamgat opened this issue Jan 31, 2024 · 1 comment
Open

[BUG] encoders / decoders don't apply to list / dict of the class #512

noamgat opened this issue Jan 31, 2024 · 1 comment
Labels
bug Something isn't working

Comments

@noamgat
Copy link

noamgat commented Jan 31, 2024

Description

Lets say I implemented a custom encoder/decoder for a class, and registered them via cfg.global_config.
It works, but it doesn't work if that class is contained in a container (List / Dict).

I think the problem and potential solution (at least for the encoder's site) is in core.py's _asdict().
Shouldn't we check if type(obj) has a custom encoder, and use it if it exists?

Code snippet that reproduces the issue

def test_list_dataclasses_json():
    call_count = 0
    @dataclass_json
    @dataclass
    class Inner:
        inner_val: int

    def encode_inner(inner: Inner):
        nonlocal call_count
        call_count += 1
        return inner.inner_val
    
    from dataclasses_json import cfg
    cfg.global_config.encoders[Inner] = encode_inner

    @dataclass_json
    @dataclass
    class Outer:
        inner_list: list[Inner]
        inner_instance: Inner

    outer = Outer(inner_list=[Inner(inner_val=1), Inner(inner_val=2)], inner_instance=Inner(inner_val=3))
    outer.to_json()
    assert call_count == 3

Describe the results you expected

I expect the function to be called three times, but it is only called once.

Python version you are using

3.11.6

Environment description

dataclasses_json

@noamgat noamgat added the bug Something isn't working label Jan 31, 2024
@bergmansj
Copy link

Exactly this I also encountered, this remark is to hopefully bring some attention to the issue. 👍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working
Projects
None yet
Development

No branches or pull requests

2 participants