Dictionary with additional attributes

G

goodman

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!
 
R

Robert Kern

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

Nope. I do recommend adding a custom __repr__(), though.

--
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma
that is made terrible by our own mad attempt to interpret it as though it had
an underlying truth."
-- Umberto Eco
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,483
Members
44,901
Latest member
Noble71S45

Latest Threads

Top