genomoncology / related

Nested Object Models in Python with dictionary, YAML, and JSON transformation support
MIT License
200 stars 15 forks source link

'from_yaml' raises 'TypeError: __init__() got an unexpected keyword argument' when using a custom key for a field #40

Closed mmmeri closed 2 years ago

mmmeri commented 5 years ago

This is a rather obscure bug I've stumbled upon. Deserializing a yaml stream into a model fails, if you use a custom key (see example below). However the json equivalent works properly.

When tracing this issue I've noticed, that in functions.from_yaml this

return cls(**yaml_dict) if cls else yaml_dict

is being returned, whereas in functions.from_json this:

return to_model(cls, json_dict) if cls else json_dict

is being returned.

Is there any reason for this distinction in the deserialization? When I adapt the yaml-deserialization to the same style as the json one, it works.

Example to reproduce the issue

import related

@related.immutable
class Model:
    TEST = related.StringField(key="test")

yaml_stream = """
test: foo
"""

try:
    model = related.from_yaml(yaml_stream, Model)
except TypeError as e:
    print('This raises :-(\n', str(e))

json_stream = """
{"test": "foo"}
"""
model = related.from_json(json_stream, Model)
M0r13n commented 2 years ago

This is fixed in my private fork: https://github.com/M0r13n/related