Skip to content Skip to sidebar Skip to footer

Assign Multiple Functions To A Single Variable?

In Python we can assign a function to a variable. For example, the math.sine function: sin = math.sin rad = math.radians print sin(rad(my_number_in_degrees)) Is there any easy way

Solution 1:

Just create a wrapper function:

def sin_rad(degrees):
    returnmath.sin(math.radians(degrees))

Call your wrapper function as normal:

print sin_rad(my_number_in_degrees)

Solution 2:

I think what the author wants is some form of functional chaining. In general, this is difficult, but may be possible for functions that

  1. take a single argument,
  2. return a single value,
  3. the return values for the previous function in the list is of the same type as that of the input type of the next function is the list

Let us say that there is a list of functions that we need to chain, off of which take a single argument, and return a single argument. Also, the types are consistent. Something like this ...

functions = [np.sin, np.cos, np.abs]

Would it be possible to write a general function that chains all of these together? Well, we can use reduce although, Guido doesn't particularly like the map, reduce implementations and was about to take them out ...

Something like this ...

>>>reduce(lambda m, n: n(m), functions, 3)
0.99005908575986534

Now how do we create a function that does this? Well, just create a function that takes a value and returns a function:

import numpy as np 

defchainFunctions(functions):
    definnerFunction(y):
        return reduce(lambda m, n: n(m), functions, y)
    return innerFunction

if __name__ == '__main__':
    functions = [np.sin, np.cos, np.abs]
    ch = chainFunctions( functions )
    print ch(3)

Solution 3:

You could write a helper function to perform the function composition for you and use it to create the kind of variable you want. Some nice features are that it can combine a variable number of functions together that each accept a variable number of arguments.

import math
try:
    reduce
except NameError:  # Python 3from functools import reduce

defcompose(*funcs):
    """ Compose a group of functions (f(g(h(...)))) into a single composite func. """return reduce(lambda f, g: lambda *args, **kwargs: f(g(*args, **kwargs)), funcs)

sindeg = compose(math.sin, math.radians)

print(sindeg(90))  # -> 1.0

Post a Comment for "Assign Multiple Functions To A Single Variable?"