1

I want to create a wrapper function something like the following:

def functionWrapper(function, **kwargs):
    """
        This function requires as input a function and a dictionary of named arguments for that function.
    """
    results=function(**kwargs)
        print results

def multiply(multiplicand1=0, multiplicand2=0):
    return multiplicand1*multiplicand2

def main():
    functionWrapper(
        multiply,
        {
            'multiplicand1': 3,
            'multiplicand2': 4,
        }
    )

if __name__ == "__main__":
    main()

I am running into difficulties with this implementation:

TypeError: functionWrapper() takes exactly 1 argument (2 given)

How should I address this problem? Is my use of the arbitrary function in the wrapper function function(**kwargs) reasonable? Thanks for your help.

EDIT: fixed error in specification of dictionary

d3pd
  • 7,935
  • 24
  • 76
  • 127

3 Answers3

3

Use ** when passing the dict items to that function;

**{
   'multiplicand1': 3,
   'multiplicand2': 4,
  }

Output:

12

As pointed out by @svk in comments, functionWrapper's doctstring says:

This function requires as input a function and a dictionary of named arguments for that function.

So in that case you need to change the function definition to:

def functionWrapper(function, kwargs):

and also fix the typo in the dict otherwise you'll get 0 as answer:

'multiplicand1': 3,
'multiplicand1': 4,  #Change this to 'multiplicand2

'

Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504
  • 1
    And note the change to `multiplicand2` for the 2nd multiplicand – doctorlove Dec 06 '13 at 14:56
  • This doesn't seem to be in line with the docstring for `functionWrapper`, which seems to say that `functionWrapper` should take two arguments: one callable and one dictionary, not a callable and an arbitrary number of keyword arguments. – svk Dec 06 '13 at 14:57
2

Just change **kwargs to kwargs in function defenition:

def functionWrapper(function, kwargs):

What does ** (double star) and * (star) do for parameters?

Community
  • 1
  • 1
ndpu
  • 22,225
  • 6
  • 54
  • 69
1

I feel like the spirit of this question is begging for this answer as well, to make it a more general wrapper.

def functionWrapper(func, *args, **kwargs):

    results = func(*args, **kw)

    print results 

def multiply(multiplicand1=0, multiplicand2=0):
    return multiplicand1*multiplicand2

if __name__ == "__main__":

    functionWrapper(multiply, multiplicand1=3, multiplicand2=4)
    # 12

    functionWrapper(multiply, 3, 4)
    # 12

    functionWrapper(multiply, 3)
    # 0

    functionWrapper(multiply)
    # 0

    functionWrapper(multiply, 5, multiplicand2=4)
    # 20
HeyWatchThis
  • 21,241
  • 6
  • 33
  • 41