pms
pms

Reputation: 4626

Python: can function be defined inside of another function's argument list?

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

another_function( function(x) {return 2*x} )

Upvotes: 0

Views: 157

Answers (2)

hamstergene
hamstergene

Reputation: 24439

Yes:

another_function( lambda x: 2*x )

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

Upvotes: 9

Ethan Furman
Ethan Furman

Reputation: 69041

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`.

Upvotes: 0

Related Questions