omer mazig omer mazig - 9 months ago 30
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')

Is there a way to do that?


This is what functools.partial would help with:

from functools import partial

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


>>> 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')