1

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)
2
  • I don't have co_argvars 'co_argvars' in dir(myFunction.__code__) results to False. Commented Dec 3, 2022 at 20:33
  • Yes, it unfortunately doesn't exist. But I can see how it makes the question confusing. I have edited accordingly. Commented Dec 3, 2022 at 20:39

1 Answer 1

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.