lidatong / dataclasses-json

Easily serialize Data Classes to and from JSON
MIT License
1.36k stars 153 forks source link

InitVar does not work with dataclasses-json #281

Open AbdulRahmanAlHamali opened 3 years ago

AbdulRahmanAlHamali commented 3 years ago

For example, the following code fails:

@dataclass
class Hello(DataClassJsonMixin):
    a: int
    b: InitVar[int]

Hello.from_dict({"a": 3, "b": 4})

With the exception:

Traceback (most recent call last):
  File "/home/aalhamali/pycharm-2020.1.3/plugins/python/helpers/pydev/pydevd.py", line 1438, in _exec
    pydev_imports.execfile(file, globals, locals)  # execute the script
  File "/home/aalhamali/pycharm-2020.1.3/plugins/python/helpers/pydev/_pydev_imps/_pydev_execfile.py", line 18, in execfile
    exec(compile(contents+"\n", file, 'exec'), glob, loc)
  File "/home/aalhamali/support_channel_scraper/main.py", line 110, in <module>
    Hello.from_dict({"a": 3, "b": 4})
  File "/home/aalhamali/support_channel_scraper/venv/lib/python3.8/site-packages/dataclasses_json/api.py", line 83, in from_dict
    return _decode_dataclass(cls, kvs, infer_missing)
  File "/home/aalhamali/support_channel_scraper/venv/lib/python3.8/site-packages/dataclasses_json/core.py", line 208, in _decode_dataclass
    return cls(**init_kwargs)
TypeError: __init__() missing 1 required positional argument: 'b'

After doing some debugging, I see that the library only rotates on the fields when it calls the constructor, and InitVars are not included in fields.

ALiangLiang commented 2 years ago

same here