Skip to content

Commit

Permalink
Replace TaskGroup with list and gather for python<3.11 compatab…
Browse files Browse the repository at this point in the history
…ility.
  • Loading branch information
MaPePeR committed Jun 7, 2023
1 parent 2813b50 commit 6d3d073
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 15 deletions.
6 changes: 3 additions & 3 deletions docs/source/rabbitmq-tutorial/7-publisher-confirms.rst
Original file line number Diff line number Diff line change
Expand Up @@ -121,10 +121,10 @@ The broker confirms published messages asynchronously, our helper function will

.. literalinclude:: examples/7-publisher-confirms/publish_asynchronously.py
:language: python
:start-at: with asyncio.TaskGroup
:end-at: asyncio.sleep(0)
:start-at: # List for storing tasks
:end-at: await asyncio.gather(*tasks)
The :code:`TaskGroup` is required to ensure that all tasks are awaited properly.
In Python 3.11 a :code:`TaskGroup` can be used instead of the :code:`list` with :code:`asyncio.gather`.

The helper function publishes the message and awaits the confirmation.
This way the helper function knows which message the confirmation, timeout or rejection belongs to.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,19 +37,23 @@ async def main() -> None:
# Declaring queue
queue = await channel.declare_queue("hello")

async with asyncio.TaskGroup() as tg:
# Sending the messages
for msg in get_messages_to_publish():
tg.create_task(
publish_and_handle_confirm(
channel.default_exchange,
queue.name,
msg,
)
# List for storing tasks
tasks = []
# Sending the messages
for msg in get_messages_to_publish():
task = asyncio.create_task(
publish_and_handle_confirm(
channel.default_exchange,
queue.name,
msg,
)
# Yield control flow to event loop,
# so message sending is initiated:
await asyncio.sleep(0)
)
tasks.append(task)
# Yield control flow to event loop, so message sending is initiated:
await asyncio.sleep(0)

# Await all tasks
await asyncio.gather(*tasks)

print(" [x] Sent and confirmed multiple messages asynchronously. ")

Expand Down

0 comments on commit 6d3d073

Please sign in to comment.