Skip to content
Advertisement

Using lambda to define a function based on another: How do I keep my code generic?

I have some python code that defines a new function based on an old one. It looks like this

def myFunction(a: int, b: int, c: int):
    # Do stuff

myNewFunction = lambda a, b: myFunction(a, b, 0)

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:

def myFunction(a: int, b: int, c: int):
    # Do stuff

func_args = myFunction.__code__.co_varnames
func_args = func_args[:-1]

myNewFunction = lambda *func_args : myFunction(*func_args, 0)

Advertisement

Answer

You’re almost correct, you can use functools.partial this way(instead of lambda):

from functools import partial

def myFunction(a: int, b: int, c: int):
    print(a, b, c)

last_param_name = myFunction.__code__.co_varnames[-1]
new_func = partial(myFunction, **{last_param_name: 0})

new_func(10, 20)

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:

def partial(func, /, *args, **keywords):
    def newfunc(*fargs, **fkeywords):
        newkeywords = {**keywords, **fkeywords}
        return func(*args, *fargs, **newkeywords)
    newfunc.func = func
    newfunc.args = args
    newfunc.keywords = keywords
    return newfunc
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement