Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function arguments fixer

Tags:

python

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.

like image 617
Pavel Ryvintsev Avatar asked Dec 26 '22 00:12

Pavel Ryvintsev


2 Answers

You can use functools.partial:

>>> import functools
>>>
>>> def a(x, y):
...     return x + y
...
>>> b = functools.partial(a, x=1, y=2)
>>> b()
3
like image 138
falsetru Avatar answered Jan 02 '23 19:01

falsetru


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
like image 41
Ffisegydd Avatar answered Jan 02 '23 20:01

Ffisegydd