Method chaining

Chris Angelico rosuav at gmail.com
Fri Nov 22 06:44:08 EST 2013


On Fri, Nov 22, 2013 at 10:26 PM, Steven D'Aprano
<steve+comp.lang.python at pearwood.info> wrote:
>         if callable(obj):
>             def selfie(*args, **kw):
>                 # Call the method just for side-effects, return self.
>                 _ = obj(*args, **kw)
>                 return self
>             return selfie
>         else:
>             return obj

Nice piece of magic. One limitation not mentioned is that this
completely destroys the chance to have a method return anything _other
than_ self. Since this is intended for Python's convention of
"mutators return None", I'd be inclined to check for a None return,
though that might still have some false positives.

            def selfie(*args, **kw):
                # Call the method for side-effects, return self if it
returns None.
                _ = obj(*args, **kw)
                if _ is None: return self
                return _
            return selfie

Either that, or manually identify a set of methods to wrap, which
could possibly be done fairly cleanly with a list of names passed to
__init__. That'd be more work, though.

ChrisA



More information about the Python-list mailing list