s-knibbs / dataclasses-jsonschema

JSON schema generation from dataclasses
MIT License
166 stars 38 forks source link

`from_dict` should not modify dict argument #130

Closed claytonlemons closed 3 years ago

claytonlemons commented 4 years ago

When calling from_dict on a class derived from JsonSchemaMixin, the dict argument may be modified if it does not contain a value for a field in the class and that class field has a default value. For example:

>>> from dataclasses import dataclass
>>> from dataclasses_jsonschema import JsonSchemaMixin
>>> @dataclass
... class MyClass(JsonSchemaMixin):
...     field1: int = 5
...     field2: str = "foo"
>>> my_dict = {"field1": 10}
>>> my_dict
{'field1': 10}
>>> MyClass.from_dict(my_dict)
MyClass(field1=10, field2='foo')
>>> my_dict
{'field1': 10, 'field2': 'foo'}  # 'field2' should not be here

The name from_dict suggests that data is only read from the dict argument, so it seems reasonable that the from_dict implementation should make a copy of the dict first before updating missing fields with default values.

s-knibbs commented 3 years ago

It looks like this might be an issue with fastjsonschema. I can't reproduce this when using jsonschema instead. Maybe worth raising an issue there.

Otherwise, you can just copy my_dict to avoid this problem.