context.py 1.7 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. import typing
  16. from abc import ABC, abstractmethod
  17. from contextvars import Token
  18. class Context(typing.Dict[str, object]):
  19. def __setitem__(self, key: str, value: object) -> None:
  20. raise ValueError
  21. class _RuntimeContext(ABC):
  22. """The RuntimeContext interface provides a wrapper for the different
  23. mechanisms that are used to propagate context in Python.
  24. Implementations can be made available via entry_points and
  25. selected through environment variables.
  26. """
  27. @abstractmethod
  28. def attach(self, context: Context) -> Token[Context]:
  29. """Sets the current `Context` object. Returns a
  30. token that can be used to reset to the previous `Context`.
  31. Args:
  32. context: The Context to set.
  33. """
  34. @abstractmethod
  35. def get_current(self) -> Context:
  36. """Returns the current `Context` object."""
  37. @abstractmethod
  38. def detach(self, token: Token[Context]) -> None:
  39. """Resets Context to a previous value
  40. Args:
  41. token: A reference to a previous Context.
  42. """
  43. __all__ = ["Context"]