gowithefloww
gowithefloww

Reputation: 2251

Iterate over function parameters

The purpose is to build a function in order to construct a training set in a machine-learning project. I have several set of features I would like to try (separately, 2 by 2, combined..) so I put them as function parameters.

I also added a dictionary in order to call the "import functions" of chosen features sets.

For instance if I choose to import the set "features1", I will call import_features1().

I have trouble to iterate over the function parameters. I tried using **kwargs but it is not working as I expected.

Here is my function :

def construct_XY(features1=False, features2=False, features3=False, **kwargs):
    #  -- function dict
    features_function = {features1: import_features1,
                         features2: import_features2,
                         features3: import_features3}
    # -- import target
    t_target = import_target()

    # -- (trying to) iterate over parameters
    for key, value in kwargs.items():
        if value is True:
            t_features = features_function(key)()
    # -- Concat chosen set of features with the target table
            t_target = pd.concat([t_target, t_features], axis=1)

    return t_target

Should I use locals() as suggested here ?

What am I missing ?

Upvotes: 1

Views: 1105

Answers (1)

Ward
Ward

Reputation: 2852

You probably want to use something like this

# Only accepts keyword attributes
def kw_only(**arguments):
    # defaults
    arguments['features1'] = arguments.get('features1', False)
    arguments['features2'] = arguments.get('features2', False)
    arguments['features3'] = arguments.get('features3', False)

    for k, v in arguments.items():
        print (k, v)

print(kw_only(one=1, two=2))

using this construction, you will need to define the defaults in your function. You will only be able to pass in keyword arguments, and will be able to iterate over all of them.

Upvotes: 1

Related Questions