X - Replacing Python's Lambda

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.

(source code available in attached files)

Examples

>>> import snippets
>>> X = snippets.get('x').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:

$$latest_version=0.1$$

Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License