chrise chrise - 1 year ago 60
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


Is there a way in Python 2.7 to do that?

Answer Source

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)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download