James Draper James Draper - 1 month ago 17
Python Question

Can I dynamically switch functions inside of a function in python 3.x?

In Python 3.x is it possible to dynamically choose a function inside of a function or class?
For example in the function below, instead of relying on conditional statements could just enter the method that I would like to use?

def npMethodChooser(n,m,method):
if method == "mean":
return np.random.rand(n,m).mean(axis=1)
if method == "std":
return np.random.rand(n,m).std(axis=1)

Answer

Dynamic attribute lookup may be done by using getattr function.

def npMethodChooser(n, m, method):
    return getattr(np.random.rand(n,m), method)(axis=1)