X
X - Replacing Python's Lambda.
Table of Contents
|
Summary
X offers anonymous functions for python which have a short and simple syntax, and can be pickled.
X works by "absorbing" operations, and later applying them when called as a function.
Code Samples
>>> from x import X >>> map( X+2, [1, 2, 3] ) [3, 4, 5] >>> filter( X>0, [5, -3, 2, -1, 0, 13] ) [5, 2, 13] >>> l = ["oh", "brave", "new", "world"] >>> sorted(l,key=X[-1]) ['world', 'brave', 'oh', 'new']
These operations can be chained:
>>> map(2**(X+1), range(10)) [2, 4, 8, 16, 32, 64, 128, 256, 512, 1024] >>> map( "P" + X[3:]*2 + “!”, ["Hello", "Suzzy"] ) ['Plolo!', 'Pzyzy!']
And pickled:
>>> expr = 1 + (X + 3) * 4 >>> s = pickle.dumps(expr) #(destory objects, change objects, switch an interpreter, whatever you wish) >>> expr2 = pickle.loads(s) >>> expr2(5) 33
Caveats
- Using X twice in the same expression probably won’t work (this can be solved)
- Since calling X evaluates it, it can’t emulate method calls. For that you have to do use call, like: X.upper.call() (’hello’) –> ‘HELLO’.
- Not all operations can be “captured”. For example, the “in” operator. For that you have to use X.in_( … ), like: X.in_(range(10)) (5) –> True
- Not all attributes will be accessible
- More problems? Likely.
More reading
Originally described in these posts:
- http://erezsh.wordpress.com/2008/11/01/fun-while-avoiding-lambda/
- http://erezsh.wordpress.com/2008/11/12/pickling-python-expressions/
Get Code! ("Download")
Latest version is 0.1, and can be found at page X-0.1-code
page revision: 1, last edited: 10 Jan 2009 19:57