[Python-Dev] Shortcut Notation for Chaining Method Calls
Raymond Hettinger
python at rcn.com
Mon Feb 5 08:05:37 CET 2007
[Michael O'Keefe]
> def desired():
> pass
> # IF we had a --> operator which would execute the method at
> # left but return a ref to object
> #return [8,9,7,1].sort()-->reverse()-->pop(0)--> # returns [8,7,1]
> # return [8,9,7,1].sort()-->reverse()-->pop(0) # returns 9
> # return [8,9,7,1].sort()-->reverse()-->pop(0) # equivalent to above
I would write these as:
>>> sorted([8,9,7,1], reverse=True)[1:]
[8, 7, 1]
>>> sorted([8,9,7,1], reverse=True)[0]
9
FWIW, I think the proposed notation is somewhat weird in that
the first example's --> chain ends with a pop but returns a list.
For successive mutations, separate lines are much more clear:
s = [8,9,7,1]
s.sort()
s.reverse()
s.pop(0)
Also, I don't think your example generalizes well. How many classes
have multiple methods that can meaningfully be chained together
in an arbitrary order. It is telling that the example chooses to call
the reverse method when it could have simple chosen the reverse=True
argument to sort().
Raymond
More information about the Python-Dev
mailing list