« Back to Index

Python EasyDict

View original Gist on GitHub

Python EasyDict.py

class EasyDict(dict):
    '''
    No need to specify brackets/quotes for accessing attributes
    A namedtuple is immutable and so you can't add new attributes
    This is a hack to work around that restriction by inheriting from `dict`
    '''
    __setattr__ = dict.__setitem__
    __getattr__ = dict.__getitem__
    __delattr__ = dict.__delitem__
    def __dir__(self):
        return list(self.keys())
        
d = EasyDict()
d  # {}
d.foo  # KeyError: 'foo'
d.foo = 123
d.foo  # 123
d  # {'foo':123}
del(d.foo)
d  # {}