Javascript style dot notation for dictionary keys unpythonic?

前端 未结 12 1035
刺人心
刺人心 2020-12-23 10:44

I\'ve started to use constructs like these:

class DictObj(object):
    def __init__(self):
        self.d = {}
    def __getattr__(self, m):
        return s         


        
12条回答
  •  轮回少年
    2020-12-23 11:04

    If you're looking for an alternative that handles nested dicts:

    Recursively transform a dict to instances of the desired class

    import json
    from collections import namedtuple
    
    
    class DictTransformer():
        @classmethod
        def constantize(self, d):
            return self.transform(d, klass=namedtuple, klassname='namedtuple')
    
        @classmethod
        def transform(self, d, klass, klassname):
            return self._from_json(self._to_json(d), klass=klass, klassname=klassname)
    
        @classmethod
        def _to_json(self, d, access_method='__dict__'):
            return json.dumps(d, default=lambda o: getattr(o, access_method, str(o)))
    
        @classmethod
        def _from_json(self, jsonstr, klass, klassname):
            return json.loads(jsonstr, object_hook=lambda d: klass(klassname, d.keys())(*d.values()))
    

    Ex:

    constants = {
      'A': {
        'B': {
          'C': 'D'
        }
      }
    }
    CONSTANTS = DictTransformer.transform(d, klass=namedtuple, klassname='namedtuple')
    CONSTANTS.A.B.C == 'D'
    

    Pros:

    • handles nested dicts
    • can potentially generate other classes
    • namedtuples provide immutability for constants

    Cons:

    • may not respond to .keys and .values if those are not provided on your klass (though you can sometimes mimic with ._fields and list(A.B.C))

    Thoughts?

    h/t to @hlzr for the original class idea

提交回复
热议问题