1

I want to do is something like this

def mult(x, y):
     return x * y

def add(x, y):
     return x + y

treeFunction = mult(2, add(x, y))

#outputs 10 (2 * ( 2 + 3 ))
print treeFunction(2, 3)

basically, is there a way during run-time to change add()'s return value by multiplying it by some value.

0

1 Answer 1

7

I think what you're asking for is a lambda function:

treeFunction = lambda x,y: mult(2, add(x, y))

Then just use it as:

treeFunction(2, 3)

EDIT

Have a read about closures in python. Definitely worth your time to learn.

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

5 Comments

There are a number of complex and general ways to do this, but I agree that for this particular example, the easiest solution is a lambda function.
The other way I interpreted this question was as asking for an interpreter for some domain-specific language. This code was easier to write.
is it hard to write def treeFunction(x,y): return mult(2, add(x,y)) ? giving a name to a lambda is plain wrong
No, it isn't. In this case, yes, there is no difference, but what if it is in a function, and you want to assign the variable differing calls depending on a condition? Using anonymous functions isn't new. I doesn't clutter the namespace and allows you to generate function calls on the fly.
After sleeping on this and re-reading it all you have answered my question, but it didn't really help with my problem =P. My mistake. Thanks for the link to the closure stuff, very interesting.

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.