0

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

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks @BrenBarn, looking for something more general though. Lambda is just a mouthful to type each time..
@TahnoonPasha: Like I said, there is no way around it. If you don't use 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.)
1

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

You would have to pass 'creosote' (that is, as a string).
Thanks i have edited..previously i had assumed that he had the variable in his code which he did not post in the question...Thanks again.
Also you need to make f accept two arguments here.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.