Printing a dictionary of class instances

Sean Ross sross at connectmail.carleton.ca
Mon Mar 24 18:14:03 EST 2003


"Grant Ito" <Grant_Ito at shaw.ca> wrote in message
news:QjIfa.540154$Yo4.33526050 at news1.calgary.shaw.ca...
[snip]
> >>> print "%(a.var1)s" % (testdict)
> Traceback (most recent call last):
>   File "<interactive input>", line 1, in ?
> KeyError: a.var1
>

The problem with the above code is that it uses 'a.var1' as a key to index
testdict, but testdict has no such key. You can do:

>>> print "%(a)s" % testdict
<__main__.testclass object at 0x00E26490>

but not %(a.var1)s


> Is there any way to write that last "print" line to make this work?
>

I don't think so. However, you could make your own dict:

class mydict(dict):
    def __getitem__(self, key):
        try:
            inst, attr = key.split('.')
        except ValueError:
            return dict.__getitem__(self, key)
        return getattr(dict.__getitem__(self, inst), attr)

then

>>> testdict = mydict()
>>> testdict['a'] = testclass()
>>> print "%(a.var1)s" % testdict
1

will give you the value of 'var1' for instance 'a', while

>>> testdict['a']
<__main__.testclass object at 0x00E26490>

will still behave normally.

Be forewarned that there may be other issues/errors in this code, but it
appears to be doing what you need.

Good luck,
Sean






More information about the Python-list mailing list