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:
- The name table's columns are
id
andfullname
. - The phone table's columns are
id
andphonenum
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.)