Отдельно разберём TaskGroup, который пришел на замену gather в Python 3.11.
Ключевые отличия
▫️create_task() возвращает объект asyncio.Task, у которого есть соответствюущие методы управления. То есть у нас больше контроля
▫️это контекстный менеджер, который гарантирует что все таски будут остановлены по выходу из контекста
▫️ошибка автоматически отменяет незавершенные задачи,
▫️except* передает нам ExceptionGroup, в котором каждую ошибку можно обработать отдельно
import asyncio
import random
async def do_it() -> str:
if random.random() < 0.1:
raise ValueError('Oops')
delay = random.uniform(0.5, 1.5)
await asyncio.sleep(delay)
return delay
async def main():
try:
async with asyncio.TaskGroup() as tg:
for _ in range(10):
tasks.append(tg.create_task(do_it()))
for t in tasks:
print(t.result())
except *ValueError as e:
for err in e.exceptions:
print(err)
asyncio.run(main())
Рекомендую изучить страницу Coroutines and Tasks из документации, где представлено больше интересных примеров и механизмов
- таймауты
- отмена задач
- создание задач из другого потока
#async
‘I told them it isn’t for me, but they didn’t believe me. They kept beating me. They fed me very poorly.’
This Indian girl was held as a sex slave for a year. She left home to get some money for her brothers to get an education, but it ended badly for her. In India, these kinds of stories are common. Children are often kidnapped and sold into slavery.
Today is International Missing Children’s Day, that’s why we want to show you this poor Indian girl’s story. Watch the clip to know what horror she has gone through.
Find more stories like this in the documentary Lost Kids.
#children#slavery
Follow: https://t.me/rtdocumentary
🖊🗞OPINION | The Revolution Will Not Be Terrorized
Andreína Chávez traces a chilling line from the Zong Massacre to the US military terror now unfolding in Caribbean waters.
UN officials have classified recent US bombings in Caribbean and Eastern Pacific waters as “extrajudicial killings,” with more than 80 people killed since September. Victims were from Venezuela, Colombia, and Trinidad and Tobago.
Washington’s accusations tying Venezuela to major drug trafficking contradict UNODC and DEA findings, which confirm the country does not produce drugs and plays an insignificant role as a transit route.
Read the full VA opinion piece here 👉🏾https://shorturl.at/6Gxhm
#Slavery#USImperialism#USMilitaryThreats#Venezuelanhistory
Один из самых успешных работорговцев в истории, кому тем не менее установлены памятники в Африке. Португалец, давший начало африканскому роду. Проходимец, ставший побратимом короля Дагомеи. Католик, похороненный с почестями в виде человеческих жертвоприношений. Белый пращур, вошедший в пантеон вуду – Франсиску Фелиз ди Соза (1754–1849).
У него были десятки жен и сотни детей, и его клан поныне пользуется большим влиянием в Того и Бенине. Вокруг клана также консолидируются потомки бразильских рабов, вернувшихся на родину после отмены рабовладения – включая тех, кого Соза продал. Для этих людей он не злодей и не угнетатель, а покровитель, фигура престижа и силы, предок-лидер. На фото – потомки Франсиску и патриарх рода Чача VIII.
Эта история ставит интересные вопросы перед теорией деколонизации, идеологическая линия которой (плод западной Академии) может не соответствовать запутанным человеческим связям и локальным мировоззрениям. Больше информации тут (на французском).
#Benin#Brazil#Africa#slavery
Solomon Northup was a free Black man who was kidnapped and sold into slavery for 12 years. He was freed on January 4, 1853. He wrote a book called Twelve Years a Slave about his life as a slave. His story helps people understand what slavery was like. 📚✊🏾
[Read more]
@googlefactss
#SolomonNorthup#Slavery#History#TwelveYearsASlave#Freedom