Search code examples
pythonkeyword-argument

How to Use Variables as Keywords in Function in Python


I need to be able to input variables as keyword arguments to a secondary function in Python. See the example code below:

def _1st_function(arg1,arg2,arg3='test1'):

    var1 = arg1 + arg2 + arg3

    return var1

def _2nd_function(**kwargs):

    _1st_function(kwargs)

test_run1 = _2nd_function(arg1='test1',arg2='test2',arg3='test3')
test_run2 = _2nd_function(arg1='test1',arg2='test2')

I know that **kwargs creates a dictionary so I understand why this isn't working. I need a solution that is as dynamic as possible, being able to take different numbers of keyword inputs and pass them into the second function.

I understand that this solution has probably been solved somewhere, I don't think I know the right terms to effectively search for a solution to this problem, hence I wasn't able to find the solution through my research.


Solution

  • Just destruct the arguments to the next function

    def _2nd_function(**kwargs):
        return  _1st_function(**kwargs)