mheleno
mheleno

Reputation: 23

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 of assigning multiple functions (ie, a function of a function) to a variable? For example:

sin = math.sin(math.radians) # I cannot use this with brackets
print sin (my_number_in_degrees)

Upvotes: 2

Views: 3283

Answers (3)

martineau
martineau

Reputation: 123473

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 3
    from functools import reduce

def compose(*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

Upvotes: 1

ssm
ssm

Reputation: 5373

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 

def chainFunctions(functions):
    def innerFunction(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)

Upvotes: 2

TigerhawkT3
TigerhawkT3

Reputation: 49310

Just create a wrapper function:

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

Call your wrapper function as normal:

print sin_rad(my_number_in_degrees)

Upvotes: 5

Related Questions