I have some python code that defines a new function based on an old one. It looks like this
JavaScript
x
5
1
def myFunction(a: int, b: int, c: int):
2
# Do stuff
3
4
myNewFunction = lambda a, b: myFunction(a, b, 0)
5
My new function is the same as the old function, but sets the last argument to 0.
My question: Say I did not know the function took three arguments. Can I make the above solution more generic? An invalid solution with the right intention might be something like:
JavaScript
1
8
1
def myFunction(a: int, b: int, c: int):
2
# Do stuff
3
4
func_args = myFunction.__code__.co_varnames
5
func_args = func_args[:-1]
6
7
myNewFunction = lambda *func_args : myFunction(*func_args, 0)
8
Advertisement
Answer
You’re almost correct, you can use functools.partial
this way(instead of lambda):
JavaScript
1
10
10
1
from functools import partial
2
3
def myFunction(a: int, b: int, c: int):
4
print(a, b, c)
5
6
last_param_name = myFunction.__code__.co_varnames[-1]
7
new_func = partial(myFunction, **{last_param_name: 0})
8
9
new_func(10, 20)
10
Technically partial
is not a function it’s a class but I don’t think this is what you concern about.
A pure Python (roughly)equivalent of the original partial
exists in documentation if you want it to be a function type:
JavaScript
1
9
1
def partial(func, /, *args, **keywords):
2
def newfunc(*fargs, **fkeywords):
3
newkeywords = {**keywords, **fkeywords}
4
return func(*args, *fargs, **newkeywords)
5
newfunc.func = func
6
newfunc.args = args
7
newfunc.keywords = keywords
8
return newfunc
9