I need a function which can fix other functions arguments to constant values. For example
def a(x, y):
return x + y
b = fix(a, x=1, y=2)
Now b should be a function that receives no parameters an returns 3 each time it is being called. I'm pretty sure python has something like that build in, but I could not find it.
Thanks.
You can use functools.partial
:
>>> import functools
>>>
>>> def a(x, y):
... return x + y
...
>>> b = functools.partial(a, x=1, y=2)
>>> b()
3
You can use functools.partial
to return a new partial
object. Effectively it provides you with the same function but one or more of the arguments have been filled with set values.
from functools import partial
def a(x, y):
return x + y
b = partial(a, x=1, y=2)
print(b())
# 3
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With