[파이썬] `sys.set_coroutine_origin_tracking_depth()`: 코루틴 원점 추적 깊이 설정

Python 3.10 introduced a new feature called coroutine origin tracking, which allows you to trace the origins of coroutines in your code. This feature can be really helpful when debugging complex asynchronous programs. In this blog post, we will focus on sys.set_coroutine_origin_tracking_depth(), a function that lets you configure the depth of coroutine origin tracking.

Understanding Coroutine Origin Tracking

Coroutines are a type of functions in Python that can be paused and resumed, allowing for asynchronous programming. When an exception occurs inside a coroutine, it can be difficult to trace the origin of the exception as it might have been raised from a different coroutine.

Coroutine origin tracking helps in identifying the exact location where an exception was raised by keeping track of the coroutine stack. By enabling coroutine origin tracking, you can get more accurate and detailed information about exceptions, making it easier to debug your code.

Using sys.set_coroutine_origin_tracking_depth()

To configure the depth of coroutine origin tracking, you can use the sys.set_coroutine_origin_tracking_depth() function. This function allows you to set the maximum number of frames to be recorded when tracking coroutine origins.

Here is the syntax of sys.set_coroutine_origin_tracking_depth():

import sys

sys.set_coroutine_origin_tracking_depth(depth: int)

The depth parameter specifies the maximum number of frames to be recorded in the coroutine stack trace. Setting a higher depth value will provide more detailed information but might have a performance impact.

By default, the depth is set to 0, which disables coroutine origin tracking. You can set the depth to a positive integer to enable tracking.

Example Usage

Let’s see an example of how to use sys.set_coroutine_origin_tracking_depth() in Python 3.10:

import sys

async def coroutine_a():
    await coroutine_b()

async def coroutine_b():
    await coroutine_c()

async def coroutine_c():
    raise ValueError("Something went wrong!")

sys.set_coroutine_origin_tracking_depth(3)

try:
    asyncio.run(coroutine_a())
except ValueError as e:
    traceback.print_tb(e.__traceback__)

In the above example, we have three coroutines, coroutine_a, coroutine_b, and coroutine_c. We raise a ValueError in coroutine_c to simulate an exception.

By setting the coroutine origin tracking depth to 3, we can trace the exception back to the three coroutine frames and get a detailed traceback.

Conclusion

Configuring the coroutine origin tracking depth using sys.set_coroutine_origin_tracking_depth() can be really useful when debugging complex asynchronous Python code. It allows you to get more detailed information about exceptions raised inside coroutines, making it easier to identify and fix issues.

Make sure to experiment with different depth values to balance the level of detail you need with the performance impact.