chrise chrise - 4 months ago 10
Python Question

Creating a copy of a function with some vars fixed

Assume I have a function

def multiply_by(x, multiplier):
return x * multiplier


How can I create a copy of that function and fix the multiplier in that function?

multiply_by_5 = multiply_by? <-- here I need python magic


such that multiply_by_5 would have only one argument x and the multiplier would be 5? So that

multiply_by_5(2)
10


Is there a way in Python 2.7 to do that?

Answer

You can use functools.partial with keyword argument:

>>> def multiply_by(x, multiplier):
...     return x * multiplier
...
>>> from functools import partial
>>> multiply_by_5 = partial(multiply_by, multiplier=5)
>>> multiply_by_5(2)
10