JD2775
JD2775

Reputation: 3801

Using variables from one .py file in a loop in another .py file

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

Answers (1)

Razmik Melikbekyan
Razmik Melikbekyan

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

Related Questions