'how to use value outside async function in python
I have a python async function. I am taking data from postgreSql database using this code:
stores = await db.select_all_stores()
After retrieving data, I am going to use Shops value outside function. I need import this variable from another module.
async def get_all_stores():
global Shops
Shops = []
stores = await db.select_all_stores()
print(stores)
for store in stores:
storeName = []
storeDict = {'lat': '', 'lon': ''}
storeDict['lat'] = float(store[6])
storeDict['lon'] = float(store[7])
storeName.append(store[1])
storeName.append(storeDict)
storeName = tuple(storeName)
Shops.append(storeName)
return Shops
Solution 1:[1]
You could simply return shops list(as you did) or tuple and assign to the Shops variable before all your handlers. example:
async def get_all_stores():
# global Shops
# Shops = []
shops_list = []
stores = await db.select_all_stores()
print(stores)
for store in stores:
storeName = []
storeDict = {'lat': '', 'lon': ''}
storeDict['lat'] = float(store[6])
storeDict['lon'] = float(store[7])
storeName.append(store[1])
storeName.append(storeDict)
storeName = tuple(storeName)
shops.append(storeName)
return shops_list
Shops = await get_all_stores()
@dp.message_handler()
async def example(message: types.Message):
# do something with your Shops variable
if __name__ == '__main__':
executor.start_polling(dp, skip_updates=True)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Maksim K. |
