Reputation: 458
There are a number of StackOverflow questions asking about using a variable as a variable (like this and this, but I don't think this is a duplicate of those. I want to know if I can use the value of a variable as a function parameter.
For example, let's say I want to call a function that will populate one of two different MySQL tables:
id
and fullname
.id
and phonenum
data = get_data() # data = a full name or a phone number
data_type = get_data_type(data) # data_type = "name" or "phone"
....
column_names_for_tables = {'name': 'fullname', 'phone': 'phonenum'}
column_name = column_names_for_tables[data_type]
# column_name now = "fullname" or "phonenum", depending on the value of #data
new_entry = MakeNewEntry(date=datetime.datetime.now(), id=123, <column_name>=data)
Of course that last line is not valid Python, but my goal is to dynamically generate the function call:
new_entry = MakeNewEntry(date=datetime.datetime.now(), id=123, fullname=data)
or
new_entry = MakeNewEntry(date=datetime.datetime.now(), id=123, phonenum=data)
That is, I want to use the value of column_name
as the name of my parameter.
Can I do that?
(For this example, please assume that MakeNewEntry()
is not under my control - it will accept date
, id
, and a phonenum
or fullname
parameter, but can't be refactored.)
Upvotes: 3
Views: 105
Reputation: 12090
You can use the double star operator to pass in arbitrary arguments to a function:
col = 'foo'
val = 'bar'
kwargs = {col: bar}
some_function(**kwargs)
And you can make that shorter by inlining the dictionary like so:
some_function(**{col: var})
You can mix and match the syntax and end up with something like this:
MakeNewEntry(date=datetime.datetime.now(), id=123, **{column_name: data})
Upvotes: 2