Skip to content

Commit d0487f0

Browse files
committed
use context manager @pcrespov @sanderegg
1 parent d9db140 commit d0487f0

File tree

2 files changed

+19
-19
lines changed

2 files changed

+19
-19
lines changed

packages/service-library/src/servicelib/async_utils.py

Lines changed: 11 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -164,19 +164,17 @@ async def worker(in_q: Queue[QueueElement], out_q: Queue) -> None:
164164
while True:
165165
element = await in_q.get()
166166
in_q.task_done()
167-
tracing.attach_context(element.tracing_context)
168-
# check if requested to shutdown
169-
try:
170-
do_profile = element.do_profile
171-
awaitable = element.input
172-
if awaitable is None:
173-
break
174-
with profile_context(do_profile):
175-
result = await awaitable
176-
except Exception as e: # pylint: disable=broad-except
177-
result = e
178-
finally:
179-
tracing.detach_context(element.tracing_context)
167+
with tracing.use_tracing_context(element.tracing_context):
168+
# check if requested to shutdown
169+
try:
170+
do_profile = element.do_profile
171+
awaitable = element.input
172+
if awaitable is None:
173+
break
174+
with profile_context(do_profile):
175+
result = await awaitable
176+
except Exception as e: # pylint: disable=broad-except
177+
result = e
180178
await out_q.put(result)
181179

182180
logging.info(

packages/service-library/src/servicelib/tracing.py

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
from contextlib import contextmanager
12
from typing import TypeAlias
23

34
from opentelemetry import context as otcontext
@@ -18,14 +19,15 @@ def get_context() -> TracingContext:
1819
return otcontext.get_current()
1920

2021

21-
def attach_context(context: TracingContext) -> None:
22+
@contextmanager
23+
def use_tracing_context(context: TracingContext):
2224
if context is not None:
2325
otcontext.attach(context)
24-
25-
26-
def detach_context(context: TracingContext) -> None:
27-
if context is not None:
28-
otcontext.detach(context)
26+
try:
27+
yield
28+
finally:
29+
if context is not None:
30+
otcontext.detach(context)
2931

3032

3133
def setup_log_tracing(tracing_settings: TracingSettings):

0 commit comments

Comments
 (0)