Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python, assign function to variable, change optional argument's value

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.

like image 410
CentAu Avatar asked Jan 03 '16 05:01

CentAu


3 Answers

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.

like image 51
chthonicdaemon Avatar answered Oct 13 '22 09:10

chthonicdaemon


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
like image 42
alecxe Avatar answered Oct 13 '22 09:10

alecxe


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)
like image 27
nshiff Avatar answered Oct 13 '22 10:10

nshiff