Getting a dictionary from an object

Thanos Tsouanas thanos at sians.org
Sun Jul 24 07:47:03 EDT 2005


On Sun, Jul 24, 2005 at 02:01:30PM +0200, Bruno Desthuilliers wrote:
> Thanos Tsouanas a écrit :
> > On Sun, Jul 24, 2005 at 01:43:43PM +1000, Steven D'Aprano wrote:
> > 
> > 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 !-)

"""The following works, but I would prefer to use a built-in way if one
exists.  Is there one?"""
 
> 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.

Thanks!!  You made clear what 'the extra functionality' was.  Indeed
there is no need to subclass dict...

> HTH

it does!

> Bruno
> -- 
> http://mail.python.org/mailman/listinfo/python-list

-- 
Thanos Tsouanas          .: My Music: http://www.thanostsouanas.com/
http://thanos.sians.org/ .: Sians Music: http://www.sians.org/



More information about the Python-list mailing list