Python analog for Groovy's it?

231 views Asked by At

Groovy has nice syntax for simple clojures, which eliminates the need to explitly name the single parameter. It will be named it by default.

def closure = { print it }
closure( "hi there" ) //prints "hi there"

What is the best way to emulate it magikal parameter in Python?

Example of what I want:

>>> it = It()
>>> print map(it + 5, [1, 2, 3])
[6, 7, 8]
3

There are 3 answers

0
uhbif19 On BEST ANSWER

So far I have found the exact anwser on my question. This is the library fn.py which implements _ magikal variable and some usable functional programming conceptions.

Example of use:

>>> from fn import _
>>> list(map(_ * 2, range(5)))
[0,2,4,6,8]
0
uhbif19 On

My first thougt is to do some magikal it object with magik methods producing curryied function.

class It :
    def __add__(self, another_one) :
         return lambda x: x + another_one



it = It()
print map(it + 5, [1, 2, 3])
0
Martijn Pieters On

You just give your lambda or function an explicit first argument:

lambda it: ' {}'.format(it)

This fits with the Zen of Python:

Explicit is better than implicit