Javier Lopez Tomas
Javier Lopez Tomas

Reputation: 2362

Using string as parameter name

I have the following functions:

def train(data,**kwargs):
    train_model(data,**kwargs)

def test_train_parameters(data1,data2,parameter_to_test, parameter_value):
    train(data1,**kwargs)
    train(data2,**kwargs)

Train function has some optional parameters, such as gamma, lambda, num_rounds and so on. Train with data1 would be called without any modified parameter, but train with data2 would be called with a parameter modified and it's value. For example, let's say I want a gamma = 5, I would code:

test_train_parameters(parameter_to_test = 'gamma', parameter_value = 5)

And the function would be called as follow:

train(data1)
train(data2, gamma = 5)

Thus, this can not be done just calling the parameter as test_train_parameters(gamma = 5)because it would interfere with the first train.

I have been searching on google but I have been unable to find something that fits my case (I have found eval, getattr, passing list... but those are for other things). How could I make it?

Upvotes: 0

Views: 99

Answers (2)

Alexandre Senges
Alexandre Senges

Reputation: 1599

In python, kwargs are just dictionaries, so you can create a dictionary in your function with your arguments:

def test_train_parameters(data1,data2,parameter_to_test, parameter_value):
    train(data1)
    kwargs = {parameter_to_test: parameter_value}
    train(data2,**kwargs)

Upvotes: 4

zslim
zslim

Reputation: 481

An if with every possible parameter? Like

def test_train_parameters(data1,data2,parameter_to_test, parameter_value):
    train(data1)
    if parameter_to_test == 'alpha':
        train(data2, alpha=parameter_value)
    elif parameter_to_test == 'beta':
        train(data2, beta=parameter_value)
    elif parameter_to_test == 'gamma':
        train(data2, gamma=parameter_value)

I know it's not pleasing to the eye but it's a simple way to do it.

Upvotes: 1

Related Questions