khpeek khpeek - 9 months ago 27
Ruby Question

Chain together methods in Python as in Ruby

In Ruby, one can chain together methods like so:

a = [2,3,1]
b = a.sort.reverse

which sets the value of the variable
while leaving
the same.

I'd like to perform similar operations in Python. So far, the shortest way to do this I have found is:

import copy
a = [2,3,1]
b = copy.copy(a)

That is, with 5 lines of code instead of 2. Is there really no simpler way?


You can write this down pretty much directly.

a = [2,3,1]
b = sorted(a, reverse=True)

Even if you want to use only methods, you can do that rather straightforward as well:

a = [2,3,1]
b = a.copy()  # a[:] in python2

Python tends to be rather picky about implicit cloning. Copying references is cheap, copying objects is expensive. Since many python types are mutable, one can easily introduce subtle bugs when things are cloned (or not) by accident. Thus, most interfaces need you to explicitly clone things.