I need some help to solve the problem : I have two files : "main.py" and let's say "script.py"
The "script.py" contains a func() that generates variable amount of lists (programm uses Database, so amount of lists and data inside is vary):
def func():
try:
connect = psycopg2.connect(database = 'car_rental',
user = 'postgres',
password = 'datapass')
curs = connect.cursor()
#iteration that creates the list contains all models available for every single brand with name '{category}_{brand.lower()}'
# (in this case: economy_{brand.lower()})
temp_var = ''
for brand in economy_brands_list:
curs.execute("""SELECT DISTINCT model
FROM fleet
WHERE category = %s and brand = %s""", ('economy', f'{brand}'))
expres = [x[0] for x in curs.fetchall()]
temp_var =f"economy_{brand.lower()} = {expres}\n"
exec(temp_var)
finally:
curs.close()
connect.close()
In "main.py" i want to use the list(s) generated in func(). So i imported func() to 'main.py', call the func(), but it gives the error instead.NameError : name 'economy_{brand}' is not defined. From the 'script.py' (which contains func()) the function works and i'm able to print the lists generated. How to make 'main.py' to define the lists generated in func()? Thank You in advance.
CodePudding user response:
To expand on Tierry Lathuille's answer, you may want something like this:
def func():
economy_brands = {}
try:
connect = psycopg2.connect(database = 'car_rental',
user = 'postgres',
password = 'datapass')
curs = connect.cursor()
#iteration that creates the list contains all models available for every single brand with name '{category}_{brand.lower()}'
# (in this case: economy_{brand.lower()})
temp_var = ''
for brand in economy_brands_list:
curs.execute("""SELECT DISTINCT model
FROM fleet
WHERE category = %s and brand = %s""", ('economy', f'{brand}'))
expres = [x[0] for x in curs.fetchall()]
economy_brands[f"economy_{brand.lower()}"] = expres
finally:
curs.close()
connect.close()
return economy_brands