1# Copyright The OpenTelemetry Authors
2# SPDX-License-Identifier: Apache-2.0
3
4from __future__ import annotations
5
6from contextvars import ContextVar, Token
7
8from opentelemetry.context.context import Context, _RuntimeContext
9
10
11class ContextVarsRuntimeContext(_RuntimeContext):
12 """An implementation of the RuntimeContext interface which wraps ContextVar under
13 the hood. This is the preferred implementation for usage with Python 3.5+
14 """
15
16 _CONTEXT_KEY = "current_context"
17
18 def __init__(self) -> None:
19 self._current_context = ContextVar(self._CONTEXT_KEY, default=Context())
20
21 def attach(self, context: Context) -> Token[Context]:
22 """Sets the current `Context` object. Returns a
23 token that can be used to reset to the previous `Context`.
24
25 Args:
26 context: The Context to set.
27 """
28 return self._current_context.set(context)
29
30 def get_current(self) -> Context:
31 """Returns the current `Context` object."""
32 return self._current_context.get()
33
34 def detach(self, token: Token[Context]) -> None:
35 """Resets Context to a previous value
36
37 Args:
38 token: A reference to a previous Context.
39 """
40 self._current_context.reset(token)
41
42
43__all__ = ["ContextVarsRuntimeContext"]