generic object implementation

Steven Bethard steven.bethard at gmail.com
Sun Nov 21 18:55:48 EST 2004


So I'm trying to get a prototype implementation of the 'generic object' 
type.  (I'm currently calling it 'bunch', but only because I can't 
really think of anything better.)  I'd like some feedback on what 
methods it needs to support.  Ideally I'd keep this as minimal as 
possible...

Remember that the goal of the 'generic object' type is to allow the 
programmer to make the design decision that attribute-style access is 
more appropriate than []-style access.  Given that, my feeling is that 
the 'generic object' type should *not* support __(get|set|del)item__ , 
though I'm still undecided on __len__, __iter__, __contains__, items, 
keys, values, etc.

Here's what I have currently:

import operator as _operator

class bunch(object):
     def __init__(self, **kwds):
         self.__dict__.update(kwds)

     def __eq__(self, other):
         if not isinstance(other, bunch):
             return False
         attrs = set(self.__dict__)
         if attrs != set(other.__dict__):
             return False
         for attr in attrs:
             if not getattr(self, attr) == getattr(other, attr):
                 return False
         return True

     def __repr__(self):
         return '%s(%s)' % (self.__class__.__name__,
                            ', '.join('%s=%r' % (k, v)
                                      for k, v in self.__dict__.items()))

     def update(self, other):
         self.__dict__.update(other.__dict__)

     @classmethod
     def frommapping(cls, mapping,
                     getkeys=iter, getitem=_operator.getitem):
         result = bunch()
         for key in getkeys(mapping):
             value = getitem(mapping, key)
             try:
                 value = bunch.frommapping(value)
             except TypeError:
                 pass
             setattr(result, key, value)
         return result



More information about the Python-list mailing list