Search code examples
pythonfunctionkeyword-argument

Using kwargs in a function in Python properly


I am experimenting with the use of kwargs in a function in Python, but I can't get it right.

Here is what I attempted:

def f_add(x, y, a):

    return(x + y + a)

def f_add_wrapper(f_, b, **kwargs):

    return(f_add(x,y,a**b))

f_add_wrapper(f_ = f_add, b = 2, **{'x' : 2, 'y' :3, 'a' : 2})
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-236-b37777c914bd> in <module>()
----> 1 f_add_wrapper(f_ = f_add, b = 2, kwargs = [2, 3,  2])

<ipython-input-229-5e01b9db8974> in f_add_wrapper(f_, b, **kwargs)
      1 def f_add_wrapper(f_, b, **kwargs):
      2 
----> 3     return(f_add(x,y,a**b))

NameError: name 'x' is not defined

f_add_wrapper(f_ = f_add, b = 2, **{x : 2, y :3, a : 2})
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-248-b862f2191e7b> in <module>()
----> 1 f_add_wrapper(f_ = f_add, b = 2, **{x : 2, y :3, a : 2})

NameError: name 'x' is not defined

Solution

  • If i got your question right the solution would may be the following: You have to change the f_add_wrapper method and pass the kwargs to the inner method.

    def f_add_wrapper(f_, b, **kwargs):
        return f_add(**kwargs)
    

    But i haven't used the args f_ and b right now. If you want to use f_ as method you have to write:

    def f_add_wrapper(f_, b, **kwargs):
        return f_(**kwargs) 
    

    If you want to use the variable a as well, I would add a explicit to your list of arguments:

    def f_add_wrapper(f_, b, a, **kwargs):
        a_to_power_of_b = a**b
        return f_(a=a_to_power_of_b , **kwargs) 
    

    With this solution every variable which is not explicitly mentioned in the list of arguments of the wrapper is passed to the inner function. The explicitly listed variables are accessible within the wrapper.