Underscore lambda in Python 14 Feb, 2009
After using Scala for a number of Project Euler problems, Python’s lambda syntax looks way too verbose. Trying to simplify it:
def call(func, *args): def wrap(item): return getattr(item, func)(*args) return wrap def call_argslater(func): def setargs(*args): def wrap(item): return getattr(item, func)(*args) return wrap return setargs inputs = [" abc ", "def "] print map(lambda x: x.strip(), inputs) print map(call("strip"), inputs) print map(call("split", "b"), inputs)
That’s just the first step, those functions (very similar to decorators) can then be wrapped in an object:
class Underscore(object): def __getattr__(self, attr): return call(attr) _ = Underscore() print map(_.strip, inputs)
The downside is that without examining the call stack, it can’t tell if the args are in the initial use or the subsequent calls from within map, so you’d need two different underscore objects (one with args, one without).
Have a way to improve this? Please email me (code@timhatch.com)