alvas alvas - 1 month ago 7
Python Question

How to define function arguments partially? Python

If I have a function with some arguments, I can define a duck function like this:

>>> def f(x, y=0, z=42): return x + y * z
...
>>> f(1,2,3)
7
>>> g = f
>>> f(1,2)
85
>>> g(1,2)
85


I've tried to override the arguments partially but this didn't work:

>>> g = f(z=23)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: f() takes at least 1 argument (1 given)


How do I define function arguments partially for the duck function?

Answer

Use functools.partial

>>> from functools import partial
>>> def f(x, y=0, z=42): return x + y * z
... 
>>> g = partial(f, z=23)
>>> g(1,2)
47
>>> f(1,2,23)
47
Comments