Skip to content

Instantly share code, notes, and snippets.

@skatesham
Created March 24, 2020 22:32
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save skatesham/ec9913a983154e308beb0479efbadcc1 to your computer and use it in GitHub Desktop.
Save skatesham/ec9913a983154e308beb0479efbadcc1 to your computer and use it in GitHub Desktop.
class Mapper:
def convertValue(self, data, obj):
"""
Mapper from dict to class, covering it's chieldrens but the key on dict must be mapping the chield with .
Exemple: data = {
"x": 0,
"y": 1,
"chield.a": "Sham Vinicius",
"chield.b": "Fiorin",
"chield.layer.c": "xxx",
"chield.layer.d": "yyy",
}
:param data: dict mapped as above
:param obj: obj with all the fields mapped
:return: the input obj with all data inserted injected in it
"""
for key, value in data.items():
keys = key.split(".")
self.__convertValue(obj, keys, value)
return obj
def __convertValue(self, obj, keys, value):
"""
Recursive function for set data in the right field
:param obj: object or chield
:param keys: the keys in the key splited by '.'
:param value: value
:return: void
"""
if len(keys) == 1:
if not value:
value = ""
elif isinstance(value, Decimal):
value = str(value)
setattr(obj, keys[0], value)
return
obj = getattr(obj, keys[0])
return self.__convertValue(obj, keys[1:], value)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment