从异步函数返回时字典变成集合?
Dictionaries turn into sets when returned from async functions?
我有一个运行以下函数的函数:
people_related_data = []
try:
task_list = []
for person in people:
task_list.append(asyncio.create_task(
process_for_bubble_chart(person)))
results = await asyncio.wait(task_list, return_when="ALL_COMPLETED")
people_related_data.extend(dict(results))
except Exception as err:
print(err)
print_tb(err.__traceback__)
在该代码块中,您有如下所示的 process_for_bubble_chart()
函数:
async def process_for_bubble_chart(person: OwnObject) -> Dict[str, list]:
"""
Function that fetches related entities from the database
based on the people objects within the 'people' list.
"""
data = dict()
related_entities = []
try:
task_list = [
asyncio.create_task(person.get_related_companies()),
asyncio.create_task(person.get_related_businesses()),
asyncio.create_task(person.get_related_limited_partners()),
asyncio.create_task(person.get_related_factories()),
asyncio.create_task(person.get_related_stockcompanies())
]
results = await asyncio.wait(task_list, return_when="ALL_COMPLETED")
except Exception as err:
print(Fore.RED, err, Style.RESET_ALL)
print_tb(err.__traceback__)
raise DataUtilError(
"Could not process tasks to get data for {}".format(person.name))
related_entities.extend(results)
data = {
"name": person.name,
"pos": person.position,
"related": related_entities
}
return data
在第一个函数的下方,我尝试像这样遍历结果:
for p_data in people_related_data:
if p_data["name"] not in count_dict.keys():
count_dict.update(
{p_data["name"]: len(p_data["related"])})
真正的问题是之前我把整个过程变成了async
,它没有错误。但是一旦我将过程转换(至少尝试)为上面的过程,我在打印结果时从第一个函数得到以下结果:
[{<Task finished name='Task-6' coro=<process_for_bubble_chart() done, defined at /Users/wilbertung/Documents/GitHub/ChiSo/backend/util/DataUtil.py:10> result={'name': '賴昆賢', 'pos': '董事長', 'related': [{<Task finishe...47> result=[]>, <Task finishe...12> result=[]>, <Task finishe...23> result=[]>, <Task finishe...fad3610f310>]>, <Task finishe...36> result=[]>}, set()]}>,
<Task finished name='Task-5' coro=<process_for_bubble_chart() done, defined at /Users/wilbertung/Documents/GitHub/ChiSo/backend/util/DataUtil.py:10> result={'name': '劉恒逸', 'pos': '監察人', 'related': [{<Task finishe...36> result=[]>, <Task finishe...01> result=[]>, <Task finishe...47> result=[]>, <Task finishe...12> result=[]>, <Task finishe...23> result=[]>}, set()]}>},
set()]
'set' object is not subscriptable
File "/Users/wilbertung/Documents/GitHub/ChiSo/backend/service/gcis.py", line 1289, in get_company_related_data
if p_data["name"] not in count_dict.keys():
所以,如果我错了,请纠正我,但这是否意味着:
- 我的
process_for_bubble_chart()
结果实际上是 set
而不是最初预期的 dict
?
或者
- 我在这个过程中搞砸了一些东西,导致结果以某种方式转换为集合?
asyncio.wait()
returns 一个元组。你必须像这样解压它:
done, pending = await asyncio.wait(task_list, return_when="ALL_COMPLETED")
更多信息here
我有一个运行以下函数的函数:
people_related_data = []
try:
task_list = []
for person in people:
task_list.append(asyncio.create_task(
process_for_bubble_chart(person)))
results = await asyncio.wait(task_list, return_when="ALL_COMPLETED")
people_related_data.extend(dict(results))
except Exception as err:
print(err)
print_tb(err.__traceback__)
在该代码块中,您有如下所示的 process_for_bubble_chart()
函数:
async def process_for_bubble_chart(person: OwnObject) -> Dict[str, list]:
"""
Function that fetches related entities from the database
based on the people objects within the 'people' list.
"""
data = dict()
related_entities = []
try:
task_list = [
asyncio.create_task(person.get_related_companies()),
asyncio.create_task(person.get_related_businesses()),
asyncio.create_task(person.get_related_limited_partners()),
asyncio.create_task(person.get_related_factories()),
asyncio.create_task(person.get_related_stockcompanies())
]
results = await asyncio.wait(task_list, return_when="ALL_COMPLETED")
except Exception as err:
print(Fore.RED, err, Style.RESET_ALL)
print_tb(err.__traceback__)
raise DataUtilError(
"Could not process tasks to get data for {}".format(person.name))
related_entities.extend(results)
data = {
"name": person.name,
"pos": person.position,
"related": related_entities
}
return data
在第一个函数的下方,我尝试像这样遍历结果:
for p_data in people_related_data:
if p_data["name"] not in count_dict.keys():
count_dict.update(
{p_data["name"]: len(p_data["related"])})
真正的问题是之前我把整个过程变成了async
,它没有错误。但是一旦我将过程转换(至少尝试)为上面的过程,我在打印结果时从第一个函数得到以下结果:
[{<Task finished name='Task-6' coro=<process_for_bubble_chart() done, defined at /Users/wilbertung/Documents/GitHub/ChiSo/backend/util/DataUtil.py:10> result={'name': '賴昆賢', 'pos': '董事長', 'related': [{<Task finishe...47> result=[]>, <Task finishe...12> result=[]>, <Task finishe...23> result=[]>, <Task finishe...fad3610f310>]>, <Task finishe...36> result=[]>}, set()]}>,
<Task finished name='Task-5' coro=<process_for_bubble_chart() done, defined at /Users/wilbertung/Documents/GitHub/ChiSo/backend/util/DataUtil.py:10> result={'name': '劉恒逸', 'pos': '監察人', 'related': [{<Task finishe...36> result=[]>, <Task finishe...01> result=[]>, <Task finishe...47> result=[]>, <Task finishe...12> result=[]>, <Task finishe...23> result=[]>}, set()]}>},
set()]
'set' object is not subscriptable
File "/Users/wilbertung/Documents/GitHub/ChiSo/backend/service/gcis.py", line 1289, in get_company_related_data
if p_data["name"] not in count_dict.keys():
所以,如果我错了,请纠正我,但这是否意味着:
- 我的
process_for_bubble_chart()
结果实际上是set
而不是最初预期的dict
? 或者 - 我在这个过程中搞砸了一些东西,导致结果以某种方式转换为集合?
asyncio.wait()
returns 一个元组。你必须像这样解压它:
done, pending = await asyncio.wait(task_list, return_when="ALL_COMPLETED")
更多信息here