3

How to use a function name as a parameter in Python? For example:

def do_something_with(func_name, arg):
    return func_name(arg)

where 'func_name' might be 'mean', 'std', 'sort', etc.

For example:

import numpy as np
func_list = ['mean', 'std']

for func in func_list:
    x = np.random.random(10)
    print do_something_with(func, x)

and of course the result should a successful application of 'mean' and 'std' on my array 'x'.

martineau
  • 119,623
  • 25
  • 170
  • 301
Arnold Klein
  • 2,956
  • 10
  • 31
  • 60
  • 7
    pass a list of functions instead. `func_list = [np.mean, np.std]` – Tadhg McDonald-Jensen Mar 02 '17 at 19:27
  • 2
    Possible duplicate of [Python - Passing a function into another function](http://stackoverflow.com/questions/1349332/python-passing-a-function-into-another-function) (although the bulk of the actual question is irrelevant, the root question and answers are valid) – Tadhg McDonald-Jensen Mar 02 '17 at 19:29

2 Answers2

10

As suggestet in the comments, pass function objects in a list to your function and call them. This will not just work with numpy, but with all Python functions:

import numpy as np
func_list = [np.mean, np.std]

for func in func_list:
    x = np.random.random(10)
    print func(x)

Make sure the function calls work all the same way, i.e. x as first parameter.

The above is pretty similar to how function renaming works:

import time

another_sleep = time.sleep
another_sleep(1)  # Sleep for one second

You create a function object (time.sleep) and assign it to a variable (another_sleep). Now you can call it with the variable's name (another_sleep(1)).

linusg
  • 6,289
  • 4
  • 28
  • 78
7

Tadhg McDonald-Jensen's solution is right because function is first-class citizen in Python. Also, I have another idea:

from operator import methodcaller

import numpy as np


func_list = ['mean', 'std']
for func in func_list:
    x = np.random.random(10)
    f = methodcaller(func, x)
    result = f(np)
    print(result)

You can use operator.methodcaller for some cases.

sangheestyle
  • 1,037
  • 2
  • 16
  • 28