5

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?

2 Answers 2

5

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')
Sign up to request clarification or add additional context in comments.

1 Comment

Exactly what I needed. Thanks!
0

This should do it:

>>> def foo(a, b):
...    return a+b
...
>>> def makefoo2(a):
...    def f(b):
...        return foo(a,b)
...    return f
...
>>> foo2 = makefoo2(3)
>>> foo2(1)
4

Obviously you can vary the definition of foo to taste.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.