Reputation: 3801
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?
Upvotes: 0
Views: 46
Reputation: 758
You should use the variable that you loop (aka, table
) and getattr
for getting attribute.
for table in tables:
print(getattr(SQL_DATA, table))
Upvotes: 1