contextvars_context.py 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. # Copyright The OpenTelemetry Authors
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. from __future__ import annotations
  15. from contextvars import ContextVar, Token
  16. from opentelemetry.context.context import Context, _RuntimeContext
  17. class ContextVarsRuntimeContext(_RuntimeContext):
  18. """An implementation of the RuntimeContext interface which wraps ContextVar under
  19. the hood. This is the preferred implementation for usage with Python 3.5+
  20. """
  21. _CONTEXT_KEY = "current_context"
  22. def __init__(self) -> None:
  23. self._current_context = ContextVar(
  24. self._CONTEXT_KEY, default=Context()
  25. )
  26. def attach(self, context: Context) -> Token[Context]:
  27. """Sets the current `Context` object. Returns a
  28. token that can be used to reset to the previous `Context`.
  29. Args:
  30. context: The Context to set.
  31. """
  32. return self._current_context.set(context)
  33. def get_current(self) -> Context:
  34. """Returns the current `Context` object."""
  35. return self._current_context.get()
  36. def detach(self, token: Token[Context]) -> None:
  37. """Resets Context to a previous value
  38. Args:
  39. token: A reference to a previous Context.
  40. """
  41. self._current_context.reset(token)
  42. __all__ = ["ContextVarsRuntimeContext"]