Accessing dict keys like an attribute?

前端 未结 27 2154
南笙
南笙 2020-11-22 04:22

I find it more convenient to access dict keys as obj.foo instead of obj[\'foo\'], so I wrote this snippet:

class AttributeDict(dict         


        
27条回答
  •  后悔当初
    2020-11-22 05:07

    Solution is:

    DICT_RESERVED_KEYS = vars(dict).keys()
    
    
    class SmartDict(dict):
        """
        A Dict which is accessible via attribute dot notation
        """
        def __init__(self, *args, **kwargs):
            """
            :param args: multiple dicts ({}, {}, ..)
            :param kwargs: arbitrary keys='value'
    
            If ``keyerror=False`` is passed then not found attributes will
            always return None.
            """
            super(SmartDict, self).__init__()
            self['__keyerror'] = kwargs.pop('keyerror', True)
            [self.update(arg) for arg in args if isinstance(arg, dict)]
            self.update(kwargs)
    
        def __getattr__(self, attr):
            if attr not in DICT_RESERVED_KEYS:
                if self['__keyerror']:
                    return self[attr]
                else:
                    return self.get(attr)
            return getattr(self, attr)
    
        def __setattr__(self, key, value):
            if key in DICT_RESERVED_KEYS:
                raise AttributeError("You cannot set a reserved name as attribute")
            self.__setitem__(key, value)
    
        def __copy__(self):
            return self.__class__(self)
    
        def copy(self):
            return self.__copy__()
    

提交回复
热议问题