Skip to content

Commit b61622d

Browse files
mrnicegyu11hyoinandoutlzchenxrmxemdneto
authored
Add typing information for contexts, token (#4346)
* Handle TypeError from opentelemetry.context.contextvars_context in detach * Add type annotations * In changelog update PR number * remove unnecessary type:ignore * fix tox -e mypy tests * Apply suggestions from code review Co-authored-by: Emídio Neto <[email protected]> * Apply suggestions from code review Co-authored-by: Emídio Neto <[email protected]> * Update conf.py * Update docs/conf.py * Update docs/conf.py --------- Co-authored-by: hyoinandout <[email protected]> Co-authored-by: Leighton Chen <[email protected]> Co-authored-by: Riccardo Magliocchetti <[email protected]> Co-authored-by: Emídio Neto <[email protected]>
1 parent 8e3c7d2 commit b61622d

File tree

6 files changed

+24
-9
lines changed

6 files changed

+24
-9
lines changed

CHANGELOG.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
77

88
## Unreleased
99

10+
- Add type annotations to context's attach & detach
11+
([#4346](https://github.com/open-telemetry/opentelemetry-python/pull/4346))
1012
- Fix OTLP encoders missing instrumentation scope schema url and attributes
1113
([#4359](https://github.com/open-telemetry/opentelemetry-python/pull/4359))
1214
- prometheus-exporter: fix labels out of place for data points with different

docs/conf.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -150,6 +150,10 @@
150150
"py:class",
151151
"opentelemetry.sdk.metrics._internal.aggregation._Aggregation",
152152
),
153+
(
154+
"py:class",
155+
"_contextvars.Token",
156+
),
153157
]
154158

155159
# Add any paths that contain templates here, relative to this directory.

opentelemetry-api/src/opentelemetry/context/__init__.py

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,8 +12,11 @@
1212
# See the License for the specific language governing permissions and
1313
# limitations under the License.
1414

15+
from __future__ import annotations
16+
1517
import logging
1618
import typing
19+
from contextvars import Token
1720
from os import environ
1821
from uuid import uuid4
1922

@@ -128,7 +131,7 @@ def get_current() -> Context:
128131
return _RUNTIME_CONTEXT.get_current()
129132

130133

131-
def attach(context: Context) -> object:
134+
def attach(context: Context) -> Token[Context]:
132135
"""Associates a Context with the caller's current execution unit. Returns
133136
a token that can be used to restore the previous Context.
134137
@@ -141,7 +144,7 @@ def attach(context: Context) -> object:
141144
return _RUNTIME_CONTEXT.attach(context)
142145

143146

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

opentelemetry-api/src/opentelemetry/context/context.py

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,8 +12,11 @@
1212
# See the License for the specific language governing permissions and
1313
# limitations under the License.
1414

15+
from __future__ import annotations
16+
1517
import typing
1618
from abc import ABC, abstractmethod
19+
from contextvars import Token
1720

1821

1922
class Context(typing.Dict[str, object]):
@@ -29,7 +32,7 @@ class _RuntimeContext(ABC):
2932
"""
3033

3134
@abstractmethod
32-
def attach(self, context: Context) -> object:
35+
def attach(self, context: Context) -> Token[Context]:
3336
"""Sets the current `Context` object. Returns a
3437
token that can be used to reset to the previous `Context`.
3538
@@ -42,7 +45,7 @@ def get_current(self) -> Context:
4245
"""Returns the current `Context` object."""
4346

4447
@abstractmethod
45-
def detach(self, token: object) -> None:
48+
def detach(self, token: Token[Context]) -> None:
4649
"""Resets Context to a previous value
4750
4851
Args:

opentelemetry-api/src/opentelemetry/context/contextvars_context.py

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,10 @@
1111
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1212
# See the License for the specific language governing permissions and
1313
# limitations under the License.
14-
from contextvars import ContextVar
14+
15+
from __future__ import annotations
16+
17+
from contextvars import ContextVar, Token
1518

1619
from opentelemetry.context.context import Context, _RuntimeContext
1720

@@ -28,7 +31,7 @@ def __init__(self) -> None:
2831
self._CONTEXT_KEY, default=Context()
2932
)
3033

31-
def attach(self, context: Context) -> object:
34+
def attach(self, context: Context) -> Token[Context]:
3235
"""Sets the current `Context` object. Returns a
3336
token that can be used to reset to the previous `Context`.
3437
@@ -41,13 +44,13 @@ def get_current(self) -> Context:
4144
"""Returns the current `Context` object."""
4245
return self._current_context.get()
4346

44-
def detach(self, token: object) -> None:
47+
def detach(self, token: Token[Context]) -> None:
4548
"""Resets Context to a previous value
4649
4750
Args:
4851
token: A reference to a previous Context.
4952
"""
50-
self._current_context.reset(token) # type: ignore
53+
self._current_context.reset(token)
5154

5255

5356
__all__ = ["ContextVarsRuntimeContext"]

opentelemetry-api/tests/context/base_context.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -64,7 +64,7 @@ def test_attach(self):
6464
self.assertEqual("yyy", context.get_value("a"))
6565

6666
with self.assertLogs(level=ERROR):
67-
context.detach("some garbage")
67+
context.detach(token)
6868

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

0 commit comments

Comments
 (0)