16

Is it possible to assign a function to a variable with modified default arguments?

To make it more concrete, I'll give an example. The following obviously doesn't work in the current form and is only meant to show what I need:

def power(a, pow=2):
    ret = 1
    for _ in range(pow):
        ret *= a
    return ret

cube = power(pow=3)

And the result of cube(5) should be 125.

3 Answers 3

22

functools.partial to the rescue:

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.

from functools import partial

cube = partial(power, pow=3)

Demo:

>>> from functools import partial
>>> 
>>> def power(a, pow=2):
...     ret = 1
...     for _ in range(pow):
...         ret *= a
...     return ret
... 
>>> cube = partial(power, pow=3)
>>> 
>>> cube(5)
125
Sign up to request clarification or add additional context in comments.

Comments

8

The answer using partial is good, using the standard library, but I think it's worth mentioning that the following approach is equivalent:

def cube(a):
   return power(a, pow=3)

Even though this doesn't seem like assignment because there isn't a =, it is doing much the same thing (binding a name to a function object). I think this is often more legible.

Comments

3

In specific there's a special function for exponents:

>>> 2**3
8

But I also solved it with a lambda function, which is a nicer version of a function pointer.

# cube = power(pow=3)  # original
cube = lambda x: power(x,3)

2 Comments

That was just an example to make what I needed clear. I was not looking for the implementation of the power or cube function.
This is the best answer!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.