Thoughts on object representation in a dictionary

Steven D'Aprano steve at REMOVETHIScyber.com.au
Sat Dec 10 00:37:32 EST 2005


On Fri, 09 Dec 2005 11:37:30 -0800, py wrote:

> Say I have classes which represent parts of a car such as Engine, Body,
> etc.  Now I want to represent a Car in a nested dictionary like...
> 
> {string_id:{engine_id:engine_object, body_id:body_object}}....ok?
> 
> Well the other thing is that I am allowed to store strings in this
> dictionary...so I can't just store the Engine and Body object and later
> use them.  ....this is just a requirement (which i dont understand
> either)...but its what I have to do.
> 
> So my question is there a good way of storing this information in a
> nested dictionary such that if I receive this dictionary I could easily
> pull it apart and create Engine and Body objects with the information?
> Any suggestions at all?  keep in mind I am limited to using a
> dictionary of strings...thats it.


Cry and beg and hold your breath until you turn blue unless your
boss/client allows you to store general objects in the dictionary?

Or at least find out *why* they will only let you store strings in the
dictionary. If they won't tell you, tell them that it makes the job
(random big number) harder, which corresponds to costing the client $$$.

Failing that, perhaps you can pickle the objects before you store them in
the dictionary, although I daresay that will hit performance *hard*.
Perhaps use cPickle for speed?

Another possibility would be to build a light-weight serializer into the
engine class itself:

class Engine:
    def __init__(self, data):
        self.initialisation_data = data
        process(data)

    def __repr__(self):
        return "Engine(%s)" % self.initialisation_data
        # can't get more lightweight than that

engine_object = Engine(data)
s = repr(engine_object)

so that eval(s) recreates the engine_object. Do the same for all the other
classes, and then you don't even need to know what each string means, you
just eval() it and turns into the right sort of object.


(If you use eval, make sure you are aware of the security implications.)



-- 
Steven.




More information about the Python-list mailing list