0

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.

jonathan topf
  • 7,897
  • 17
  • 55
  • 85

1 Answers1

3

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)
BenMorel
  • 34,448
  • 50
  • 182
  • 322
Peter Varo
  • 11,726
  • 7
  • 55
  • 77
  • Unfortunately I don't have the ability to change the definition as `update_database()` is a function from an external module – jonathan topf Sep 13 '13 at 12:23
  • I can show you how to wrap a function with another, but I'm not quite sure, what is the goal you want to achieve. Do you want to rename the keywords, before passing to this `update_database` function? Or do you want to filter them, to pass only some of the keywords? Or? – Peter Varo Sep 13 '13 at 12:45
  • Say I have a dict `keywords = {'arg1': 'value', 'arg2': 'value'}`, I'd like to use that dict as an argument for a function something like: `update_database('db_name', args=keywords)` rather than `update_database('db_name', arg1='value', arg2='value')` as those args may change at runtime, I hope that makes sense – jonathan topf Sep 13 '13 at 12:49
  • I updated my answer, see if that fits your needs @jonathantopf! – Peter Varo Sep 13 '13 at 12:55
  • thats exactly it, thanks! – jonathan topf Sep 13 '13 at 14:06