genomoncology / related

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

Key name overrides for Python keywords. #4

Closed imaurer closed 6 years ago

imaurer commented 6 years ago

Objects cannot have a keyword for a field name. For instance, this is invalid:

@related.immutable
class MyModel(object):
    for = related.StringField()   # invalid !
    not = related.BooleanField()  # invalid too !

But sometimes, you need to be able to convert to and from JSON formats that contain those keywords as keys:

{ "for": "Elise", "not": true }

To handle these situations, this fix will allow for overriding the name in the to/from dictionary methods.

@related.immutable
class MyModel(object):
    is_for = related.StringField(key="for")
    is_not = related.BooleanField(key="not")

obj = related.to_model(MyModel, { "for": "Elise", "not": True })
assert obj.is_for == "Elise"
assert obj.is_not is True
imaurer commented 6 years ago

Fixed here:

https://github.com/genomoncology/related/blob/master/tests/ex05_field_names/test_renamed.py