alvas
alvas

Reputation: 122032

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?

Upvotes: 2

Views: 76

Answers (1)

Brendan Abel
Brendan Abel

Reputation: 37509

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

Upvotes: 3

Related Questions