2

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....)

user3017048
  • 2,711
  • 3
  • 22
  • 32

2 Answers2

5

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.

Cory Kramer
  • 114,268
  • 16
  • 167
  • 218
2

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.

roippi
  • 25,533
  • 4
  • 48
  • 73