简体   繁体   中英

Python analog for Groovy's it?

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]

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

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]

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])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM