Introduction
Python 3.15 has arrived with its share of impressive new features, but amidst the headlines, some subtleties deserve a closer look. These enhancements, while subtle, can significantly impact your day-to-day coding practices.
TaskGroup Cancellations in Asyncio
With Python 3.15, asyncio introduces a key feature: the ability to cancel a TaskGroup gracefully. Prior to this version, managing interruptions in a TaskGroup required complex gymnastics with custom exceptions. Now, it's as simple as:
``python async with asyncio.TaskGroup() as tg: tg.create_task(run()) tg.create_task(run()) if await wait_for_signal(): tg.cancel() ``
This simplicity reduces error risk and facilitates asynchronous task management.
Context Manager Improvements
Context managers are now more versatile. Did you know they can also be used as decorators? This simplifies execution time measurement:
``python @contextmanager def duration(message: str) -> Iterator[None]: start = time.perf_counter() try: yield finally: print(f"{message} elapsed {time.perf_counter() - start:.2f} seconds") ``
This function can now be directly applied to asynchronous functions, which was not possible before.
Asynchronous Exception Handling
Another subtle improvement involves handling exceptions in asynchronous functions, which has become more intuitive. This allows for better code structuring and reduces potential bugs.
Conclusion
Python 3.15 offers us tools that are not only powerful but also practical for developers. These small features, often overshadowed by major announcements, can significantly improve your productivity. To learn more and integrate these new features into your projects, let's discuss your project in 15 minutes.