Skip to content

[BUG] Field decoders are not called for None values #563

@yossibiton

Description

@yossibiton

Description

When a field's value is None in the input JSON, dataclasses-json raises a warning about non-optional types but doesn't call the field's decoder. This prevents proper handling of None values through decoders.

Current Workaround

Currently, we have to handle None values in post_init, which is not ideal as it:

  1. Splits the field's value handling logic
  2. Requires additional boilerplate code
  3. Makes the decoder configuration ineffective for None values

Suggested Solution

The library should call field decoders before handling None values, allowing the decoders to handle the None case appropriately.

Code snippet that reproduces the issue

@dataclass_json
@dataclass
class SimpleTest:
    test_list: List[str] = field(
        default_factory=list,
        metadata=config(
            decoder=lambda x: print(f"decoder called with {x}") or ([] if x is None else x)
        )
    )

test_data = {"test_list": None}
result = SimpleTest.from_dict(test_data)

Describe the results you expected

The library:

  1. Detects the None value
  2. Raises a warning: "'NoneType' object value of non-optional type test_list detected when decoding SimpleTest"
  3. Sets the field to None
  4. Never calls the decoder

Expected Behavior

The decoder should be called even for None values, allowing proper handling of such cases. This would allow users to define how None values should be handled at the field level through decoders.

Python version you are using

3.9.12

Environment description

dataclasses-json version: 0.6.7

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions