Mocking Trio's open_nursery and spawn with asyncio.TaskGroup

Show how to mock Trio's nursery pattern using Python's asyncio.TaskGroup to simulate task spawning and completion.

Medium Python 3.11+ Aug 9, 2026 Concurrency & performance 14 views 0 copies

Python code

20 lines
Python 3.11+
import asyncio

class MockSpawner:
    async def spawn(self, nursery):
        print("Spawning mock task...")
        await asyncio.sleep(1)
        print("Mock task completed")

async def open_nursery():
    async with asyncio.TaskGroup() as nursery:
        mock = MockSpawner()
        nursery.create_task(mock.spawn(nursery))
    print("Nursery closed")

async def main():
    print("Opening nursery")
    await open_nursery()

if __name__ == "__main__":
    asyncio.run(main())

Output

stdout
Opening nursery
Spawning mock task...
Mock task completed
Nursery closed

How it works

Used asyncio.TaskGroup (Python 3.11+) as a stand-in for Trio's trio.open_nursery context manager. create_task schedules a coroutine concurrently inside the task group. The async context manager waits for all tasks to finish before exiting, mirroring Trio's cancellation semantics. The mock spawner logs its progress to simulate real async work.

Common mistakes

  • Forgetting to await the coroutine inside `create_task` (passing coroutine directly is fine, but not awaiting later).
  • Not using `async with` for TaskGroup, causing tasks to be cancelled or not awaited.
  • Assuming Trio's nursery functions work directly with asyncio; you must translate to `asyncio.TaskGroup`.

Variations

  1. Use `asyncio.gather` inside a plain async function instead of TaskGroup.
  2. Keep Trio imports and use `trio.open_nursery` if the actual runtime is Trio, not asyncio.

Real-world use cases

  • Testing async code that expects nursery semantics by replacing Trio with asyncio for unit tests.
  • Porting a Trio-based concurrency pattern to a standard asyncio application.
  • Simulating task orchestration in a test suite without installing third-party async libraries.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Concurrency & performance

Related tutorials and quizzes for this topic.