MrYouMath
MrYouMath

Reputation: 603

Python A function that takes a function as a parameter with its parameters

Imagine I have a two functions

def areaSquare(a,b):
   print( a * b)

def areaCircle(radius):
   print(3.14159 * radius ** 2)

And I want to create a third function that is called area.

area(areaCircle,radius = 3, repeat = 5)
# prints 3.14159 * 9 five times
area(areaSquare, a = 2, b = 3, repeat = 6)
# prints 2 * 6 six times

So the function takes a function as a parameter. Depending on the function which is passed to it as a parameter, it should require additional parameters. Is there a way to achieve this? I know function overloading would be an option. But I do not want to define multiple functions for this purpose.

Upvotes: 0

Views: 114

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476574

Yes, kwargs are your friend here. We can define the function such that the remaining parameters are captured in a dictionary named kwargs, and then passed to the function we provide. Like:

def area(func, repeat, **kwargs):
    for _ in range(repeat):
        func(**kwargs)

So all parameters except func and repeat are stored in the kwargs dictionary, and later we call the func function (the first argument) with the named parameters.

Note that this will not work (correctly) for functions that require a func and/or repeat parameter, since we capture these at the area function level.

Upvotes: 4

Related Questions