Search code examples
pythonstringgetattr

Get content of a string variable using getattr


I would like to know how to retrieve the content of a string variable so that I can use its value as an argument name in a function. Here the code:

import pandas
import jinja2

oDateList = ['2017-03-22','2017-03-23','2017-03-24']
oData = pandas.DataFrame()
oData['Date'] = oDateList
MyTemplate = 'Today is {{ Date }}'
oTemplate = jinja2.Template(MyTemplate)

for oRow in oData.index:
    for oColumn in oData.columns:
        MyTemplateUpdated = oTemplate.render(Date=oData.loc[oRow, oColumn])
        print(MyTemplateUpdated)

It works well and returns:

Today is 2017-03-22
Today is 2017-03-23
Today is 2017-03-24

I would like to dynamically retrieve the argument name Date= from the dataframe column name oColumn (which is 'Date'). I thought about using getattr(oColumn, 'something') but did not figure out how to do so.

I have also tried str(oColumn) and it returns the error: SyntaxError: keyword can't be an expression

Thank you


Solution

  • If you want to dynamically set the argument name being sent to a function, you'll need to use kwargs.

    render(**{argument_name: argument_value}
    

    So in your case, assuming that oColumn contains the string you wish to be the argument, it would look something like this;

    render(**{oColumn: oData.loc[oRow, oColumn]})
    

    Let me know if I have misunderstood your intent.