Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save arbinish/1edd5e1546553f387aeff3b6a1d65884 to your computer and use it in GitHub Desktop.
Save arbinish/1edd5e1546553f387aeff3b6a1d65884 to your computer and use it in GitHub Desktop.
subclassing dict in python.
class AttrStorage(dict):
def __init__(self, fields=None, **kwargs):
""" only keys defined in fields are allowed """
self.fields = ()
if fields:
self.fields = fields
super(AttrStorage, self).__init__(kwargs)
def __getitem__(self, name):
val = super(AttrStorage, self).get(name)
if val:
return val
raise KeyError(name)
def __setitem__(self, k, v):
""" Additionaly restrict changing the value once set """
if len(self.fields) and k not in self.fields:
raise AttributeError("{0}: not allowed".format(k))
try:
self.__getitem__(k)
except KeyError:
pass
else:
raise RuntimeError('Read-only attribute: {0}'.format(k))
return super(AttrStorage, self).__setitem__(k, v)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment