0

It's hard for me to describe what I'm trying to do for the title, but I feel like what I'm looking for is actually pretty simple.

So, I have a Python script that pulls data from a JSON config file and then executes a set of SQL queries.

The SQL queries are stored in the JSON file under Queries.{name of query}.query, like this: Queries.List_of_Teams.query, etc.

My main function iterates through the queries available in the JSON file like this:

    for i in conf.Queries:
        run_query(i)

and the function run_query looks like this:

def run_query(query_name):
    join_query = ' '.join(conf.Queries.query_name.query)
    CAT_query = join_query.format(CAT_start_date, CAT_end_date)
...

I'm struggling with the first line of the function. How can I replace query_name in that first line with the actual query name passed to it from the for loop? I've validated that i and query_name are both List_of_Teams, but I get this error when I run the script:

    join_query = ' '.join(conf.Queries.query_name.query)
                          ^^^^^^^^^^^^^^^^^^^^^^^
KeyError: 'query_name'
  • 1
    `KeyError` instead of `AttributeError` suggests that it might be some exotic type where `conf.Queries[query_name]` works too. – Ry- Mar 07 '23 at 20:59

1 Answers1

1

With the power of getattr:

join_query = ' '.join(getattr(conf.Queries, query_name).query)
Guimoute
  • 4,407
  • 3
  • 12
  • 28