How to pass functions as parameters of another function with pre-specified arguments in python? [duplicate]

Multi tool use
How to pass functions as parameters of another function with pre-specified arguments in python? [duplicate]
This question already has an answer here:
Is there a way to pass function with arguments that looks clean? For example, if I want pass function h
with particular parameter-values a
b
from ars so that ars1 runs with these particular a
b
, what should I do? I want to do
h
a
b
a
b
def h(x, a, b):
return x * a * b
def ars(fcn):
a = 1
b = 2
return ars1(fcn( . , a,b))
def ars1(fcn):
return fcn(1)*fcn(1)
ars(h)
I could do
def h(x, a, b):
return x * a * b
def ars(fcn):
a = 1
b = 2
return ars1(fcn, a, b)
def ars1(fcn, a, b):
return fcn(1, a, b)*fcn(1, a, b)
which achieves the purpose but since a
b
have nothing to do with ars1
, the code looks messy and lacks modularity.
a
b
ars1
This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.
I’d like to say that functools is quite common, with “partial” in particular being very heavily used. It is in the standard library for a reason. That said, lambda is the other way to go, or *args.
– soundstripe
Jul 1 at 22:43
Using standard library functions should be considered standard.
– juanpa.arrivillaga
Jul 1 at 23:29
1 Answer
1
You can use a lambda
function to achieve this:
lambda
def h(x, a, b):
return x * a * b
def ars(fcn):
a = 1
b = 2
return ars1(lambda x: fcn(x, a, b))
def ars1(fcn):
return fcn(1)*fcn(1)
ars(h)
"For example, Creating Python function with partial parameters uses functools which in my opinion not very standard" - you've got some weird opinions.
– user2357112
Jul 1 at 22:42