Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing SOME of the parameters to a function in python

Tags:

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?

like image 957
omer mazig Avatar asked May 06 '16 16:05

omer mazig


People also ask

How do you pass multiple parameters to a function?

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.

Does Python allow you to pass multiple arguments to a 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.

How do you pass variable number of arguments to a function in Python?

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.


1 Answers

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')
like image 183
alecxe Avatar answered Oct 30 '22 12:10

alecxe