basic language question

Stephan Diehl stephan.diehl at gmx.net
Fri Sep 5 04:40:48 EDT 2003


Stephan Diehl wrote:

> Terry Reedy wrote:
> 
>> 
>> "Stephan Diehl" <stephan.diehl at gmx.net> wrote in message
>> news:bj7ots$48j$06$1 at news.t-online.com...
>>> Once in a while, I get bitten by the fact, that mutating list
>> methods such
>>> as 'append' or 'extend' return None instead of the (mutated) list
>> itself.
> 
> [...]
> 
>> 
>> 'Returners' could wrap no-return mutators with functions or
>> derived-class methods that do return the object, but I have never seen
>> anyone post a complete module that does so for, say, all list
>> mutators.
> 
> That's actually a nice idea. I might just do that.

o.k., the following short code would give you a list class, that returns
'self' when invoking any of the mutating methods.
The solution involves a metaclass and I wouldn't consider this code more as
an example than an industrial strength solution (for example, at the
moment, you couldn't overload any of these methods)
------------------------------------------------------------------
def wrapedmeth(classname,meth):
    def _meth(self,*argl,**argd):
        getattr(super(globals()[classname],self),meth)(*argl,**argd)
        return self

    return _meth

class ReturnMeta(type):
    def __new__(cls,classname,bases,classdict):
        wrap = classdict.get('return_self_super_methods')
        if wrap is not None:
            for method in wrap:
                classdict[method] = wrapedmeth(classname,meth)
        return super(ReturnMeta,cls).__new__(cls,classname,bases,classdict)

class mylist(list):
    __metaclass__ = ReturnMeta
    return_self_super_methods = ['append',
                           'extend',
                           'insert',
                           'remove',
                           'reverse',
                           'sort']


if __name__ == '__main__':
    print 'l = [1,2]'
    print 'mylist: print l.append(3)'
    l = mylist([1,2])
    print l.append(3)
    print 'list: print l.append(3)'
    l = [1,2]
    print l.append(3)
------------------------------------------------------------------------------

have fun

Stephan




More information about the Python-list mailing list