diff --git a/scripts/build_aws_lambda_layer.py b/scripts/build_aws_lambda_layer.py index a7e2397546..faace9e50e 100644 --- a/scripts/build_aws_lambda_layer.py +++ b/scripts/build_aws_lambda_layer.py @@ -3,12 +3,10 @@ import subprocess import sys import tempfile -from typing import TYPE_CHECKING +from typing import Optional from sentry_sdk.consts import VERSION as SDK_VERSION -if TYPE_CHECKING: - from typing import Optional DIST_PATH = "dist" # created by "make dist" that is called by "make aws-lambda-layer" PYTHON_SITE_PACKAGES = "python" # see https://docs.aws.amazon.com/lambda/latest/dg/configuration-layers.html#configuration-layers-path @@ -17,10 +15,9 @@ class LayerBuilder: def __init__( self, - base_dir, # type: str - out_zip_filename=None, # type: Optional[str] - ): - # type: (...) -> None + base_dir: str, + out_zip_filename: Optional[str] = None, + ) -> None: self.base_dir = base_dir self.python_site_packages = os.path.join(self.base_dir, PYTHON_SITE_PACKAGES) self.out_zip_filename = ( @@ -29,12 +26,10 @@ def __init__( else out_zip_filename ) - def make_directories(self): - # type: (...) -> None + def make_directories(self) -> None: os.makedirs(self.python_site_packages) - def install_python_packages(self): - # type: (...) -> None + def install_python_packages(self) -> None: # Install requirements for Lambda Layer (these are more limited than the SDK requirements, # because Lambda does not support the newest versions of some packages) subprocess.check_call( @@ -68,8 +63,7 @@ def install_python_packages(self): check=True, ) - def create_init_serverless_sdk_package(self): - # type: (...) -> None + def create_init_serverless_sdk_package(self) -> None: """ Method that creates the init_serverless_sdk pkg in the sentry-python-serverless zip @@ -84,8 +78,7 @@ def create_init_serverless_sdk_package(self): "scripts/init_serverless_sdk.py", f"{serverless_sdk_path}/__init__.py" ) - def zip(self): - # type: (...) -> None + def zip(self) -> None: subprocess.run( [ "zip", diff --git a/scripts/init_serverless_sdk.py b/scripts/init_serverless_sdk.py index d58605ff6f..341d8d6832 100644 --- a/scripts/init_serverless_sdk.py +++ b/scripts/init_serverless_sdk.py @@ -9,15 +9,11 @@ import os import sys import re +from typing import Any import sentry_sdk from sentry_sdk.integrations.aws_lambda import AwsLambdaIntegration -from typing import TYPE_CHECKING - -if TYPE_CHECKING: - from typing import Any - # Configure Sentry SDK sentry_sdk.init( @@ -70,8 +66,7 @@ def get_lambda_handler(self): return getattr(self.lambda_function_module, self.handler_name) -def sentry_lambda_handler(event, context): - # type: (Any, Any) -> None +def sentry_lambda_handler(event: Any, context: Any) -> None: """ Handler function that invokes a lambda handler which path is defined in environment variables as "SENTRY_INITIAL_HANDLER" diff --git a/sentry_sdk/api.py b/sentry_sdk/api.py index 2050119d4a..089e569dfa 100644 --- a/sentry_sdk/api.py +++ b/sentry_sdk/api.py @@ -339,6 +339,5 @@ def end_session() -> None: @scopemethod -def set_transaction_name(name, source=None): - # type: (str, Optional[str]) -> None +def set_transaction_name(name: str, source: Optional[str] = None) -> None: return get_current_scope().set_transaction_name(name, source) diff --git a/sentry_sdk/integrations/django/__init__.py b/sentry_sdk/integrations/django/__init__.py index 004adee7ff..8895d3924e 100644 --- a/sentry_sdk/integrations/django/__init__.py +++ b/sentry_sdk/integrations/django/__init__.py @@ -712,8 +712,7 @@ def _set_db_data(span: Span, cursor_or_db: Any) -> None: span.set_attribute(SPANDATA.SERVER_SOCKET_ADDRESS, server_socket_address) -def add_template_context_repr_sequence(): - # type: () -> None +def add_template_context_repr_sequence() -> None: try: from django.template.context import BaseContext diff --git a/sentry_sdk/serializer.py b/sentry_sdk/serializer.py index a4a54e757a..1ab83ba293 100644 --- a/sentry_sdk/serializer.py +++ b/sentry_sdk/serializer.py @@ -53,11 +53,10 @@ def add_global_repr_processor(processor: ReprProcessor) -> None: global_repr_processors.append(processor) -sequence_types = [Sequence, Set] # type: List[type] +sequence_types: list[type] = [Sequence, Set] -def add_repr_sequence_type(ty): - # type: (type) -> None +def add_repr_sequence_type(ty: type) -> None: sequence_types.append(ty) diff --git a/sentry_sdk/utils.py b/sentry_sdk/utils.py index 3a44b25578..8ce150c848 100644 --- a/sentry_sdk/utils.py +++ b/sentry_sdk/utils.py @@ -1875,12 +1875,12 @@ def set_thread_info_from_span( data[SPANDATA.THREAD_NAME] = span.get_attribute(SPANDATA.THREAD_NAME) -def safe_serialize(data): - # type: (Any) -> str +def safe_serialize(data: Any) -> str: """Safely serialize to a readable string.""" - def serialize_item(item): - # type: (Any) -> Union[str, dict[Any, Any], list[Any], tuple[Any, ...]] + def serialize_item( + item: Any, + ) -> Union[str, dict[Any, Any], list[Any], tuple[Any, ...]]: if callable(item): try: module = getattr(item, "__module__", None) diff --git a/tests/integrations/chalice/test_chalice.py b/tests/integrations/chalice/test_chalice.py index fbd4be4e59..27dcd431ce 100644 --- a/tests/integrations/chalice/test_chalice.py +++ b/tests/integrations/chalice/test_chalice.py @@ -10,11 +10,10 @@ from pytest_chalice.handlers import RequestHandler -def _generate_lambda_context(self): +def _generate_lambda_context(self) -> LambdaContext: # Monkeypatch of the function _generate_lambda_context # from the class LocalGateway # for mock the timeout - # type: () -> LambdaContext if self._config.lambda_timeout is None: timeout = 10 * 1000 else: diff --git a/tests/integrations/django/test_middleware.py b/tests/integrations/django/test_middleware.py index 2a8d94f623..6e5c1e76be 100644 --- a/tests/integrations/django/test_middleware.py +++ b/tests/integrations/django/test_middleware.py @@ -5,8 +5,7 @@ from sentry_sdk.integrations.django.middleware import _wrap_middleware -def _sync_capable_middleware_factory(sync_capable): - # type: (Optional[bool]) -> type +def _sync_capable_middleware_factory(sync_capable: Optional[bool]) -> type: """Create a middleware class with a sync_capable attribute set to the value passed to the factory. If the factory is called with None, the middleware class will not have a sync_capable attribute. """ diff --git a/tests/integrations/langchain/test_langchain.py b/tests/integrations/langchain/test_langchain.py index 1ffc4a3228..93118fef88 100644 --- a/tests/integrations/langchain/test_langchain.py +++ b/tests/integrations/langchain/test_langchain.py @@ -34,8 +34,8 @@ def get_word_length(word: str) -> int: return len(word) -global stream_result_mock # type: Mock -global llm_type # type: str +stream_result_mock: Mock +llm_type: str class MockOpenAI(ChatOpenAI): diff --git a/tests/integrations/sanic/test_sanic.py b/tests/integrations/sanic/test_sanic.py index 05b23cb215..0244e0f329 100644 --- a/tests/integrations/sanic/test_sanic.py +++ b/tests/integrations/sanic/test_sanic.py @@ -3,6 +3,7 @@ import os import random import sys +from typing import Any, Iterable, Optional, Container from unittest.mock import Mock import pytest @@ -26,11 +27,6 @@ except ImportError: ReusableClient = None -from typing import TYPE_CHECKING - -if TYPE_CHECKING: - from collections.abc import Iterable, Container - from typing import Any, Optional SANIC_VERSION = tuple(map(int, SANIC_VERSION_RAW.split("."))) PERFORMANCE_SUPPORTED = SANIC_VERSION >= (21, 9) @@ -341,14 +337,13 @@ class TransactionTestConfig: def __init__( self, - integration_args, - url, - expected_status, - expected_transaction_name, - expected_source=None, - has_transaction_event=True, - ): - # type: (Iterable[Optional[Container[int]]], str, int, Optional[str], Optional[str], bool) -> None + integration_args: Iterable[Optional[Container[int]]], + url: str, + expected_status: int, + expected_transaction_name: Optional[str], + expected_source: Optional[str] = None, + has_transaction_event: bool = True, + ) -> None: """ expected_transaction_name of None indicates we expect to not receive a transaction """ @@ -408,8 +403,9 @@ def __init__( ), ], ) -def test_transactions(test_config, sentry_init, app, capture_events): - # type: (TransactionTestConfig, Any, Any, Any) -> None +def test_transactions( + test_config: TransactionTestConfig, sentry_init: Any, app: Any, capture_events: Any +) -> None: # Init the SanicIntegration with the desired arguments sentry_init( diff --git a/tests/profiler/test_transaction_profiler.py b/tests/profiler/test_transaction_profiler.py index 97836d59d9..0dc4e82af5 100644 --- a/tests/profiler/test_transaction_profiler.py +++ b/tests/profiler/test_transaction_profiler.py @@ -623,16 +623,13 @@ def test_max_profile_duration_reached(scheduler_class): class NoopScheduler(Scheduler): - def setup(self): - # type: () -> None + def setup(self) -> None: pass - def teardown(self): - # type: () -> None + def teardown(self) -> None: pass - def ensure_running(self): - # type: () -> None + def ensure_running(self) -> None: pass diff --git a/tests/test_basics.py b/tests/test_basics.py index 17a0e218ad..7872fb7e7b 100644 --- a/tests/test_basics.py +++ b/tests/test_basics.py @@ -42,10 +42,10 @@ class NoOpIntegration(Integration): identifier = "noop" @staticmethod - def setup_once(): # type: () -> None + def setup_once() -> None: pass - def __eq__(self, __value): # type: (object) -> bool + def __eq__(self, __value: object) -> bool: """ All instances of NoOpIntegration should be considered equal to each other. """ diff --git a/tests/test_client.py b/tests/test_client.py index 5350450d95..b69a6a0f3f 100644 --- a/tests/test_client.py +++ b/tests/test_client.py @@ -5,9 +5,9 @@ import sys import time from collections import Counter, defaultdict -from collections.abc import Mapping from textwrap import dedent from unittest import mock +from typing import Optional, Union, Mapping, Callable import pytest @@ -26,13 +26,7 @@ from sentry_sdk.transport import Transport from sentry_sdk.serializer import MAX_DATABAG_BREADTH from sentry_sdk.consts import DEFAULT_MAX_BREADCRUMBS, DEFAULT_MAX_VALUE_LENGTH - -from typing import TYPE_CHECKING - -if TYPE_CHECKING: - from collections.abc import Callable - from typing import Any, Optional, Union - from sentry_sdk._types import Event +from sentry_sdk.types import Event maximum_python_312 = pytest.mark.skipif( @@ -1135,12 +1129,11 @@ def test_spotlight_option( class IssuesSamplerTestConfig: def __init__( self, - expected_events, - sampler_function=None, - sample_rate=None, - exception_to_raise=Exception, - ): - # type: (int, Optional[Callable[[Event], Union[float, bool]]], Optional[float], type[Exception]) -> None + expected_events: int, + sampler_function: Optional[Callable[[Event], Union[float, bool]]] = None, + sample_rate: Optional[float] = None, + exception_to_raise: type = Exception, + ) -> None: self.sampler_function_mock = ( None if sampler_function is None @@ -1150,14 +1143,12 @@ def __init__( self.sample_rate = sample_rate self.exception_to_raise = exception_to_raise - def init_sdk(self, sentry_init): - # type: (Callable[[*Any], None]) -> None + def init_sdk(self, sentry_init: Callable[..., None]) -> None: sentry_init( error_sampler=self.sampler_function_mock, sample_rate=self.sample_rate ) - def raise_exception(self): - # type: () -> None + def raise_exception(self) -> None: raise self.exception_to_raise() diff --git a/tests/test_logs.py b/tests/test_logs.py index 0147279695..337783bb6f 100644 --- a/tests/test_logs.py +++ b/tests/test_logs.py @@ -17,10 +17,8 @@ ) -def otel_attributes_to_dict(otel_attrs): - # type: (Mapping[str, Any]) -> Mapping[str, Any] - def _convert_attr(attr): - # type: (Mapping[str, Union[str, float, bool]]) -> Any +def otel_attributes_to_dict(otel_attrs: Mapping[str, Any]) -> Mapping[str, Any]: + def _convert_attr(attr: Mapping[str, Union[str, float, bool]]) -> Any: if attr["type"] == "boolean": return attr["value"] if attr["type"] == "double": @@ -38,7 +36,7 @@ def _convert_attr(attr): def envelopes_to_logs(envelopes: List[Envelope]) -> List[Log]: - res = [] # type: List[Log] + res: List[Log] = [] for envelope in envelopes: for item in envelope.items: if item.type == "log": @@ -54,7 +52,7 @@ def envelopes_to_logs(envelopes: List[Envelope]) -> List[Log]: "attributes": otel_attributes_to_dict(log_json["attributes"]), "time_unix_nano": int(float(log_json["timestamp"]) * 1e9), "trace_id": log_json["trace_id"], - } # type: Log + } res.append(log) return res diff --git a/tests/test_tracing_utils.py b/tests/test_tracing_utils.py index 2b2c62a6f9..70a7d0ed4c 100644 --- a/tests/test_tracing_utils.py +++ b/tests/test_tracing_utils.py @@ -5,8 +5,7 @@ import pytest -def id_function(val): - # type: (object) -> str +def id_function(val: object) -> str: if isinstance(val, ShouldBeIncludedTestCase): return val.id @@ -88,8 +87,9 @@ class ShouldBeIncludedTestCase: ], ids=id_function, ) -def test_should_be_included(test_case, expected): - # type: (ShouldBeIncludedTestCase, bool) -> None +def test_should_be_included( + test_case: ShouldBeIncludedTestCase, expected: bool +) -> None: """Checking logic, see: https://github.com/getsentry/sentry-python/issues/3312""" kwargs = asdict(test_case) kwargs.pop("id") diff --git a/tests/test_transport.py b/tests/test_transport.py index 7e0cc6383c..300251fc0c 100644 --- a/tests/test_transport.py +++ b/tests/test_transport.py @@ -61,8 +61,7 @@ def inner(**kwargs): return inner -def mock_transaction_envelope(span_count): - # type: (int) -> Envelope +def mock_transaction_envelope(span_count: int) -> Envelope: event = defaultdict( mock.MagicMock, type="transaction", diff --git a/tests/test_utils.py b/tests/test_utils.py index af943f1e7e..fb63ccb517 100644 --- a/tests/test_utils.py +++ b/tests/test_utils.py @@ -54,8 +54,7 @@ class TestIntegration(Integration): gevent = None -def _normalize_distribution_name(name): - # type: (str) -> str +def _normalize_distribution_name(name: str) -> str: """Normalize distribution name according to PEP-0503. See: