contextvars_context.py 1.3 KB

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