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?
The * symbol is used to pass a variable number of arguments to a function. Typically, this syntax is used to avoid the code failing when we don't know how many arguments will be sent to the function.
Python allows you to pass multiple arguments to a function. To assign a value to a global variable in a function, the global variable must be first declared in the function. The value assigned to a global constant can be changed in the mainline logic.
As you expect it, Python has also its own way of passing variable-length keyword arguments (or named arguments): this is achieved by using the **kwargs symbol. When using **kwargs, all the keywords arguments you pass to the function are packed inside a dictionary.
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')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With