[Python-Dev] Shortcut Notation for Chaining Method Calls

dustin at v.igoro.us dustin at v.igoro.us
Sat Feb 3 20:39:52 CET 2007


On Sat, Feb 03, 2007 at 07:01:47PM +0000, Michael O\'Keefe wrote:
> Anyhow, just curious for ideas and sparking discussion.
...

I haven't been on the list long enough to know, but I would expect that this
idea and its relatives have been batted around at least once before.  I think a
lot of people have been frustrated at the repetitive nature of operations on
lists, for example, as you indicated in your first post.  I think there's room
for debate on whether specific list methods that currently return None should
instead return the list, although I would definitely consult the archives
before entering that fray. 

I expect that the idea of adding a new operator or any other syntactic change
is, like the count of 5, "right out".

For what it's worth, you can wrap an object so it behaves the way you like as
follows, although of course this will discard the return value of any functions
which produce one:

class wrapcall(object):
    def __init__(self, inner): 
        self.inner = inner 

    def __getattr__(self, attr):
        rv = getattr(self.inner, attr)
        if callable(rv):
            def wrap(*args, **kwargs):
                rv(*args, **kwargs)
                return self
            return wrap
        else:   
            return rv

mylist = [1, 2, 3]
wrapcall(mylist).reverse().append(2).reverse()
assert mylist == [2, 1, 2, 3]

Dustin


More information about the Python-Dev mailing list