I Want To Subclass Dict And Set Default Values
I have a need to create a special subclass of dict.  In it I want to set default values for a set of keys.   I seem to be failing in finding the correct syntax to do this. Here is
Solution 1:
You can achieve what you want as such:
classNewDict(dict):
    def__init__(self):
        self['Key1'] = 'stuff'
        ...
PrefilledDict = NewDict()
print PrefilledDict['Key1']
With your code, you are creating attributes of the NewDict class, not keys in the dictionary, meaning that you would access the attributes as such:
PrefilledDict = NewDict()
print PrefilledDict.Key1
Solution 2:
No subclassing needed:
defpredefined_dict(**kwargs):
    d = {
        'key1': 'stuff',
        ...
    }
    d.update(kwargs)
    return d
new_dict = predefined_dict()
print new_dict['key1']
or just:
defaults = {'a':1, 'b':2}
new_dict = defaults.copy()
print new_dict['a']
Solution 3:
@astynax provided a good answer but if you must use a subclass you could:
classdefaultattrdict(dict):
    def__missing__(self, key):
        try: returngetattr(self, key)
        except AttributeError:
            raise KeyError(key) #PEP409 from NoneThen:
classNewDict(defaultattrdict):
    Key1 = "stuff"
    Key2 = "Other stuff"
    NoList = []
    Nada = None
PrefilledDict = NewDict()
print(PrefilledDict['Key1']) # -> "stuff"print(PrefilledDict.get('Key1')) #NOTE: None as defaultdictNote: your code doesn't follow pep8 naming convention.
Post a Comment for "I Want To Subclass Dict And Set Default Values"