Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[WIP] Add typing information for contexts, token #4346

Draft
wants to merge 4 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

## Unreleased

- Add type annotations to context's attach & detach
([#4164](https://github.com/open-telemetry/opentelemetry-python/pull/4346))
- Fix crash exporting a log record with None body
([#4276](https://github.com/open-telemetry/opentelemetry-python/pull/4276))
- Fix metrics export with exemplar and no context and filtering observable instruments
Expand Down
5 changes: 3 additions & 2 deletions opentelemetry-api/src/opentelemetry/context/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@

import logging
import typing
from contextvars import Token
from os import environ
from uuid import uuid4

Expand Down Expand Up @@ -128,7 +129,7 @@ def get_current() -> Context:
return _RUNTIME_CONTEXT.get_current()


def attach(context: Context) -> object:
def attach(context: Context) -> Token[Context]:
"""Associates a Context with the caller's current execution unit. Returns
a token that can be used to restore the previous Context.

Expand All @@ -141,7 +142,7 @@ def attach(context: Context) -> object:
return _RUNTIME_CONTEXT.attach(context)


def detach(token: object) -> None:
def detach(token: Token[Context]) -> None:
"""Resets the Context associated with the caller's current execution unit
to the value it had before attaching a specified Context.

Expand Down
5 changes: 3 additions & 2 deletions opentelemetry-api/src/opentelemetry/context/context.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@

import typing
from abc import ABC, abstractmethod
from contextvars import Token


class Context(typing.Dict[str, object]):
Expand All @@ -29,7 +30,7 @@ class _RuntimeContext(ABC):
"""

@abstractmethod
def attach(self, context: Context) -> object:
def attach(self, context: Context) -> Token[Context]:
"""Sets the current `Context` object. Returns a
token that can be used to reset to the previous `Context`.

Expand All @@ -42,7 +43,7 @@ def get_current(self) -> Context:
"""Returns the current `Context` object."""

@abstractmethod
def detach(self, token: object) -> None:
def detach(self, token: Token[Context]) -> None:
"""Resets Context to a previous value

Args:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from contextvars import ContextVar
from contextvars import ContextVar, Token

from opentelemetry.context.context import Context, _RuntimeContext

Expand All @@ -28,7 +28,7 @@ def __init__(self) -> None:
self._CONTEXT_KEY, default=Context()
)

def attach(self, context: Context) -> object:
def attach(self, context: Context) -> Token[Context]:
"""Sets the current `Context` object. Returns a
token that can be used to reset to the previous `Context`.

Expand All @@ -41,13 +41,13 @@ def get_current(self) -> Context:
"""Returns the current `Context` object."""
return self._current_context.get()

def detach(self, token: object) -> None:
def detach(self, token: Token[Context]) -> None:
"""Resets Context to a previous value

Args:
token: A reference to a previous Context.
"""
self._current_context.reset(token) # type: ignore
self._current_context.reset(token)


__all__ = ["ContextVarsRuntimeContext"]
2 changes: 1 addition & 1 deletion opentelemetry-api/tests/context/base_context.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ def test_attach(self):
self.assertEqual("yyy", context.get_value("a"))

with self.assertLogs(level=ERROR):
context.detach("some garbage")
context.detach("some garbage") # type:ignore
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why is the type: ignore needed?

Suggested change
context.detach("some garbage") # type:ignore
context.detach("some garbage") # type: ignore[?]


def test_detach_out_of_order(self):
t1 = context.attach(context.set_value("c", 1))
Expand Down