wonderbeyond
8/25/2015 - 8:28 AM

Simple way to convert dict to object with predefined schema

Simple way to convert dict to object with predefined schema

class BalanceItem(object):
    _fields_map = {'id': {'raw_field': '_id'},
                   'tradecco': {'raw_field': 'tradeacco'},
                   'code': {'raw_field': 'fundid'},
                   # holding share
                   'balance': {'raw_field': 'balance'},
                   # disposable share
                   'avaliable': {'raw_field': 'avaliable'},
                   'market_value': {'raw_field': 'mktvalue'},
                   'dayprofit': {'raw_field': 'dayprofit'},
                   # with unprofit included
                   'profit': {'raw_field': 'profit'},
                   'unprofit': {'raw_field': 'unprofit'},
                   # only for ZYB products currently
                   'expprofit': {'raw_field': 'expprofit'},
                   # total yield rate
                   'yield_rate': {'raw_field': 'profitprop'},
                   'melonmd': {'raw_field': 'melonmd', 'choices': melonmd_map},
                   }

    def __init__(self, raw_data):
        self._raw_data = raw_data
        for attr, opts in self._fields_map.items():
            raw_field = opts['raw_field']
            value = raw_data.get(raw_field, None)
            choices = opts.get('choices')
            if choices:
                value = {'id': value, 'display': choices.get(value)}

            setattr(self, attr, value)

    def __nonzero__(self):
        return True if self._raw_data and self.code else False