Question

I have a program that has an update_database() function but I don't know what the keyword arguments will be until runtime, so one time the function is called it may need to be:

table_name = 'example1'
update_database(table_name, column1='...', column3='...')

but another time it may be:

table_name = 'example2'
update_database(table_name, column5='...', column2='...')

So the function calls will need to be a mix of regular arguments and keyword arguments. The keyword argument names I have access to as a list so I can format them any old way I like easy enough but I m not sure if this behaviour is even possible in python.

Does anybody know if/how this may be possible?

UPDATE:

Its also worth noting that the update_database() function is part of an imported module so i cant modify its definition, I could wrap it somehow but I'm not sure if this gains me anything.

Was it helpful?

Solution

You can always use undefined number of keyword arguments in your original function, like:

(In the case of keyword arguments, you have a simple dictionary instead of a list)

def update_database(tname, **columns):
    for key, value in columns.items():
        # do something with key-value pairs

UPDATE:

So I guess, this is what we are talking about in the comment section, am I correct?

# Create dictionaries with keys as keywords and values as argument values
kwargs0 = {'arg0': 0, 'arg1': 2, 'arg2': 5}
kwargs1 = {'arg99': 1, 'arg13': None, 'arg0': 7}

# Call the function and UNPACK the dictionaries
update_database('db_name', **kwargs0)
update_database('db_name', **kwargs1)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top