0

I have a sql_data.py file that looks like this:

TABLE_A = '''Select * from Table_A;'''
TABLE_B = '''Select * from Table_B;'''

I have a main.py file where I want to loop over those variables and print the SQL.

import sql_data

tables = ['TABLE_A', 'TABLE_B']

# this doesn't work, but this is what I am looking for.  Something dynamic like below

for table in tables:
    print(SQL_DATA.[table])

# this works, but it's hard coding in the table name which I don't want

for table in tables:
    print(SQL_DATA.TABLE_A)

Any suggestions?

2
  • Did you try SQL_DATA.[table]? Commented Feb 24, 2021 at 19:06
  • 1
    Yep, sorry. Had typo in code. I did try lowercase. Doesnt work. Commented Feb 24, 2021 at 19:07

1 Answer 1

1

You should use the variable that you loop (aka, table) and getattr for getting attribute.

for table in tables:
    print(getattr(SQL_DATA, table))
Sign up to request clarification or add additional context in comments.

1 Comment

Perfect, that worked. I will accept when the timer lets me. Thanks again

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.