I want to pass different calculation methods to a function, for example:
def example_func(method='mean'):
result = np.+method([1,2,3,4])
What is the easiest and most fruitful way to do this (besides maybe a dictionary....)
I want to pass different calculation methods to a function, for example:
def example_func(method='mean'):
result = np.+method([1,2,3,4])
What is the easiest and most fruitful way to do this (besides maybe a dictionary....)
You can pass the function object itself, then call it within your function
import numpy as np
def do_func(f, arg):
return f(arg)
>>> do_func(np.mean, [1,2,3,4])
2.5
You can see that the argument in the example above (f
) is itself a function, so you can call it with whatever you want inside your function.
As written, you can do
getattr(np, method)([1,2,3,4])
or
from operator import methodcaller
f = methodcaller(method, [1,2,3,4])
f(np)
or just pass the function directly into the other function. Functions are first-class objects.