Dictionary with additional attributes

goodman goodman.m.w at gmail.com
Tue Feb 22 14:49:18 EST 2011


Hi, my question is this: Is it a bad idea to create a wrapper class
for a dictionary so I can add attributes? E.g.:

class DictWithAttrs(dict):
    pass

More information:
I'm using a nested defaultdict to store a machine-learning model,
where the first key is a class, the second key is a feature, and the
value is a probability for the pair. For example:

model = defaultdict(lambda: defaultdict(float))

This works quite well, but now I would like to keep track of the set
of all features within the model. While I can get the set of classes
by model.keys(), for the features I would have to do something like
set(feat for cls in model for feat in model[cls]). Rather than do
something like:

model['__features__'] = set(feat for cls in model for feat in
model[cls])

It seems less hackish to put it in an attribute, since that wouldn't
potentially collide with an actual key in the model:

model.features = set(feat for cls in model for feat in model[cls])

Note that I'm not asking to access dictionary key/values by means of
attributes, but have additional attributes. I'm looking for best, or
common, practice for this sort of thing.

Thanks!



More information about the Python-list mailing list