chrise - 10 months ago 42

Python Question

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
```

Source (Stackoverflow)