Skip to content

Commit c84c942

Browse files
committed
Add type hints to HTTPX
1 parent 1ddba1b commit c84c942

File tree

2 files changed

+55
-60
lines changed
  • instrumentation/opentelemetry-instrumentation-httpx/src/opentelemetry/instrumentation/httpx

2 files changed

+55
-60
lines changed

instrumentation/opentelemetry-instrumentation-httpx/src/opentelemetry/instrumentation/httpx/__init__.py

Lines changed: 55 additions & 60 deletions
Original file line numberDiff line numberDiff line change
@@ -230,7 +230,7 @@ async def async_response_hook(span, request, response):
230230
NETWORK_PEER_ADDRESS,
231231
NETWORK_PEER_PORT,
232232
)
233-
from opentelemetry.trace import SpanKind, TracerProvider, get_tracer
233+
from opentelemetry.trace import SpanKind, Tracer, TracerProvider, get_tracer
234234
from opentelemetry.trace.span import Span
235235
from opentelemetry.trace.status import StatusCode
236236
from opentelemetry.util.http import remove_url_credentials, sanitize_method
@@ -253,17 +253,15 @@ class RequestInfo(typing.NamedTuple):
253253
method: bytes
254254
url: httpx.URL
255255
headers: httpx.Headers | None
256-
stream: typing.Optional[
257-
typing.Union[httpx.SyncByteStream, httpx.AsyncByteStream]
258-
]
259-
extensions: typing.Optional[dict]
256+
stream: httpx.SyncByteStream | httpx.AsyncByteStream | None
257+
extensions: dict[str, typing.Any] | None
260258

261259

262260
class ResponseInfo(typing.NamedTuple):
263261
status_code: int
264262
headers: httpx.Headers | None
265263
stream: typing.Iterable[bytes]
266-
extensions: typing.Optional[dict]
264+
extensions: dict[str, typing.Any] | None
267265

268266

269267
def _get_default_span_name(method: str) -> str:
@@ -274,11 +272,13 @@ def _get_default_span_name(method: str) -> str:
274272
return method
275273

276274

277-
def _prepare_headers(headers: typing.Optional[Headers]) -> httpx.Headers:
275+
def _prepare_headers(headers: Headers | None) -> httpx.Headers:
278276
return httpx.Headers(headers)
279277

280278

281-
def _extract_parameters(args, kwargs):
279+
def _extract_parameters(
280+
args: tuple[typing.Any, ...], kwargs: dict[str, typing.Any]
281+
):
282282
if isinstance(args[0], httpx.Request):
283283
# In httpx >= 0.20.0, handle_request receives a Request object
284284
request: httpx.Request = args[0]
@@ -311,10 +311,9 @@ def _inject_propagation_headers(headers, args, kwargs):
311311

312312

313313
def _extract_response(
314-
response: typing.Union[
315-
httpx.Response, typing.Tuple[int, Headers, httpx.SyncByteStream, dict]
316-
],
317-
) -> typing.Tuple[int, Headers, httpx.SyncByteStream, dict, str]:
314+
response: httpx.Response
315+
| tuple[int, Headers, httpx.SyncByteStream, dict[str, typing.Any]],
316+
) -> tuple[int, Headers, httpx.SyncByteStream, dict[str, typing.Any], str]:
318317
if isinstance(response, httpx.Response):
319318
status_code = response.status_code
320319
headers = response.headers
@@ -331,7 +330,7 @@ def _extract_response(
331330

332331

333332
def _apply_request_client_attributes_to_span(
334-
span_attributes: dict,
333+
span_attributes: dict[str, typing.Any],
335334
url: typing.Union[str, URL, httpx.URL],
336335
method_original: str,
337336
semconv: _StabilityMode,
@@ -407,9 +406,9 @@ class SyncOpenTelemetryTransport(httpx.BaseTransport):
407406
def __init__(
408407
self,
409408
transport: httpx.BaseTransport,
410-
tracer_provider: typing.Optional[TracerProvider] = None,
411-
request_hook: typing.Optional[RequestHook] = None,
412-
response_hook: typing.Optional[ResponseHook] = None,
409+
tracer_provider: TracerProvider | None = None,
410+
request_hook: RequestHook | None = None,
411+
response_hook: ResponseHook | None = None,
413412
):
414413
_OpenTelemetrySemanticConventionStability._initialize()
415414
self._sem_conv_opt_in_mode = _OpenTelemetrySemanticConventionStability._get_opentelemetry_stability_opt_in_mode(
@@ -426,27 +425,27 @@ def __init__(
426425
self._request_hook = request_hook
427426
self._response_hook = response_hook
428427

429-
def __enter__(self) -> "SyncOpenTelemetryTransport":
428+
def __enter__(self) -> SyncOpenTelemetryTransport:
430429
self._transport.__enter__()
431430
return self
432431

433432
def __exit__(
434433
self,
435-
exc_type: typing.Optional[typing.Type[BaseException]] = None,
436-
exc_value: typing.Optional[BaseException] = None,
437-
traceback: typing.Optional[TracebackType] = None,
434+
exc_type: type[BaseException] | None = None,
435+
exc_value: BaseException | None = None,
436+
traceback: TracebackType | None = None,
438437
) -> None:
439438
self._transport.__exit__(exc_type, exc_value, traceback)
440439

441440
# pylint: disable=R0914
442441
def handle_request(
443442
self,
444-
*args,
445-
**kwargs,
446-
) -> typing.Union[
447-
typing.Tuple[int, "Headers", httpx.SyncByteStream, dict],
448-
httpx.Response,
449-
]:
443+
*args: typing.Any,
444+
**kwargs: typing.Any,
445+
) -> (
446+
tuple[int, Headers, httpx.SyncByteStream, dict[str, typing.Any]]
447+
| httpx.Response
448+
):
450449
"""Add request info to span."""
451450
if not is_http_instrumentation_enabled():
452451
return self._transport.handle_request(*args, **kwargs)
@@ -565,11 +564,13 @@ async def __aexit__(
565564

566565
# pylint: disable=R0914
567566
async def handle_async_request(
568-
self, *args, **kwargs
569-
) -> typing.Union[
570-
typing.Tuple[int, "Headers", httpx.AsyncByteStream, dict],
571-
httpx.Response,
572-
]:
567+
self, *args: typing.Any, **kwargs: typing.Any
568+
) -> (
569+
typing.Tuple[
570+
int, Headers, httpx.AsyncByteStream, dict[str, typing.Any]
571+
]
572+
| httpx.Response
573+
):
573574
"""Add request info to span."""
574575
if not is_http_instrumentation_enabled():
575576
return await self._transport.handle_async_request(*args, **kwargs)
@@ -653,7 +654,7 @@ class HTTPXClientInstrumentor(BaseInstrumentor):
653654
def instrumentation_dependencies(self) -> typing.Collection[str]:
654655
return _instruments
655656

656-
def _instrument(self, **kwargs):
657+
def _instrument(self, **kwargs: typing.Any):
657658
"""Instruments httpx Client and AsyncClient
658659
659660
Args:
@@ -716,20 +717,20 @@ def _instrument(self, **kwargs):
716717
),
717718
)
718719

719-
def _uninstrument(self, **kwargs):
720+
def _uninstrument(self, **kwargs: typing.Any):
720721
unwrap(httpx.HTTPTransport, "handle_request")
721722
unwrap(httpx.AsyncHTTPTransport, "handle_async_request")
722723

723724
@staticmethod
724725
def _handle_request_wrapper( # pylint: disable=too-many-locals
725-
wrapped,
726-
instance,
727-
args,
728-
kwargs,
729-
tracer,
730-
sem_conv_opt_in_mode,
731-
request_hook,
732-
response_hook,
726+
wrapped: typing.Callable[..., typing.Any],
727+
instance: httpx.HTTPTransport,
728+
args: tuple[typing.Any, ...],
729+
kwargs: dict[str, typing.Any],
730+
tracer: Tracer,
731+
sem_conv_opt_in_mode: _HTTPStabilityMode,
732+
request_hook: RequestHook,
733+
response_hook: ResponseHook,
733734
):
734735
if not is_http_instrumentation_enabled():
735736
return wrapped(*args, **kwargs)
@@ -796,14 +797,14 @@ def _handle_request_wrapper( # pylint: disable=too-many-locals
796797

797798
@staticmethod
798799
async def _handle_async_request_wrapper( # pylint: disable=too-many-locals
799-
wrapped,
800-
instance,
801-
args,
802-
kwargs,
803-
tracer,
804-
sem_conv_opt_in_mode,
805-
async_request_hook,
806-
async_response_hook,
800+
wrapped: typing.Callable[..., typing.Awaitable[typing.Any]],
801+
instance: httpx.AsyncHTTPTransport,
802+
args: tuple[typing.Any, ...],
803+
kwargs: dict[str, typing.Any],
804+
tracer: Tracer,
805+
sem_conv_opt_in_mode: _HTTPStabilityMode,
806+
async_request_hook: AsyncRequestHook,
807+
async_response_hook: AsyncResponseHook,
807808
):
808809
if not is_http_instrumentation_enabled():
809810
return await wrapped(*args, **kwargs)
@@ -872,14 +873,10 @@ async def _handle_async_request_wrapper( # pylint: disable=too-many-locals
872873
@classmethod
873874
def instrument_client(
874875
cls,
875-
client: typing.Union[httpx.Client, httpx.AsyncClient],
876-
tracer_provider: TracerProvider = None,
877-
request_hook: typing.Union[
878-
typing.Optional[RequestHook], typing.Optional[AsyncRequestHook]
879-
] = None,
880-
response_hook: typing.Union[
881-
typing.Optional[ResponseHook], typing.Optional[AsyncResponseHook]
882-
] = None,
876+
client: httpx.Client | httpx.AsyncClient,
877+
tracer_provider: TracerProvider | None = None,
878+
request_hook: RequestHook | AsyncRequestHook | None = None,
879+
response_hook: ResponseHook | AsyncResponseHook | None = None,
883880
) -> None:
884881
"""Instrument httpx Client or AsyncClient
885882
@@ -977,9 +974,7 @@ def instrument_client(
977974
client._is_instrumented_by_opentelemetry = True
978975

979976
@staticmethod
980-
def uninstrument_client(
981-
client: typing.Union[httpx.Client, httpx.AsyncClient],
982-
):
977+
def uninstrument_client(client: httpx.Client | httpx.AsyncClient) -> None:
983978
"""Disables instrumentation for the given client instance
984979
985980
Args:

instrumentation/opentelemetry-instrumentation-httpx/src/opentelemetry/instrumentation/httpx/py.typed

Whitespace-only changes.

0 commit comments

Comments
 (0)