Skip to content
Merged
1 change: 1 addition & 0 deletions .changelog/5277.changed
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Remove typing aliases deprecated in python 3.9 and replace all usages of `typing.Union` and `typing.Optional` with `|`.
Original file line number Diff line number Diff line change
Expand Up @@ -879,8 +879,8 @@ def _get_field_type_hint(
if field_desc.label == descriptor.FieldDescriptorProto.LABEL_REPEATED:
return f"builtins.list[{base_type}]"
if field_desc.type == descriptor.FieldDescriptorProto.TYPE_ENUM:
return f"typing.Union[{base_type}, builtins.int, None]"
return f"typing.Optional[{base_type}]"
return f"{base_type} | builtins.int | None"
return f"{base_type} | None"

def _resolve_message_type(self, type_name: str, proto_file: str) -> str:
"""
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@

import abc
import base64
import collections.abc
import json
import math
import typing
Expand Down Expand Up @@ -101,7 +102,7 @@ def encode_float(value: float) -> float | str:

def encode_repeated(
values: list[T] | None,
map_fn: typing.Callable[[T], typing.Any],
map_fn: collections.abc.Callable[[T], typing.Any],
) -> list[typing.Any]:
"""
Helper to serialize repeated fields with a mapping function.
Expand Down Expand Up @@ -207,7 +208,7 @@ def decode_float(value: float | int | str | None, field_name: str) -> float:

def decode_repeated(
values: list[typing.Any] | None,
item_parser: typing.Callable[[typing.Any], T],
item_parser: collections.abc.Callable[[typing.Any], T],
field_name: str,
) -> list[T]:
"""
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,6 @@
NewType,
Optional,
TypeVar,
Union,
)
from urllib.parse import urlparse

Expand Down
10 changes: 6 additions & 4 deletions opentelemetry-api/src/opentelemetry/_events/__init__.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
# Copyright The OpenTelemetry Authors
# SPDX-License-Identifier: Apache-2.0

from __future__ import annotations

from abc import ABC, abstractmethod
from logging import getLogger
from os import environ
from typing import Optional, cast
from typing import cast

from typing_extensions import deprecated

Expand Down Expand Up @@ -32,7 +34,7 @@ def __init__(
timestamp: int | None = None,
trace_id: int | None = None,
span_id: int | None = None,
trace_flags: Optional["TraceFlags"] = None,
trace_flags: TraceFlags | None = None,
body: AnyValue | None = None,
severity_number: SeverityNumber | None = None,
attributes: _ExtendedAttributes | None = None,
Expand Down Expand Up @@ -72,7 +74,7 @@ def __init__(
self._attributes = attributes

@abstractmethod
def emit(self, event: "Event") -> None:
def emit(self, event: Event) -> None:
"""Emits a :class:`Event` representing an event."""


Expand Down Expand Up @@ -244,7 +246,7 @@ def get_event_logger(
schema_url: str | None = None,
attributes: _ExtendedAttributes | None = None,
event_logger_provider: EventLoggerProvider | None = None,
) -> "EventLogger":
) -> EventLogger:
if event_logger_provider is None:
event_logger_provider = get_event_logger_provider()
return event_logger_provider.get_event_logger(
Expand Down
11 changes: 4 additions & 7 deletions opentelemetry-api/src/opentelemetry/propagators/_envcarrier.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,7 @@

import os
import re
import typing
from collections.abc import MutableMapping
from collections.abc import Mapping, MutableMapping

from opentelemetry.propagators.textmap import Getter, Setter

Expand All @@ -16,7 +15,7 @@ def _normalize_key(key: str) -> str:
return result


class EnvironmentGetter(Getter[typing.Mapping[str, str]]):
class EnvironmentGetter(Getter[Mapping[str, str]]):
"""Getter implementation for extracting context and baggage from environment variables.

EnvironmentGetter creates a normalized lookup from the current environment
Expand All @@ -39,9 +38,7 @@ def __init__(self):
_normalize_key(k): v for k, v in os.environ.items()
}

def get(
self, carrier: typing.Mapping[str, str], key: str
) -> list[str] | None:
def get(self, carrier: Mapping[str, str], key: str) -> list[str] | None:
"""Get a value from the environment carrier for the given key.

Args:
Expand All @@ -56,7 +53,7 @@ def get(
return None
return [val]

def keys(self, carrier: typing.Mapping[str, str]) -> list[str]:
def keys(self, carrier: Mapping[str, str]) -> list[str]:
"""Get all keys from the environment carrier.

Args:
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
# Copyright The OpenTelemetry Authors
# SPDX-License-Identifier: Apache-2.0
import collections.abc
import logging
import typing

from typing_extensions import deprecated

Expand All @@ -20,7 +20,7 @@ class CompositePropagator(textmap.TextMapPropagator):
"""

def __init__(
self, propagators: typing.Sequence[textmap.TextMapPropagator]
self, propagators: collections.abc.Sequence[textmap.TextMapPropagator]
) -> None:
self._propagators = propagators

Expand Down
13 changes: 7 additions & 6 deletions opentelemetry-api/src/opentelemetry/propagators/textmap.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@

import abc
import typing
from collections.abc import Iterable, Mapping, MutableMapping

from opentelemetry.context.context import Context

Expand Down Expand Up @@ -59,9 +60,9 @@ def set(self, carrier: CarrierT, key: str, value: str) -> None:
"""


class DefaultGetter(Getter[typing.Mapping[str, CarrierValT]]):
class DefaultGetter(Getter[Mapping[str, CarrierValT]]):
def get(
self, carrier: typing.Mapping[str, CarrierValT], key: str
self, carrier: Mapping[str, CarrierValT], key: str
) -> list[str] | None:
"""Getter implementation to retrieve a value from a dictionary.

Expand All @@ -74,22 +75,22 @@ def get(
val = carrier.get(key, None)
if val is None:
return None
if isinstance(val, typing.Iterable) and not isinstance(val, str):
if isinstance(val, Iterable) and not isinstance(val, str):
return list(val)
return [val]

def keys(self, carrier: typing.Mapping[str, CarrierValT]) -> list[str]:
def keys(self, carrier: Mapping[str, CarrierValT]) -> list[str]:
"""Keys implementation that returns all keys from a dictionary."""
return list(carrier.keys())


default_getter: Getter[CarrierT] = DefaultGetter() # type: ignore


class DefaultSetter(Setter[typing.MutableMapping[str, CarrierValT]]):
class DefaultSetter(Setter[MutableMapping[str, CarrierValT]]):
def set(
self,
carrier: typing.MutableMapping[str, CarrierValT],
carrier: MutableMapping[str, CarrierValT],
key: str,
value: CarrierValT,
) -> None:
Expand Down
49 changes: 26 additions & 23 deletions opentelemetry-api/src/opentelemetry/trace/span.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,15 @@
# Copyright The OpenTelemetry Authors
# SPDX-License-Identifier: Apache-2.0

from __future__ import annotations

import abc
import logging
import re
import types as python_types
import typing
import warnings
from collections.abc import Iterator, Mapping, Sequence

from opentelemetry.trace.status import Status, StatusCode
from opentelemetry.util import types
Expand Down Expand Up @@ -70,7 +73,7 @@ def end(self, end_time: int | None = None) -> None:
"""

@abc.abstractmethod
def get_span_context(self) -> "SpanContext":
def get_span_context(self) -> SpanContext:
"""Gets the span's SpanContext.

Get an immutable, serializable identifier for this span that can be
Expand All @@ -82,7 +85,7 @@ def get_span_context(self) -> "SpanContext":

@abc.abstractmethod
def set_attributes(
self, attributes: typing.Mapping[str, types.AttributeValue]
self, attributes: Mapping[str, types.AttributeValue]
) -> None:
"""Sets Attributes.

Expand Down Expand Up @@ -122,7 +125,7 @@ def add_event(

def add_link( # pylint: disable=no-self-use
self,
context: "SpanContext",
context: SpanContext,
attributes: types.Attributes = None,
) -> None:
"""Adds a `Link`.
Expand Down Expand Up @@ -179,7 +182,7 @@ def record_exception(
) -> None:
"""Records an exception as a span event."""

def __enter__(self) -> "Span":
def __enter__(self) -> Span:
"""Invoked when `Span` is used as a context manager.

Returns the `Span` itself.
Expand Down Expand Up @@ -217,7 +220,7 @@ class TraceFlags(int):
RANDOM_TRACE_ID = 0x02

@classmethod
def get_default(cls) -> "TraceFlags":
def get_default(cls) -> TraceFlags:
return cls(cls.DEFAULT)

@property
Expand All @@ -232,7 +235,7 @@ def random_trace_id(self) -> bool:
DEFAULT_TRACE_OPTIONS = TraceFlags.get_default()


class TraceState(typing.Mapping[str, str]):
class TraceState(Mapping[str, str]):
"""A list of key-value pairs representing vendor-specific trace info.

Keys and values are strings of up to 256 printable US-ASCII characters.
Expand All @@ -245,7 +248,7 @@ class TraceState(typing.Mapping[str, str]):

def __init__(
self,
entries: typing.Sequence[tuple[str, str]] | None = None,
entries: Sequence[tuple[str, str]] | None = None,
) -> None:
self._dict = {} # type: dict[str, str]
if entries is None:
Expand Down Expand Up @@ -274,7 +277,7 @@ def __contains__(self, item: object) -> bool:
def __getitem__(self, key: str) -> str:
return self._dict[key]

def __iter__(self) -> typing.Iterator[str]:
def __iter__(self) -> Iterator[str]:
return iter(self._dict)

def __len__(self) -> int:
Expand All @@ -287,7 +290,7 @@ def __repr__(self) -> str:
]
return str(pairs)

def add(self, key: str, value: str) -> "TraceState":
def add(self, key: str, value: str) -> TraceState:
"""Adds a key-value pair to tracestate. The provided pair should
adhere to w3c tracestate identifiers format.

Expand Down Expand Up @@ -318,7 +321,7 @@ def add(self, key: str, value: str) -> "TraceState":
new_state = [(key, value)] + list(self._dict.items())
return TraceState(new_state)

def update(self, key: str, value: str) -> "TraceState":
def update(self, key: str, value: str) -> TraceState:
"""Updates a key-value pair in tracestate. The provided pair should
adhere to w3c tracestate identifiers format.

Expand All @@ -343,7 +346,7 @@ def update(self, key: str, value: str) -> "TraceState":
new_state = [(key, value), *prev_state.items()]
return TraceState(new_state)

def delete(self, key: str) -> "TraceState":
def delete(self, key: str) -> TraceState:
"""Deletes a key-value from tracestate.

Args:
Expand Down Expand Up @@ -374,7 +377,7 @@ def to_header(self) -> str:
return ",".join(key + "=" + value for key, value in self._dict.items())

@classmethod
def from_header(cls, header_list: list[str]) -> "TraceState":
def from_header(cls, header_list: list[str]) -> TraceState:
"""Parses one or more w3c tracestate header into a TraceState.

Args:
Expand Down Expand Up @@ -413,7 +416,7 @@ def from_header(cls, header_list: list[str]) -> "TraceState":
return cls(list(pairs.items()))

@classmethod
def get_default(cls) -> "TraceState":
def get_default(cls) -> TraceState:
return cls()

def keys(self) -> typing.KeysView[str]:
Expand Down Expand Up @@ -450,9 +453,9 @@ def __new__(
trace_id: int,
span_id: int,
is_remote: bool,
trace_flags: typing.Optional["TraceFlags"] = DEFAULT_TRACE_OPTIONS,
trace_state: typing.Optional["TraceState"] = DEFAULT_TRACE_STATE,
) -> "SpanContext":
trace_flags: TraceFlags | None = DEFAULT_TRACE_OPTIONS,
trace_state: TraceState | None = DEFAULT_TRACE_STATE,
) -> SpanContext:
if trace_flags is None:
trace_flags = DEFAULT_TRACE_OPTIONS
if trace_state is None:
Expand All @@ -470,7 +473,7 @@ def __new__(

def __getnewargs__(
self,
) -> tuple[int, int, bool, "TraceFlags", "TraceState"]:
) -> tuple[int, int, bool, TraceFlags, TraceState]:
return (
self.trace_id,
self.span_id,
Expand All @@ -492,11 +495,11 @@ def is_remote(self) -> bool:
return self[2] # pylint: disable=unsubscriptable-object

@property
def trace_flags(self) -> "TraceFlags":
def trace_flags(self) -> TraceFlags:
return self[3] # pylint: disable=unsubscriptable-object

@property
def trace_state(self) -> "TraceState":
def trace_state(self) -> TraceState:
return self[4] # pylint: disable=unsubscriptable-object

@property
Expand All @@ -523,10 +526,10 @@ class NonRecordingSpan(Span):
All operations are no-op except context propagation.
"""

def __init__(self, context: "SpanContext") -> None:
def __init__(self, context: SpanContext) -> None:
self._context = context

def get_span_context(self) -> "SpanContext":
def get_span_context(self) -> SpanContext:
return self._context

def is_recording(self) -> bool:
Expand All @@ -536,7 +539,7 @@ def end(self, end_time: int | None = None) -> None:
pass

def set_attributes(
self, attributes: typing.Mapping[str, types.AttributeValue]
self, attributes: Mapping[str, types.AttributeValue]
) -> None:
pass

Expand All @@ -553,7 +556,7 @@ def add_event(

def add_link(
self,
context: "SpanContext",
context: SpanContext,
attributes: types.Attributes = None,
) -> None:
pass
Expand Down
Loading
Loading