Is it possible to pass functions with arguments to another function in Python?
Say for something like:
def perform(function):
return function()
But the functions to be passed will have arguments like:
action1()
action2(p)
action3(p,r)
Is it possible to pass functions with arguments to another function in Python?
Say for something like:
def perform(function):
return function()
But the functions to be passed will have arguments like:
action1()
action2(p)
action3(p,r)
This is what lambda is for:
(months later) a tiny real example where lambda is useful, partial not:
say you want various 1-dimensional cross-sections through a 2-dimensional function, like slices through a row of hills.
quadf( x, f )
takes a 1-df
and calls it for variousx
.To call it for vertical cuts at y = -1 0 1 and horizontal cuts at x = -1 0 1,
As far as I know,
partial
can't do this --(How to add tags numpy, partial, lambda to this ?)
This is called partial functions and there are at least 3 ways to do this. My favorite way is using lambda because it avoids dependency on extra package and is the least verbose. Assume you have a function
add(x, y)
and you want to passadd(3, y)
to some other function as parameter such that the other function decides the value fory
.Use lambda
Create Your Own Wrapper
Here you need to create a function that returns the partial function. This is obviously lot more verbose.
Use partial from functools
This is almost identical to
lambda
shown above. Then why do we need this? There are few reasons. In short,partial
might be bit faster in some cases (see its implementation) and that you can use it for early binding vs lambda's late binding.Here is a way to do it with a closure:
Do you mean this?
Use functools.partial, not lambdas! And ofc Perform is a useless function, you can pass around functions directly.