basic language question
jacek.generowicz at cern.ch
Fri Sep 5 14:31:27 CEST 2003
Stephan Diehl <stephan.diehl at gmx.net> writes:
> Stephan Diehl wrote:
> > Terry Reedy wrote:
> >> '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.
OK, here's a variaton on the theme, just wraps the object in-place in
a way which makes it return self. This way you can get the desired
effect on any object you get, without pre-meditation, so you can still
fit the call chain on one line (wasn't that the point?)
> The solution involves a metaclass
Mine avoids them altogether.
> and I wouldn't consider this code more as an example than an
> industrial strength solution
def __init__(self, object):
self.object = object
def __getattr__(self, name):
def proxy(*args, **kwds):
getattr(self.object, name)(*args, **kwds)
lst = [1,2,3]
print lst.append(4) # Here you get None
print returner(lst).append(5) # Here you get the modified list.
More information about the Python-list