Три способа выполнить множество задач с asyncio
Функция для примера:
async def do_it(n):
await asyncio.sleep(random.uniform(0.5, 1))
return n
1. Последовательный вызов
async def main():
for i in range(100):
result = await do_it(i)
Такой вызов имеет смысл только тогда, когда результат одной задачи требуется для вызова следующей.
Если они независимы, то это антипаттерн, так как аналогичен простому синхронному вызову по очереди.
2. Упорядоченный результат
async def main():
tasks = [do_it(i) for i in range(100)]
results = await asyncio.gather(*tasks)
Выполняет корутины конкурентно и возвращает результат в виде списка.
Полезен когда требуется получить результаты в том же порядке в котором задачи отправлены.
3. Результат по мере готовности
tasks = [asyncio.create_task(do_it(i)) for i in range(100)]
for cor in asyncio.as_completed(tasks):
result = await cor
Так же выполняет корутины конкурентно, но не гарантирует порядок. Результат возвращается по мере готовности, каждый отдельно.
Полезен когда нужно обработать любой ответ как можно скорее.
#async
News: At last day of its mandate, #Tigray interim administration president meets #PM_Abiy to present annual report
On the last day of its mandate, President of the Tigray Interim Administration, Lt. Gen. #Tadesse Worede, met Prime Minister Abiy Ahmed this morning to present his annual report, according to a brief statement from the Prime Minister’s Office.
The statement shared by the PM Office said the meeting focused on receiving the report and discussing its findings, but did not disclose details of the content or outcomes of the discussion.
The meeting comes exactly one year after Lt. Gen. Tadesse was appointed on April 8, 2025, to lead the interim administration in the Tigray Region, replacing Getachew Reda. Prior to his appointment, Tadesse served as deputy president of the interim administration and head of its cabinet secretariat for peace and security.........
https://www.facebook.com/AddisstandardEng/posts/pfbid026T2zp6KVZ5rdVCzYZ2etaSMRY3C9WWRNS9efDwjLTJFpQoVASVTBXr7Xn4nfbWudl
#Ethiopia: Preparedness is vital’: #Tigray President warns against ‘living in defeat’ at Emperor Yohannes IV commemoration
During the 137th anniversary of the martyrdom of #Emperor_Yohannes IV, Lieutenant General #Tadesse Wereda, President of the Interim Administration of Tigray, delivered a sobering address, emphasizing that while peace remains the priority, the region must remain prepared for any eventuality.
The President acknowledged that this year’s remembrance comes at a precarious time. He described the current atmosphere not as one of comfort, but as one defined by "heavy political tension."
"We are carefully nurturing the relative peace we have in our hands," President Tadesse stated. "However, there are circumstances where forces beyond your capacity emerge, forcing you to make decisions you would not otherwise choose."
In a pointed message regarding the region's security & political stance, the President underscored that peaceful options must......
Read more: https://addisstandard.com/?p=55799
#Ethiopia: Interim President says dialogue under #Pretoria Agreement remains possible as #Tigray forces withdraw from Tselemti
Tigray advanced forces have withdrawn from #Tselemti in what the Tigray Interim Administration described as a confidence-building measure aimed at demonstrating readiness for dialogue and a peaceful resolution to the current tensions, Interim President Lt. General #Tadesse said.
“Our withdrawal shows clearly that we have no desire to return to war,” General Tadesse said, adding that “there is no question that can be answered by war, but by peace and negotiation.”
Speaking on Saturday to Tigrai Television, he stressed that the situation does not have to escalate into full-scale conflict, emphasizing that dialogue remains both possible and preferable.
The Interim President said Tigray’s core demands remain unchanged, centering on the return of internally displaced persons (#IDPs) and the restoration .....
Read more: https://addisstandard.com/?p=54888