Passing all arguments of a function to another function

PythonFunctionArguments

Python Problem Overview


I want to pass all the arguments passed to a function(func1) as arguments to another function(func2) inside func1 This can be done with *args, *kwargs in the called func1 and passing them down to func2, but is there another way?

Originally

def func1(*args, **kwargs):
    func2(*args, **kwargs)

but if my func1 signature is

def func1(a=1, b=2, c=3):

how do I send them all to func2, without using

def func1(a=1, b=2, c=3):
    func2(a, b, c)

Is there a way as in javascript callee.arguments?

Python Solutions


Solution 1 - Python

Explicit is better than implicit but if you really don't want to type a few characters:

def func1(a=1, b=2, c=3):
    func2(**locals())

locals() are all local variables, so you can't set any extra vars before calling func2 or they will get passed too.

Solution 2 - Python

Provided that the arguments to func1 are only keyword arguments, you could do this:

def func1(a=1, b=2, c=3):
    func2(**locals())

Solution 3 - Python

As others have said, using locals() might cause you to pass on more variables than intended, if func1() creates new variables before calling func2().

This is can be circumvented by calling locals() as the first thing, like so:

def func1(a=1, b=2,c=3):
    par = locals()

    d = par["a"] + par["b"]

    func2(**par)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionroopeshView Question on Stackoverflow
Solution 1 - PythonJochen RitzelView Answer on Stackoverflow
Solution 2 - PythonKip StreithorstView Answer on Stackoverflow
Solution 3 - PythonOlsgaardView Answer on Stackoverflow