Created
May 1, 2016 06:58
-
-
Save arbinish/1edd5e1546553f387aeff3b6a1d65884 to your computer and use it in GitHub Desktop.
subclassing dict in python.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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