Skip to content

Commit 4d0f3cc

Browse files
author
The TensorFlow Datasets Authors
committed
Use contextvars instead of threading.local for error context.
PiperOrigin-RevId: 648309870
1 parent 9f7dbed commit 4d0f3cc

File tree

1 file changed

+11
-5
lines changed

1 file changed

+11
-5
lines changed

tensorflow_datasets/core/utils/error_utils.py

Lines changed: 11 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -17,9 +17,9 @@
1717

1818
import contextlib
1919
import dataclasses
20-
import threading
2120
from typing import Callable, Iterator, List, Type, Union
2221

22+
from etils import edc
2323
from tensorflow_datasets.core import utils
2424

2525
Message = Union[str, Callable[[], str]]
@@ -38,7 +38,13 @@ class ErrorContext:
3838

3939

4040
# Current error context. Accessed by `reraise_with_context` and `add_context`.
41-
context_holder = threading.local()
41+
@edc.dataclass
42+
@dataclasses.dataclass
43+
class ContextHolder:
44+
current_context_msg: edc.ContextVar[ErrorContext | None] = None
45+
46+
47+
context_holder = ContextHolder()
4248

4349

4450
@contextlib.contextmanager
@@ -53,7 +59,7 @@ def reraise_with_context(error_cls: Type[Exception]) -> Iterator[None]:
5359
"""
5460
# If current_context_msg exists, we are already within the scope of the
5561
# session contextmanager.
56-
if hasattr(context_holder, 'current_context_msg'):
62+
if context_holder.current_context_msg is not None:
5763
yield
5864
return
5965

@@ -64,7 +70,7 @@ def reraise_with_context(error_cls: Type[Exception]) -> Iterator[None]:
6470
context_msg = '\n'.join(context_holder.current_context_msg.messages)
6571
utils.reraise(e, suffix=context_msg)
6672
finally:
67-
del context_holder.current_context_msg
73+
context_holder.current_context_msg = None
6874

6975

7076
def add_context(msg: str) -> None:
@@ -79,7 +85,7 @@ def add_context(msg: str) -> None:
7985
Raises:
8086
AttributeError if local thread has no current_context_msg attribute.
8187
"""
82-
if not hasattr(context_holder, 'current_context_msg'):
88+
if context_holder.current_context_msg is None:
8389
raise AttributeError(
8490
'add_context called outside of reraise_with_context contextmanager.'
8591
)

0 commit comments

Comments
 (0)