spell method chaining?

Just van Rossum just at letterror.com
Sat Jun 9 12:52:03 EDT 2001


Robin Becker wrote:
> 
> In article <3B21D830.E823D70F at letterror.com>, Just van Rossum <just at letterror.com> writes
> Well what I'm really interested in is dynamically wrapping classes for a property collection.

(erm, I didn't write that, you did ;-)

> With a simple ion that's fairly easy, but when the collection is over a class then the wrapper
> __getitem__ has to try and chain getattr to either go through the wrapped class or if that fails
> to try the collection.
> 
> the main code looks like
> 
> _ItemWrapper={}
> 
> class TypedPropertyCollection(PropHolder):
>     def __init__(self, exampleClass):
>         #give it same validation rules as what it holds
>         self.__dict__['_value'] = exampleClass()
>         self.__dict__['_children'] = {}
> 
>     def __getitem__(self, index):
>         try:
>             return self._children[index]
>         except KeyError:
>             Klass = self._value.__class__
>             if _ItemWrapper.has_key(Klass):
>                 WKlass = _ItemWrapper[Klass]
>             else:
>                 class WKlass(Klass):
>                     def __getattr__(self,name):
>                         try:
>                             return self.__class__.__bases__[0].__getattr__(self,name)
>                         except:
>                             return getattr(self._parent,name)
>                 _ItemWrapper[Klass] = WKlass
> 
>             child = WKlass()
>             child._parent = self
>             for i in filter(lambda x,K=child.__dict__.keys(): x in K,child._attrMap.keys()):
>                 del child.__dict__[i]
> 
>             self._children[index] = child
>             return child
> 
> it currently uses the __bases__ trick for compatibility with earlier python, but that goes wrong
> under certain conditions the gen(gen(C)) recursion etc. The nested scopes version would work OK.

I can't deduct from this code what on earth it's supposed to be _doing_: it's way too
convoluted for me to parse. But I'm wondering: is subclassing really the best solution
for the problem? Instead of painfully trying to dynamically create classes, why don't
you use containment and delegation? As in:

class Wrapper:

    def __init__(self, object):
        self.__object = object
    def __getattr__(self, name):
        # this is enough for retrieving attrs, if attrs are set-able, you
        # also need to need a corresponding __setattr__ and __delattr__
        return getattr(self.__object, name)
    def __getitem__(self, index):
        return Wrapper(self.__object[index])  # whatever

Just



More information about the Python-list mailing list