Function argument latch

I need a function that can correct the arguments of other functions for constant values. for instance

def a(x, y):
    return x + y

b = fix(a, x=1, y=2)

Now b should be a function that does not receive any parameters when returning 3 with every call. I am sure python has something similar, but I could not find it.

Thank.

+4
source share
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
+6
source

You can use functools.partialto return a new object partial. In fact, it provides you with the same function, but one or more arguments are filled with the given values.

from functools import partial

def a(x, y):
    return x + y

b = partial(a, x=1, y=2)

print(b())
# 3
+4
source

Source: https://habr.com/ru/post/1568968/


All Articles