martian_rover
martian_rover

Reputation: 341

Make list's values to boolean in custom function arguments

I have a given list and a custom function with some parameters. The list contains the parameters in string form and i want to change these parameters to True if list contains else remain false in function.

Here is example:

list_params = ['remove_digits','remove_stopwords','clean_data']

custom_function(remove_digits =False, clean_data =False, remove_stopwords = False, text_lemmatization =False)

Here all parameters are false first but as soon as list contains these parameters, select them to True in function else remains false. I want all the parameters to True at once if present in list.

Upvotes: 1

Views: 275

Answers (2)

Tomerikoo
Tomerikoo

Reputation: 19414

Assuming your function definition is something like:

def custom_function(remove_digits=False, clean_data=False, remove_stopwords=False, text_lemmatization=False):

So you want to "turn on" the arguments from the list. You can do this by converting the list to a kwargs dict and unpack it to the function call:

list_params = ['remove_digits','remove_stopwords','clean_data']
dict_params = {param: True for param in list_params}

custom_function(**dict_params)

Upvotes: 2

Thibault D.
Thibault D.

Reputation: 301

The best would probably to change the signature of custom_function to receive a list of parameters. If you cannot change it, you can still call your function like this:

custom_function(remove_digits in list_params, clean_data in list_params, remove_stopwords in list_params, text_lemmatization in list_params)

Otherwise, if you have the list of the parameters expected by the function, for example the list params = ['remove_digits', 'clean_data', 'remove_stopwords', 'text_lemmatization'] (which you can get with inspect.signature), you can write args = [x in list_params for x in params], and call custom_function as custom_function(*args):

list_params = ['remove_digits','remove_stopwords','clean_data']

import inspect
params = list(inspect.signature(custom_function).parameters)
# params = ['remove_digits', 'clean_data', 'remove_stopwords', 'text_lemmatization']
args = [x in list_params for x in params]
custom_function(*args)

Upvotes: 1

Related Questions