omer mazig omer mazig - 6 months ago 8
Python Question

Passing SOME of the parameters to a function in python

Let's say I have:

def foo(my_num, my_string):
...


And I want to dynamically create a function (something like a lambba) that already has my_string, and I only have to pass it my_num:

foo2 = ??(foo)('my_string_example')
foo2(5)
foo2(7)


Is there a way to do that?

Answer

This is what functools.partial would help with:

from functools import partial

foo2 = partial(foo, my_string="my_string_example")

Demo:

>>> from functools import partial
>>> def foo(my_num, my_string):
...     print(my_num, my_string)
... 
>>> foo2 = partial(foo, my_string="my_string_example")
>>> foo2(10)
(10, 'my_string_example')
>>> foo2(30)
(30, 'my_string_example')
Comments