Stephan said:
Terry said:
Stephan Diehl said:
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)