0

Is there a way to achieve something like this in python?

another_function( function(x) {return 2*x} )
1
  • What does this code do? If called as another_function(9) is 18 what is actually passed into another_function? Commented Oct 10, 2011 at 16:59

2 Answers 2

9

Yes:

another_function( lambda x: 2*x )

To be clear: this is taking place when another_function is called, not when it is defined.

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

4 Comments

This gives SyntaxError: invalid syntax
No typo -- thought question was about function definition time, whereas your answer is at function call time.
@EthanFurman the question was exactly about call time (doesn't the fact that the answer is accepted ring a bell?). The author has used anonymous function syntax from Javascript and other ecmascript-based languages.
Amazingly enough, not everybody speaks Javascript or other ecmascript-based languages (and unfortunately I've seen bad answers accepted); I've changed my vote, though.
0
def another_function( function=lambda x: 2*x ):
    print(function(10))  #an example

I'm not sure what happens with the example code you posted, but with the solution shown if you call another_function it will call function(10) and print 20.

More to the point, you cannot call another_function(7) and get 14 because 7 will get assigned to function and 7(10)' will get youTypeError: 'int' object is not callable`.

Comments

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.