function names from config file in python
Question: I have a JSON config file which tells me what kind of distribution to sample
from. For example:

    
    
    { "parameter1" : { "distribution" : "exponential", "mean" = 5},
      "parameter2" : { "distribution" : "poisson", "mean" = 3} }
    

The list above can be exhaustive. I need have a function which will read this
json file, and return the appropriate distribution to the calling code.

I tried using string concatenation and `eval()`, but that gives me the sample
values directly. I should be able to return the object/function to the calling
function.

Can some one help me do it?

My attempt:

    
    
    import numpy.random as random
    
    def getDistribution(distribution, params):
        string= 'random.'+distribution
        return eval(string)(params["mean"])
    

This returns a value to me. Is there a way to return a handle to the actual
distribution function like `random.exponential()` or `random.poisson()` which
I can use in the function calling `getDistribution()`?


Answer: You can use getattr to return the method (which is an attribute of `random`):

    
    
    def get_method(name):
        return getattr(random, name, None)
    
    def get_distribution(method, params):
        return method(params['mean'])
    
    method_name = 'exponential'
    method = get_method(method_name)
    if method:
        results = get_distribution(method, params)
    else:
        raise AttributeError('No such method in random: {}'.format(method_name))
    

`getattr` takes an optional third argument which is the value to return when
the attribute cannot be found. I am using this to explicitly return `None`.
You can change that to a default method that you want to use if the chosen
method name is not available.

