Getting a dictionary from an object

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


Steven D'Aprano a écrit :
> On Sun, 24 Jul 2005 02:09:54 +0300, Thanos Tsouanas wrote:
> 
> 
(snip)
> 
> Are you telling me that the ONLY thing you use dictobj objects for is to
> print them?
> 
> I don't think so. I do know how to print an object, amazingly.
> 
> Perhaps you would like to explain how you use the rest of the
> functionality of the dictobj, instead of taking my words out of context
> and giving an inane answer.
> 
> 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?
> 

The idea of the OP is not to use the dictobj as a full fledged dict,
just to wrap the obj in something that is dict-like enough to be used
for "%(attname)s" formatting. I also assume that he doesn't want to 
manually alter the code of each and every class to achieve this !-)

So we can certainly agree that subclassing dict here is overkill and a 
bit misleading, but there are probably better ways to express this 
feeling. Of course, it would have been simpler if the OP had tell us 
from the start what was it's use case, but what...

One could of course use metaclass tricks and the like to customize the 
objects __str__ or __repr__ (as in David Mertz's gnosis.magic package), 
but that would be overkill too IMHO.

The plain old Decorator[1] pattern is probably enough in this case, 
since it's quite easy to implement a generic Decorator in Python. 
Another solution could be to dynamically modify the to-be-wrapped 
object's class to add a __getitem__ method.








More information about the Python-list mailing list