mirunix
mirunix

Reputation: 31

Pass in function with default parameters

I have a function in Python f(a, b) and I am trying to define a new function g that takes in f with one argument already set, something like g(f(a = 5)). This would be a simple example:

def sum(a, b):
   return a+b

def g(x, f):
   return f(x)

And I want to be able to evaluate g(5, sum(b=0)). How do I do that?

Upvotes: 3

Views: 63

Answers (1)

J0HN
J0HN

Reputation: 26961

Using functools.partial:

g(5, partial(sum, b=5))

Return a new partial object which when called will behave like func called with the positional arguments args and keyword arguments keywords. If more arguments are supplied to the call, they are appended to args. If additional keyword arguments are supplied, they extend and override keywords

The partial() is used for partial function application which “freezes” some portion of a function’s arguments and/or keywords resulting in a new object with a simplified signature. For example, partial() can be used to create a callable that behaves like the int() function where the base argument defaults to two:

basetwo = partial(int, base=2)

Upvotes: 6

Related Questions