Karl
Karl

Reputation: 5822

Python: pass function as argument, evaluate with try/except and return result

I'm currently trying to extract model result information from H2O in Python.

For context, I have something along the following lines:

model = H2ODeepLearningEstimator(...)
model.train()

After the model is trained, I can call up the various model metrics. However, some metric will only be generated depending on the type of model.

So for example, I could call model.mse(valid=True) and it will return a value. but if I call model.aic(valid=True) it will throw and exception if AIC was not generated. This is a problem because I need to generate a function that writes all generated metrics to a HIVE table. If the metric has not been generated and calling it throws an except, we'll simply write NULL to hive.

So, I've tried to do the following:

param=None
try:
    param=tryParam(model.aic())
except:
    pass
print(param)

This will correctly return None for the AIC value

However, I need to do this for every parameter, so would prefer to wrap a generic function around it. For example, I would like to pass the function model.aic() as a parameter to a function called tryParam, which then evaluates it and catches any expections that occur. Such as:

def tryParam(getParam):
    try:
        return getParam
    except:   
        return None

tryParam(model.aic())
tryParam(model.mse())
tryParam(model.mae())
etc.

However, this does not work. When I call tryParam(model.aic()) the exception is raised and the program stops. It would seem to me that the parameter is being evaluated before it is passed to tryParam (hence triggering the exception before the code to handle it is actually called). This is only a guess though.

Does anyone know how I could do this?

Upvotes: 2

Views: 1961

Answers (2)

Alasdair
Alasdair

Reputation: 308789

Call the function inside tryParam with any args or kwargs passed.

def tryParam(getParam, *args, **kwargs):
    try:
        return getParam(*args, **kwargs)
    except:   
        return None

Then pass the function itself rather than calling it, along with any args or kwargs.

tryParam(model.aic, valid=True)

Upvotes: 4

Latrova
Latrova

Reputation: 493

I would try to do this way:

def tryParam(obj, methodName):
    method = getattr(obj, methodName, None)
    if method is not None:
        return method()

Then I can use like:

model = H2ODeepLearningEstimator(...)
model.train()

aic = tryParam(model, 'aic')
mse = tryParam(model, 'mse')
mae = tryParam(model, 'mae')

Repl.it example here

Upvotes: 1

Related Questions