This is a slightly frivolous question:
I have a piece of python code with a lot of filter-map-reduce functions.
I'm finding it a bit painful retyping eg.
filter(lambda x: x['identity'] == 'creosote', skits)
each time. I'd like to be able to do something like
filter(f(x['identity']==creosote),skits)
instead. I've tried :
def f(y):
f = lambda(x: y)
but that doesn't seem to work. Thanks
I get a NameError: name 'x' is not defined
What I'm trying to accomplish is to "symlink" lambda x: to something so that I don't have to type it.
2 Answers 2
You can do this:
def f(x):
return x['identity'] == 'creosote'
Then you would just do filter(f, skits).
There is no way to have something like f(x['identity'] == 'creosote') without having the expression x['identity'] == 'creosote' evaluated before f is called (which means, among other things, that the variable x has to be defined in the enclosing scope). If you want to defer execution you must put the expression inside a function, which you can do with lambda or with a full def.
Python does not have macros that would allow you to do a "symlink" in the way you suggest. You can't alias some text to other text in Python; you can only evaluate well-formed expressions. lambda is not a function, it is part of the Python syntax, so you can't alias it to something else, just like you can't do plus = + and then do 4 plus 3.
2 Comments
lambda anything you put in the function call will be evaluated before the function is called. There are no macros to do "symlinks" like you seem to want. (You can try other ways of shortening things, though, a la user3's answer.)You could pass x and y to the function if x and y is different:
def f(x, y):
return (x==y)
and call the function as:
filter(f(x['identity'], 'creosote'),skits)
3 Comments
'creosote' (that is, as a string).f accept two arguments here.