Getting a dictionary from an object

Bruno Desthuilliers bdesth.quelquechose at free.quelquepart.fr
Sun Jul 24 08:01:30 EDT 2005


Thanos Tsouanas a écrit :
> On Sun, Jul 24, 2005 at 01:43:43PM +1000, Steven D'Aprano wrote:

(snip)
> 
>>Why jump through all those hoops to get attributes when Python already
>>provides indexing and attribute grabbing machinery that work well? Why do
>>you bother to subclass dict, only to mangle the dict __getitem__ method so
>>that you can no longer retrieve items from the dict?

> 
> Because *obviously* I don't know of these indexing and attribute
> grabbing machineries you are talking about in my case.  If you cared to
> read my first post, all I asked was for the "normal", "built-in" way to
> do it.  Now, is there one, or not?

If you re-read your first post, you'll notice that you didn't say 
anything about the intention, only about implementation !-)

Now if your *only* need is to access object as a dict for formated 
output, you don't need to subclass dict. This is (well, should be) enough:

class Wrapper(object):
     def __init__(self, obj):
         self._obj = obj
     def __getitem__(self, name):
         return getattr(self._obj, name)

This works with 'normal' attributes as well as with properties. Notice 
that this wrapper is read-only, and don't pretend to be a real 
dictionnary - but still it implements the minimum required interface for 
"%(attname)s" like formatting.

HTH
Bruno



More information about the Python-list mailing list