通过部分应用运算符生成匿名函数的简单方法。
whatever的Python项目详细描述
一种通过部分应用python操作符制作lambdas的简单方法。
灵感来自Perl6 One,请参见http://perlcabal.org/syn/S02.html#The_Whatever_Object
用法
fromwhateverimport_,that# get a list of guys namesnames=map(_.name,guys)names=map(that.name,guys)odd=map(_*2+1,range(10))squares=map(_**2,range(100))small_squares=filter(_<100,squares)best=max(tries,key=_.score)sort(guys,key=-that.height)factorial=lambdan:reduce(_*_,range(2,n+1))
注意:不能实现链式比较,因为python中没有布尔重载。
注意事项
在某些特殊情况下,任何可能导致混淆的东西:
_.attr# this makes callableobj._# this fetches '_' attribute of obj_[key]# this works tood[_]# KeyError, most probably_._# short for attrgetter('_')_[_]# short for lambda d, k: d[k]if_=='Any value':# You will get here, definitely# `_ == something` produces callable, which is true[1,2,_*2,None].index('hi')# => 2, since bool(_ * 2 == 'hi') is True
此外,无论有时在后期绑定时失败:
(_*2)('2')# -> NotImplemented