From 2b6997295ea0b6024c29ae32b498565d90b4cee6 Mon Sep 17 00:00:00 2001 From: "sentry-junior[bot]" <264270552+sentry-junior[bot]@users.noreply.github.com> Date: Mon, 16 Nov 2026 09:54:33 +0000 Subject: [PATCH 1/2] ci(ruff): Enable PLC0415 to flag inline imports in the SDK AGENTS.md asks for top-level imports. Existing inline imports get a noqa comment, so a new one has to be marked explicitly. Tests are excluded. Co-Authored-By: Ivana Kellyer <131587164+sentrivana@users.noreply.github.com> --- pyproject.toml | 4 +++ sentry_sdk/_compat.py | 8 ++--- sentry_sdk/client.py | 2 +- sentry_sdk/consts.py | 2 +- sentry_sdk/integrations/__init__.py | 2 +- sentry_sdk/integrations/anthropic.py | 2 +- sentry_sdk/integrations/beam.py | 6 ++-- sentry_sdk/integrations/celery/__init__.py | 6 ++-- sentry_sdk/integrations/celery/beat.py | 2 +- sentry_sdk/integrations/chalice.py | 2 +- sentry_sdk/integrations/django/__init__.py | 34 +++++++++---------- sentry_sdk/integrations/django/asgi.py | 10 +++--- sentry_sdk/integrations/django/caching.py | 8 ++--- sentry_sdk/integrations/django/middleware.py | 4 +-- .../integrations/django/signals_handlers.py | 2 +- sentry_sdk/integrations/django/tasks.py | 2 +- sentry_sdk/integrations/django/templates.py | 6 ++-- sentry_sdk/integrations/django/views.py | 8 ++--- sentry_sdk/integrations/flask.py | 2 +- sentry_sdk/integrations/gcp.py | 2 +- sentry_sdk/integrations/grpc/__init__.py | 2 +- sentry_sdk/integrations/openai.py | 2 +- .../openai_agents/patches/error_tracing.py | 4 +-- .../integrations/pydantic_ai/__init__.py | 2 +- .../integrations/pydantic_ai/patches/tools.py | 4 +-- sentry_sdk/integrations/pydantic_ai/utils.py | 2 +- sentry_sdk/integrations/pyramid.py | 2 +- sentry_sdk/integrations/redis/__init__.py | 2 +- .../integrations/redis/_async_common.py | 4 +-- sentry_sdk/integrations/redis/_sync_common.py | 4 +-- sentry_sdk/integrations/redis/rb.py | 2 +- sentry_sdk/integrations/redis/redis.py | 4 +-- .../integrations/redis/redis_cluster.py | 6 ++-- .../redis/redis_py_cluster_legacy.py | 2 +- sentry_sdk/integrations/spark/spark_driver.py | 10 +++--- sentry_sdk/integrations/spark/spark_worker.py | 6 ++-- sentry_sdk/integrations/starlette.py | 4 +-- sentry_sdk/integrations/threading.py | 4 +-- sentry_sdk/scope.py | 2 +- sentry_sdk/spotlight.py | 2 +- sentry_sdk/traces.py | 4 +-- sentry_sdk/tracing.py | 2 +- sentry_sdk/transport.py | 4 +-- sentry_sdk/utils.py | 20 +++++------ 44 files changed, 109 insertions(+), 105 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index cfac620006..3c9c1fce02 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -301,6 +301,7 @@ select = [ "I", # Note: B and N rules are NOT enabled by default in flake8 # They were only active through the plugins, which may not have been fully enabled + "PLC0415", # Import not at the top level of the file ] # Use ONLY the same ignores as the original flake8 config + compatibility for this codebase @@ -317,6 +318,9 @@ ignore = [ "E721", # Use isinstance instead of type() == - existing pattern in this codebase ] +[tool.ruff.lint.per-file-ignores] +"tests/**" = ["PLC0415"] + [tool.ruff.format] # ruff format already excludes the same files as specified in extend-exclude # Ensure Python 3.7 compatibility - avoid using Python 3.9+ syntax features diff --git a/sentry_sdk/_compat.py b/sentry_sdk/_compat.py index f62175c09f..64dcabddcf 100644 --- a/sentry_sdk/_compat.py +++ b/sentry_sdk/_compat.py @@ -35,11 +35,11 @@ def check_uwsgi_thread_support() -> bool: # --py-call-uwsgi-fork-hooks to force uWSGI to run regular cpython # after-fork hooks that take care of cleaning up stale thread data. try: - from uwsgi import opt # type: ignore + from uwsgi import opt # type: ignore # noqa: PLC0415 except ImportError: return True - from sentry_sdk.consts import FALSE_VALUES + from sentry_sdk.consts import FALSE_VALUES # noqa: PLC0415 def enabled(option: str) -> bool: value = opt.get(option, False) @@ -61,7 +61,7 @@ def enabled(option: str) -> bool: lazy_mode = enabled("lazy-apps") or enabled("lazy") if lazy_mode and not threads_enabled: - from warnings import warn + from warnings import warn # noqa: PLC0415 warn( Warning( @@ -75,7 +75,7 @@ def enabled(option: str) -> bool: return False elif not lazy_mode and (not threads_enabled or not fork_hooks_on): - from warnings import warn + from warnings import warn # noqa: PLC0415 warn( Warning( diff --git a/sentry_sdk/client.py b/sentry_sdk/client.py index 16bb8ac02b..e5e7f53103 100644 --- a/sentry_sdk/client.py +++ b/sentry_sdk/client.py @@ -653,7 +653,7 @@ def _record_lost_event( # Setup Spotlight before creating batchers so _capture_envelope can use it. # setup_spotlight handles all config/env var resolution per the SDK spec. - from sentry_sdk.spotlight import setup_spotlight + from sentry_sdk.spotlight import setup_spotlight # noqa: PLC0415 self.spotlight = setup_spotlight(self.options) if self.spotlight is not None and not self.options["dsn"]: diff --git a/sentry_sdk/consts.py b/sentry_sdk/consts.py index 95decc19bc..05f179e32e 100644 --- a/sentry_sdk/consts.py +++ b/sentry_sdk/consts.py @@ -1912,7 +1912,7 @@ def __init__( def _get_default_options() -> "dict[str, Any]": - import inspect + import inspect # noqa: PLC0415 a = inspect.getfullargspec(ClientConstructor.__init__) defaults = a.defaults or () diff --git a/sentry_sdk/integrations/__init__.py b/sentry_sdk/integrations/__init__.py index e61365cc7f..1b8fdc7fcb 100644 --- a/sentry_sdk/integrations/__init__.py +++ b/sentry_sdk/integrations/__init__.py @@ -30,7 +30,7 @@ def iter_default_integrations( with_auto_enabling_integrations: bool, ) -> "Iterator[Type[Integration]]": """Returns an iterator of the default integration classes:""" - from importlib import import_module + from importlib import import_module # noqa: PLC0415 if with_auto_enabling_integrations: all_import_strings = integrations + auto_enabling_integrations diff --git a/sentry_sdk/integrations/anthropic.py b/sentry_sdk/integrations/anthropic.py index 6af004f209..a7b6f9e512 100644 --- a/sentry_sdk/integrations/anthropic.py +++ b/sentry_sdk/integrations/anthropic.py @@ -281,7 +281,7 @@ def setup_once() -> None: AsyncMessageStream.close = _wrap_async_close(AsyncMessageStream.close) # type: ignore[method-assign] try: - from functools import cached_property + from functools import cached_property # noqa: PLC0415 except ImportError: return diff --git a/sentry_sdk/integrations/beam.py b/sentry_sdk/integrations/beam.py index 31f45f73de..5141cfb231 100644 --- a/sentry_sdk/integrations/beam.py +++ b/sentry_sdk/integrations/beam.py @@ -32,7 +32,7 @@ class BeamIntegration(Integration): @staticmethod def setup_once() -> None: - from apache_beam.transforms.core import DoFn, ParDo # type: ignore + from apache_beam.transforms.core import DoFn, ParDo # type: ignore # noqa: PLC0415 ignore_logger("root") ignore_logger("bundle_processor.create") @@ -94,11 +94,11 @@ def _inspect(self: "Any") -> "Any": # getfullargspec is deprecated in more recent beam versions and get_function_args_defaults # (which uses Signatures internally) should be used instead. try: - from apache_beam.transforms.core import get_function_args_defaults + from apache_beam.transforms.core import get_function_args_defaults # noqa: PLC0415 return get_function_args_defaults(process_func) except ImportError: - from apache_beam.typehints.decorators import getfullargspec # type: ignore + from apache_beam.typehints.decorators import getfullargspec # type: ignore # noqa: PLC0415 return getfullargspec(process_func) diff --git a/sentry_sdk/integrations/celery/__init__.py b/sentry_sdk/integrations/celery/__init__.py index 38c76b67c6..69c5751bea 100644 --- a/sentry_sdk/integrations/celery/__init__.py +++ b/sentry_sdk/integrations/celery/__init__.py @@ -497,7 +497,7 @@ def _inner(*args: "Any", **kwargs: "Any") -> "Any": def _patch_build_tracer() -> None: - import celery.app.trace as trace # type: ignore + import celery.app.trace as trace # type: ignore # noqa: PLC0415 original_build_tracer = trace.build_tracer @@ -527,7 +527,7 @@ def _patch_task_apply_async() -> None: def _patch_celery_send_task() -> None: - from celery import Celery + from celery import Celery # noqa: PLC0415 Celery.send_task = _wrap_task_run(Celery.send_task) @@ -535,7 +535,7 @@ def _patch_celery_send_task() -> None: def _patch_worker_exit() -> None: # Need to flush queue before worker shutdown because a crashing worker will # call os._exit - from billiard.pool import Worker # type: ignore + from billiard.pool import Worker # type: ignore # noqa: PLC0415 original_workloop = Worker.workloop diff --git a/sentry_sdk/integrations/celery/beat.py b/sentry_sdk/integrations/celery/beat.py index fbe3593c87..5bbece4e9d 100644 --- a/sentry_sdk/integrations/celery/beat.py +++ b/sentry_sdk/integrations/celery/beat.py @@ -188,7 +188,7 @@ def _wrap_beat_scheduler( if already_patched: return original_function - from sentry_sdk.integrations.celery import CeleryIntegration + from sentry_sdk.integrations.celery import CeleryIntegration # noqa: PLC0415 def sentry_patched_scheduler(*args: "Any", **kwargs: "Any") -> None: integration = sentry_sdk.get_client().get_integration(CeleryIntegration) diff --git a/sentry_sdk/integrations/chalice.py b/sentry_sdk/integrations/chalice.py index 9baa0e5cdd..16deb0950c 100644 --- a/sentry_sdk/integrations/chalice.py +++ b/sentry_sdk/integrations/chalice.py @@ -163,7 +163,7 @@ def setup_once() -> None: if version < (1, 20): old_get_view_function_response = Chalice._get_view_function_response else: - from chalice.app import RestAPIEventHandler + from chalice.app import RestAPIEventHandler # noqa: PLC0415 old_get_view_function_response = ( RestAPIEventHandler._get_view_function_response diff --git a/sentry_sdk/integrations/django/__init__.py b/sentry_sdk/integrations/django/__init__.py index 294b5b56ff..439f023891 100644 --- a/sentry_sdk/integrations/django/__init__.py +++ b/sentry_sdk/integrations/django/__init__.py @@ -187,7 +187,7 @@ def setup_once() -> None: ignore_logger("django.server") ignore_logger("django.request") - from django.core.handlers.wsgi import WSGIHandler + from django.core.handlers.wsgi import WSGIHandler # noqa: PLC0415 old_app = WSGIHandler.__call__ @@ -197,7 +197,7 @@ def sentry_patched_wsgi_handler( ) -> "_ScopedResponse": bound_old_app = old_app.__get__(self, WSGIHandler) - from django.conf import settings + from django.conf import settings # noqa: PLC0415 use_x_forwarded_for = settings.USE_X_FORWARDED_HOST @@ -280,7 +280,7 @@ def _django_queryset_repr( # If we fail to import, return `NotImplemented`. It's at least # unlikely that we have a query set in `value` when importing # `QuerySet` fails. - from django.db.models.query import QuerySet + from django.db.models.query import QuerySet # noqa: PLC0415 except Exception: return NotImplemented @@ -349,7 +349,7 @@ def _patch_drf() -> None: with capture_internal_exceptions(): try: - from rest_framework.views import APIView # type: ignore + from rest_framework.views import APIView # type: ignore # noqa: PLC0415 except ImportError: pass else: @@ -369,7 +369,7 @@ def sentry_patched_drf_initial( with capture_internal_exceptions(): try: - from rest_framework.request import Request # type: ignore + from rest_framework.request import Request # type: ignore # noqa: PLC0415 except ImportError: pass else: @@ -407,7 +407,7 @@ def sentry_patched_drf_authenticate(self: "Request") -> "Any": def _patch_channels() -> None: try: - from channels.http import AsgiHandler # type: ignore + from channels.http import AsgiHandler # type: ignore # noqa: PLC0415 except ImportError: return @@ -424,14 +424,14 @@ def _patch_channels() -> None: + CONTEXTVARS_ERROR_MESSAGE ) - from sentry_sdk.integrations.django.asgi import patch_channels_asgi_handler_impl + from sentry_sdk.integrations.django.asgi import patch_channels_asgi_handler_impl # noqa: PLC0415 patch_channels_asgi_handler_impl(AsgiHandler) def _patch_django_asgi_handler() -> None: try: - from django.core.handlers.asgi import ASGIHandler + from django.core.handlers.asgi import ASGIHandler # noqa: PLC0415 except ImportError: return @@ -445,7 +445,7 @@ def _patch_django_asgi_handler() -> None: "We detected that you are using Django 3." + CONTEXTVARS_ERROR_MESSAGE ) - from sentry_sdk.integrations.django.asgi import patch_django_asgi_handler_impl + from sentry_sdk.integrations.django.asgi import patch_django_asgi_handler_impl # noqa: PLC0415 patch_django_asgi_handler_impl(ASGIHandler) @@ -623,7 +623,7 @@ def _patch_get_response() -> None: """ patch get_response, because at that point we have the Django request object """ - from django.core.handlers.base import BaseHandler + from django.core.handlers.base import BaseHandler # noqa: PLC0415 old_get_response = BaseHandler.get_response @@ -638,7 +638,7 @@ def sentry_patched_get_response( BaseHandler.get_response = sentry_patched_get_response if hasattr(BaseHandler, "get_response_async"): - from sentry_sdk.integrations.django.asgi import patch_get_response_async + from sentry_sdk.integrations.django.asgi import patch_get_response_async # noqa: PLC0415 patch_get_response_async(BaseHandler, _before_get_response) @@ -725,7 +725,7 @@ def _patch_response_for_exception() -> None: too, along with the status code Django picked for them. """ try: - from django.core.handlers import exception as exception_handler + from django.core.handlers import exception as exception_handler # noqa: PLC0415 except ImportError: # Django < 1.10 does this in `BaseHandler`, nothing to patch here return @@ -839,16 +839,16 @@ def _set_user_info(request: "WSGIRequest", event: "Event") -> None: def install_sql_hook() -> None: """If installed this causes Django's queries to be captured.""" try: - from django.db.backends.utils import CursorWrapper + from django.db.backends.utils import CursorWrapper # noqa: PLC0415 except ImportError: - from django.db.backends.util import CursorWrapper + from django.db.backends.util import CursorWrapper # noqa: PLC0415 try: # django 1.6 and 1.7 compatibility - from django.db.backends import BaseDatabaseWrapper + from django.db.backends import BaseDatabaseWrapper # noqa: PLC0415 except ImportError: # django 1.8 or later - from django.db.backends.base.base import BaseDatabaseWrapper + from django.db.backends.base.base import BaseDatabaseWrapper # noqa: PLC0415 try: real_execute = CursorWrapper.execute @@ -1077,7 +1077,7 @@ def _set_db_data( def add_template_context_repr_sequence() -> None: try: - from django.template.context import BaseContext + from django.template.context import BaseContext # noqa: PLC0415 add_repr_sequence_type(BaseContext) except Exception: diff --git a/sentry_sdk/integrations/django/asgi.py b/sentry_sdk/integrations/django/asgi.py index df287e6436..9816b05334 100644 --- a/sentry_sdk/integrations/django/asgi.py +++ b/sentry_sdk/integrations/django/asgi.py @@ -57,7 +57,7 @@ def asgi_request_event_processor(event: "Event", hint: "dict[str, Any]") -> "Eve # if the request is gone we are fine not logging the data from # it. This might happen if the processor is pushed away to # another thread. - from sentry_sdk.integrations.django import ( + from sentry_sdk.integrations.django import ( # noqa: PLC0415 DjangoRequestExtractor, _set_user_info, ) @@ -86,7 +86,7 @@ def asgi_request_event_processor(event: "Event", hint: "dict[str, Any]") -> "Eve def patch_django_asgi_handler_impl(cls: "Any") -> None: - from sentry_sdk.integrations.django import DjangoIntegration + from sentry_sdk.integrations.django import DjangoIntegration # noqa: PLC0415 old_app = cls.__call__ @@ -138,9 +138,9 @@ async def sentry_patched_get_response_async( def patch_channels_asgi_handler_impl(cls: "Any") -> None: - import channels # type: ignore + import channels # type: ignore # noqa: PLC0415 - from sentry_sdk.integrations.django import DjangoIntegration + from sentry_sdk.integrations.django import DjangoIntegration # noqa: PLC0415 if channels.__version__ < "3.0.0": old_app = cls.__call__ @@ -170,7 +170,7 @@ async def sentry_patched_asgi_handler( def wrap_async_view(callback: "Any") -> "Any": - from sentry_sdk.integrations.django import DjangoIntegration + from sentry_sdk.integrations.django import DjangoIntegration # noqa: PLC0415 @functools.wraps(callback) async def sentry_wrapped_callback( diff --git a/sentry_sdk/integrations/django/caching.py b/sentry_sdk/integrations/django/caching.py index 2cfc0cd2e1..8690bab05b 100644 --- a/sentry_sdk/integrations/django/caching.py +++ b/sentry_sdk/integrations/django/caching.py @@ -38,7 +38,7 @@ def _patch_cache_method( address: "Optional[str]", port: "Optional[int]", ) -> None: - from sentry_sdk.integrations.django import DjangoIntegration + from sentry_sdk.integrations.django import DjangoIntegration # noqa: PLC0415 original_method = getattr(cache, method_name) @@ -213,11 +213,11 @@ def _get_address_port( def should_enable_cache_spans() -> bool: - from sentry_sdk.integrations.django import DjangoIntegration + from sentry_sdk.integrations.django import DjangoIntegration # noqa: PLC0415 client = sentry_sdk.get_client() integration = client.get_integration(DjangoIntegration) - from django.conf import settings + from django.conf import settings # noqa: PLC0415 return integration is not None and ( (client.spotlight is not None and settings.DEBUG is True) @@ -235,7 +235,7 @@ def sentry_get_item(self: "CacheHandler", alias: str) -> "Any": cache = original_get_item(self, alias) if should_enable_cache_spans(): - from django.conf import settings + from django.conf import settings # noqa: PLC0415 address, port = _get_address_port( settings.CACHES[alias or "default"] diff --git a/sentry_sdk/integrations/django/middleware.py b/sentry_sdk/integrations/django/middleware.py index 01ed8962e0..5f18549b10 100644 --- a/sentry_sdk/integrations/django/middleware.py +++ b/sentry_sdk/integrations/django/middleware.py @@ -38,7 +38,7 @@ def patch_django_middlewares() -> None: - from django.core.handlers import base + from django.core.handlers import base # noqa: PLC0415 old_import_string = base.import_string @@ -65,7 +65,7 @@ def sentry_patched_load_middleware(*args: "Any", **kwargs: "Any") -> "Any": def _wrap_middleware(middleware: "Any", middleware_name: str) -> "Any": - from sentry_sdk.integrations.django import DjangoIntegration + from sentry_sdk.integrations.django import DjangoIntegration # noqa: PLC0415 def _check_middleware_span( old_method: "Callable[..., Any]", diff --git a/sentry_sdk/integrations/django/signals_handlers.py b/sentry_sdk/integrations/django/signals_handlers.py index 1df42c47fa..93e155ddbb 100644 --- a/sentry_sdk/integrations/django/signals_handlers.py +++ b/sentry_sdk/integrations/django/signals_handlers.py @@ -44,7 +44,7 @@ def patch_signals() -> None: This only wraps sync receivers. Django>=5.0 introduced async receivers, but since we don't create transactions for ASGI Django, we don't wrap them. """ - from sentry_sdk.integrations.django import DjangoIntegration + from sentry_sdk.integrations.django import DjangoIntegration # noqa: PLC0415 old_live_receivers = Signal._live_receivers diff --git a/sentry_sdk/integrations/django/tasks.py b/sentry_sdk/integrations/django/tasks.py index 303040d042..9b4face45e 100644 --- a/sentry_sdk/integrations/django/tasks.py +++ b/sentry_sdk/integrations/django/tasks.py @@ -25,7 +25,7 @@ def patch_tasks() -> None: @wraps(old_task_enqueue) def _sentry_enqueue(self: "Any", *args: "Any", **kwargs: "Any") -> "Any": - from sentry_sdk.integrations.django import DjangoIntegration + from sentry_sdk.integrations.django import DjangoIntegration # noqa: PLC0415 integration = sentry_sdk.get_client().get_integration(DjangoIntegration) if integration is None: diff --git a/sentry_sdk/integrations/django/templates.py b/sentry_sdk/integrations/django/templates.py index 1c0986dd9e..0f77f3213c 100644 --- a/sentry_sdk/integrations/django/templates.py +++ b/sentry_sdk/integrations/django/templates.py @@ -53,9 +53,9 @@ def _get_template_name_description(template_name: str) -> str: def patch_templates() -> None: - from django.template.response import SimpleTemplateResponse + from django.template.response import SimpleTemplateResponse # noqa: PLC0415 - from sentry_sdk.integrations.django import DjangoIntegration + from sentry_sdk.integrations.django import DjangoIntegration # noqa: PLC0415 real_rendered_content = SimpleTemplateResponse.rendered_content @@ -87,7 +87,7 @@ def rendered_content(self: "SimpleTemplateResponse") -> str: if DJANGO_VERSION < (1, 7): return - import django.shortcuts + import django.shortcuts # noqa: PLC0415 real_render = django.shortcuts.render diff --git a/sentry_sdk/integrations/django/views.py b/sentry_sdk/integrations/django/views.py index d37d54117d..4be88586c6 100644 --- a/sentry_sdk/integrations/django/views.py +++ b/sentry_sdk/integrations/django/views.py @@ -13,10 +13,10 @@ def patch_views() -> None: - from django.core.handlers.base import BaseHandler - from django.template.response import SimpleTemplateResponse + from django.core.handlers.base import BaseHandler # noqa: PLC0415 + from django.template.response import SimpleTemplateResponse # noqa: PLC0415 - from sentry_sdk.integrations.django import DjangoIntegration + from sentry_sdk.integrations.django import DjangoIntegration # noqa: PLC0415 old_make_view_atomic = BaseHandler.make_view_atomic old_render = SimpleTemplateResponse.render @@ -65,7 +65,7 @@ def sentry_patched_make_view_atomic( def _wrap_sync_view(callback: "Any") -> "Any": - from sentry_sdk.integrations.django import DjangoIntegration + from sentry_sdk.integrations.django import DjangoIntegration # noqa: PLC0415 @functools.wraps(callback) def sentry_wrapped_callback(request: "Any", *args: "Any", **kwargs: "Any") -> "Any": diff --git a/sentry_sdk/integrations/flask.py b/sentry_sdk/integrations/flask.py index b99a3b49eb..b3aaa29246 100644 --- a/sentry_sdk/integrations/flask.py +++ b/sentry_sdk/integrations/flask.py @@ -74,7 +74,7 @@ def __init__( @staticmethod def setup_once() -> None: try: - from quart import Quart # type: ignore + from quart import Quart # type: ignore # noqa: PLC0415 if Flask == Quart: # This is Quart masquerading as Flask, don't enable the Flask diff --git a/sentry_sdk/integrations/gcp.py b/sentry_sdk/integrations/gcp.py index c0debc8094..d6feb25017 100644 --- a/sentry_sdk/integrations/gcp.py +++ b/sentry_sdk/integrations/gcp.py @@ -200,7 +200,7 @@ def __init__(self, timeout_warning: bool = False) -> None: @staticmethod def setup_once() -> None: - import __main__ as gcp_functions + import __main__ as gcp_functions # noqa: PLC0415 if not hasattr(gcp_functions, "worker_v1"): logger.warning( diff --git a/sentry_sdk/integrations/grpc/__init__.py b/sentry_sdk/integrations/grpc/__init__.py index bf74ff1351..5e074f0e41 100644 --- a/sentry_sdk/integrations/grpc/__init__.py +++ b/sentry_sdk/integrations/grpc/__init__.py @@ -175,7 +175,7 @@ class GRPCIntegration(Integration): @staticmethod def setup_once() -> None: - import grpc + import grpc # noqa: PLC0415 grpc.insecure_channel = _wrap_channel_sync(grpc.insecure_channel) grpc.secure_channel = _wrap_channel_sync(grpc.secure_channel) diff --git a/sentry_sdk/integrations/openai.py b/sentry_sdk/integrations/openai.py index 04ae33daff..4c30002efa 100644 --- a/sentry_sdk/integrations/openai.py +++ b/sentry_sdk/integrations/openai.py @@ -129,7 +129,7 @@ def __init__( self.tiktoken_encoding = None if tiktoken_encoding_name is not None: - import tiktoken + import tiktoken # noqa: PLC0415 self.tiktoken_encoding = tiktoken.get_encoding(tiktoken_encoding_name) diff --git a/sentry_sdk/integrations/openai_agents/patches/error_tracing.py b/sentry_sdk/integrations/openai_agents/patches/error_tracing.py index 2135ecd753..3716aece8f 100644 --- a/sentry_sdk/integrations/openai_agents/patches/error_tracing.py +++ b/sentry_sdk/integrations/openai_agents/patches/error_tracing.py @@ -24,7 +24,7 @@ def _patch_error_tracing() -> None: # Try newer location first (agents.util._error_tracing) try: - from agents.util import _error_tracing + from agents.util import _error_tracing # noqa: PLC0415 error_tracing_module = _error_tracing except (ImportError, AttributeError): @@ -33,7 +33,7 @@ def _patch_error_tracing() -> None: # Try older location (agents._utils) if error_tracing_module is None: try: - import agents._utils + import agents._utils # noqa: PLC0415 error_tracing_module = agents._utils except (ImportError, AttributeError): diff --git a/sentry_sdk/integrations/pydantic_ai/__init__.py b/sentry_sdk/integrations/pydantic_ai/__init__.py index a3215aa284..8dda4d3e5e 100644 --- a/sentry_sdk/integrations/pydantic_ai/__init__.py +++ b/sentry_sdk/integrations/pydantic_ai/__init__.py @@ -129,7 +129,7 @@ def setup_once() -> None: return try: - from pydantic_ai.capabilities import Hooks + from pydantic_ai.capabilities import Hooks # noqa: PLC0415 except ImportError: return diff --git a/sentry_sdk/integrations/pydantic_ai/patches/tools.py b/sentry_sdk/integrations/pydantic_ai/patches/tools.py index a88e1d5712..c4bde8d1c7 100644 --- a/sentry_sdk/integrations/pydantic_ai/patches/tools.py +++ b/sentry_sdk/integrations/pydantic_ai/patches/tools.py @@ -85,7 +85,7 @@ async def wrapped_execute_tool_call( exc_info = sys.exc_info() with capture_internal_exceptions(): # Avoid circular import due to multi-file integration structure - from sentry_sdk.integrations.pydantic_ai import ( + from sentry_sdk.integrations.pydantic_ai import ( # noqa: PLC0415 PydanticAIIntegration, ) @@ -158,7 +158,7 @@ async def wrapped_call_tool( exc_info = sys.exc_info() with capture_internal_exceptions(): # Avoid circular import due to multi-file integration structure - from sentry_sdk.integrations.pydantic_ai import ( + from sentry_sdk.integrations.pydantic_ai import ( # noqa: PLC0415 PydanticAIIntegration, ) diff --git a/sentry_sdk/integrations/pydantic_ai/utils.py b/sentry_sdk/integrations/pydantic_ai/utils.py index c847c143b5..6a2a8f60bb 100644 --- a/sentry_sdk/integrations/pydantic_ai/utils.py +++ b/sentry_sdk/integrations/pydantic_ai/utils.py @@ -63,7 +63,7 @@ def _should_send_prompts_legacy() -> bool: if not should_send_default_pii(): return False - from . import PydanticAIIntegration + from . import PydanticAIIntegration # noqa: PLC0415 # Get the integration instance from the client integration = sentry_sdk.get_client().get_integration(PydanticAIIntegration) diff --git a/sentry_sdk/integrations/pyramid.py b/sentry_sdk/integrations/pyramid.py index 49f734f52b..d1bc6e81e1 100644 --- a/sentry_sdk/integrations/pyramid.py +++ b/sentry_sdk/integrations/pyramid.py @@ -69,7 +69,7 @@ def __init__(self, transaction_style: str = "route_name") -> None: @staticmethod def setup_once() -> None: - from pyramid import router + from pyramid import router # noqa: PLC0415 old_call_view = router._call_view diff --git a/sentry_sdk/integrations/redis/__init__.py b/sentry_sdk/integrations/redis/__init__.py index 7095721ed2..7f3c06ff37 100644 --- a/sentry_sdk/integrations/redis/__init__.py +++ b/sentry_sdk/integrations/redis/__init__.py @@ -35,7 +35,7 @@ def __init__( @staticmethod def setup_once() -> None: try: - from redis import StrictRedis, client + from redis import StrictRedis, client # noqa: PLC0415 except ImportError: raise DidNotEnable("Redis client not installed") diff --git a/sentry_sdk/integrations/redis/_async_common.py b/sentry_sdk/integrations/redis/_async_common.py index 956fe91154..a121ab9f4a 100644 --- a/sentry_sdk/integrations/redis/_async_common.py +++ b/sentry_sdk/integrations/redis/_async_common.py @@ -38,7 +38,7 @@ def patch_redis_async_pipeline( ) -> None: old_execute = pipeline_cls.execute - from sentry_sdk.integrations.redis import RedisIntegration + from sentry_sdk.integrations.redis import RedisIntegration # noqa: PLC0415 async def _sentry_execute(self: "Any", *args: "Any", **kwargs: "Any") -> "Any": client = sentry_sdk.get_client() @@ -106,7 +106,7 @@ def patch_redis_async_client( ) -> None: old_execute_command = cls.execute_command - from sentry_sdk.integrations.redis import RedisIntegration + from sentry_sdk.integrations.redis import RedisIntegration # noqa: PLC0415 async def _sentry_execute_command( self: "Any", name: str, *args: "Any", **kwargs: "Any" diff --git a/sentry_sdk/integrations/redis/_sync_common.py b/sentry_sdk/integrations/redis/_sync_common.py index fcb1822094..739cbfbb15 100644 --- a/sentry_sdk/integrations/redis/_sync_common.py +++ b/sentry_sdk/integrations/redis/_sync_common.py @@ -35,7 +35,7 @@ def patch_redis_pipeline( ) -> None: old_execute = pipeline_cls.execute - from sentry_sdk.integrations.redis import RedisIntegration + from sentry_sdk.integrations.redis import RedisIntegration # noqa: PLC0415 def sentry_patched_execute(self: "Any", *args: "Any", **kwargs: "Any") -> "Any": client = sentry_sdk.get_client() @@ -104,7 +104,7 @@ def patch_redis_client( """ old_execute_command = cls.execute_command - from sentry_sdk.integrations.redis import RedisIntegration + from sentry_sdk.integrations.redis import RedisIntegration # noqa: PLC0415 def sentry_patched_execute_command( self: "Any", name: str, *args: "Any", **kwargs: "Any" diff --git a/sentry_sdk/integrations/redis/rb.py b/sentry_sdk/integrations/redis/rb.py index e2ce863fe8..05c4455a35 100644 --- a/sentry_sdk/integrations/redis/rb.py +++ b/sentry_sdk/integrations/redis/rb.py @@ -10,7 +10,7 @@ def _patch_rb() -> None: try: - import rb.clients # type: ignore + import rb.clients # type: ignore # noqa: PLC0415 except ImportError: pass else: diff --git a/sentry_sdk/integrations/redis/redis.py b/sentry_sdk/integrations/redis/redis.py index e704c9bc6a..e93257cf3e 100644 --- a/sentry_sdk/integrations/redis/redis.py +++ b/sentry_sdk/integrations/redis/redis.py @@ -45,11 +45,11 @@ def _patch_redis(StrictRedis: "Any", client: "Any") -> None: # noqa: N803 ) try: - import redis.asyncio + import redis.asyncio # noqa: PLC0415 except ImportError: pass else: - from sentry_sdk.integrations.redis._async_common import ( + from sentry_sdk.integrations.redis._async_common import ( # noqa: PLC0415 patch_redis_async_client, patch_redis_async_pipeline, ) diff --git a/sentry_sdk/integrations/redis/redis_cluster.py b/sentry_sdk/integrations/redis/redis_cluster.py index b6c95e6abd..059ddc3497 100644 --- a/sentry_sdk/integrations/redis/redis_cluster.py +++ b/sentry_sdk/integrations/redis/redis_cluster.py @@ -76,7 +76,7 @@ def _set_cluster_db_data( def _patch_redis_cluster() -> None: """Patches the cluster module on redis SDK (as opposed to rediscluster library)""" try: - from redis import RedisCluster, cluster + from redis import RedisCluster, cluster # noqa: PLC0415 except ImportError: pass else: @@ -93,11 +93,11 @@ def _patch_redis_cluster() -> None: ) try: - from redis.asyncio import cluster as async_cluster + from redis.asyncio import cluster as async_cluster # noqa: PLC0415 except ImportError: pass else: - from sentry_sdk.integrations.redis._async_common import ( + from sentry_sdk.integrations.redis._async_common import ( # noqa: PLC0415 patch_redis_async_client, patch_redis_async_pipeline, ) diff --git a/sentry_sdk/integrations/redis/redis_py_cluster_legacy.py b/sentry_sdk/integrations/redis/redis_py_cluster_legacy.py index 3437aa1f2f..d8c266b595 100644 --- a/sentry_sdk/integrations/redis/redis_py_cluster_legacy.py +++ b/sentry_sdk/integrations/redis/redis_py_cluster_legacy.py @@ -15,7 +15,7 @@ def _patch_rediscluster() -> None: try: - import rediscluster # type: ignore + import rediscluster # type: ignore # noqa: PLC0415 except ImportError: return diff --git a/sentry_sdk/integrations/spark/spark_driver.py b/sentry_sdk/integrations/spark/spark_driver.py index a83532b6a6..6dc390bd3f 100644 --- a/sentry_sdk/integrations/spark/spark_driver.py +++ b/sentry_sdk/integrations/spark/spark_driver.py @@ -25,7 +25,7 @@ def _set_app_properties() -> None: Set properties in driver that propagate to worker processes, allowing for workers to have access to those properties. This allows worker integration to have access to app_name and application_id. """ - from pyspark import SparkContext + from pyspark import SparkContext # noqa: PLC0415 spark_context = SparkContext._active_spark_context if spark_context: @@ -43,7 +43,7 @@ def _start_sentry_listener(sc: "SparkContext") -> None: """ Start java gateway server to add custom `SparkListener` """ - from pyspark.java_gateway import ensure_callback_server_started + from pyspark.java_gateway import ensure_callback_server_started # noqa: PLC0415 gw = sc._gateway ensure_callback_server_started(gw) @@ -92,7 +92,7 @@ def _activate_integration(sc: "SparkContext") -> None: def _patch_spark_context_init() -> None: - from pyspark import SparkContext + from pyspark import SparkContext # noqa: PLC0415 spark_context_init = SparkContext._do_init @@ -108,7 +108,7 @@ def _sentry_patched_spark_context_init( def _setup_sentry_tracing() -> None: - from pyspark import SparkContext + from pyspark import SparkContext # noqa: PLC0415 if SparkContext._active_spark_context is not None: _activate_integration(SparkContext._active_spark_context) @@ -241,7 +241,7 @@ def onStageSubmitted(self, stageSubmitted: "Any") -> None: # noqa: N802,N803 _set_app_properties() def onStageCompleted(self, stageCompleted: "Any") -> None: # noqa: N802,N803 - from py4j.protocol import Py4JJavaError # type: ignore + from py4j.protocol import Py4JJavaError # type: ignore # noqa: PLC0415 stage_info = stageCompleted.stageInfo() message = "" diff --git a/sentry_sdk/integrations/spark/spark_worker.py b/sentry_sdk/integrations/spark/spark_worker.py index 5906472748..b8ab3a1660 100644 --- a/sentry_sdk/integrations/spark/spark_worker.py +++ b/sentry_sdk/integrations/spark/spark_worker.py @@ -22,7 +22,7 @@ class SparkWorkerIntegration(Integration): @staticmethod def setup_once() -> None: - import pyspark.daemon as original_daemon + import pyspark.daemon as original_daemon # noqa: PLC0415 original_daemon.worker_main = _sentry_worker_main @@ -57,7 +57,7 @@ def _capture_exception(exc_info: "ExcInfo") -> None: def _tag_task_context() -> None: - from pyspark.taskcontext import TaskContext + from pyspark.taskcontext import TaskContext # noqa: PLC0415 scope = sentry_sdk.get_isolation_scope() @@ -98,7 +98,7 @@ def process_event(event: "Event", hint: "Hint") -> "Optional[Event]": def _sentry_worker_main(*args: "Optional[Any]", **kwargs: "Optional[Any]") -> None: - import pyspark.worker as original_worker + import pyspark.worker as original_worker # noqa: PLC0415 try: original_worker.main(*args, **kwargs) diff --git a/sentry_sdk/integrations/starlette.py b/sentry_sdk/integrations/starlette.py index 33d50bba81..c5a18fbf06 100644 --- a/sentry_sdk/integrations/starlette.py +++ b/sentry_sdk/integrations/starlette.py @@ -740,13 +740,13 @@ def patch_templates() -> None: # (markupsafe is a dependency of Jinja2) # In this case we do not need to patch the Jinja2Templates class try: - from markupsafe import Markup + from markupsafe import Markup # noqa: PLC0415 except ImportError: return # Nothing to do # https://github.com/Kludex/starlette/commit/96479daca2e4bd8157f68d914fd162aa94eff73a try: - from starlette.templating import Jinja2Templates + from starlette.templating import Jinja2Templates # noqa: PLC0415 except ImportError: return diff --git a/sentry_sdk/integrations/threading.py b/sentry_sdk/integrations/threading.py index f3ba046332..7866fa905b 100644 --- a/sentry_sdk/integrations/threading.py +++ b/sentry_sdk/integrations/threading.py @@ -49,12 +49,12 @@ def setup_once() -> None: old_start = Thread.start try: - from django import VERSION as django_version # noqa: N811 + from django import VERSION as django_version # noqa: N811, PLC0415 except ImportError: django_version = None try: - import channels # type: ignore[import-untyped] + import channels # type: ignore[import-untyped] # noqa: PLC0415 channels_version = channels.__version__ except (ImportError, AttributeError): diff --git a/sentry_sdk/scope.py b/sentry_sdk/scope.py index 78f974a533..e7e044ab0b 100644 --- a/sentry_sdk/scope.py +++ b/sentry_sdk/scope.py @@ -378,7 +378,7 @@ def get_global_scope(cls) -> "Scope": return _global_scope def set_global_attributes(self) -> None: - from sentry_sdk.client import SDK_INFO + from sentry_sdk.client import SDK_INFO # noqa: PLC0415 self.set_attribute(SPANDATA.SENTRY_SDK_NAME, SDK_INFO["name"]) self.set_attribute(SPANDATA.SENTRY_SDK_VERSION, SDK_INFO["version"]) diff --git a/sentry_sdk/spotlight.py b/sentry_sdk/spotlight.py index 93cf33be13..21165160c8 100644 --- a/sentry_sdk/spotlight.py +++ b/sentry_sdk/spotlight.py @@ -118,7 +118,7 @@ class SpotlightMiddleware(MiddlewareMixin): # type: ignore[misc] def __init__(self: "Self", get_response: "Callable[..., HttpResponse]") -> None: super().__init__(get_response) - import sentry_sdk.api + import sentry_sdk.api # noqa: PLC0415 self.sentry_sdk = sentry_sdk.api diff --git a/sentry_sdk/traces.py b/sentry_sdk/traces.py index 0d317be083..30a8eac35c 100644 --- a/sentry_sdk/traces.py +++ b/sentry_sdk/traces.py @@ -174,7 +174,7 @@ def start_span( :return: The span that has been started. :rtype: StreamedSpan """ - from sentry_sdk.tracing_utils import has_span_streaming_enabled + from sentry_sdk.tracing_utils import has_span_streaming_enabled # noqa: PLC0415 client = sentry_sdk.get_client() if client.is_active() and not has_span_streaming_enabled(client.options): @@ -864,7 +864,7 @@ def make_db_query(sql): # Function implementation pass """ - from sentry_sdk.tracing_utils import ( + from sentry_sdk.tracing_utils import ( # noqa: PLC0415 create_streaming_span_decorator, ) diff --git a/sentry_sdk/tracing.py b/sentry_sdk/tracing.py index 38922773ea..c55b3ab5be 100644 --- a/sentry_sdk/tracing.py +++ b/sentry_sdk/tracing.py @@ -1466,7 +1466,7 @@ def calculate_interest_rate(amount, rate, years): # Function implementation pass """ - from sentry_sdk.tracing_utils import create_span_decorator + from sentry_sdk.tracing_utils import create_span_decorator # noqa: PLC0415 decorator = create_span_decorator( op=op, diff --git a/sentry_sdk/transport.py b/sentry_sdk/transport.py index 85308c7797..ed7715386e 100644 --- a/sentry_sdk/transport.py +++ b/sentry_sdk/transport.py @@ -217,7 +217,7 @@ class HttpTransportCore(Transport): TIMEOUT = 30 # seconds def __init__(self: "Self", options: "Dict[str, Any]") -> None: - from sentry_sdk.consts import VERSION + from sentry_sdk.consts import VERSION # noqa: PLC0415 Transport.__init__(self, options) assert self.parsed_dsn is not None @@ -821,7 +821,7 @@ def _make_pool(self: "Self") -> "Union[PoolManager, ProxyManager]": use_socks_proxy = True try: # Check if PySocks dependency is available - from urllib3.contrib.socks import SOCKSProxyManager + from urllib3.contrib.socks import SOCKSProxyManager # noqa: PLC0415 except ImportError: use_socks_proxy = False logger.warning( diff --git a/sentry_sdk/utils.py b/sentry_sdk/utils.py index 6d4d46993f..bef8993e97 100644 --- a/sentry_sdk/utils.py +++ b/sentry_sdk/utils.py @@ -592,7 +592,7 @@ def serialize_frame( max_value_length: "Optional[int]" = None, custom_repr: "Optional[Callable[..., Optional[str]]]" = None, ) -> "Dict[str, Any]": - from sentry_sdk.serializer import serialize + from sentry_sdk.serializer import serialize # noqa: PLC0415 f_code = getattr(frame, "f_code", None) if not f_code: @@ -1364,8 +1364,8 @@ def _is_contextvars_broken() -> bool: Returns whether gevent/eventlet have patched the stdlib in a way where thread locals are now more "correct" than contextvars. """ try: - import gevent - from gevent.monkey import is_object_patched + import gevent # noqa: PLC0415 + from gevent.monkey import is_object_patched # noqa: PLC0415 # Get the MAJOR and MINOR version numbers of Gevent version_tuple = tuple( @@ -1391,8 +1391,8 @@ def _is_contextvars_broken() -> bool: pass try: - import greenlet - from eventlet.patcher import is_monkey_patched # type: ignore + import greenlet # noqa: PLC0415 + from eventlet.patcher import is_monkey_patched # type: ignore # noqa: PLC0415 greenlet_version = parse_version(greenlet.__version__) @@ -1454,7 +1454,7 @@ def _get_contextvars() -> "Tuple[bool, type]": # `aiocontextvars` is absolutely required for functional # contextvars on Python 3.6. try: - from aiocontextvars import ContextVar + from aiocontextvars import ContextVar # noqa: PLC0415 return True, ContextVar except ImportError: @@ -1462,7 +1462,7 @@ def _get_contextvars() -> "Tuple[bool, type]": else: # On Python 3.7 contextvars are functional. try: - from contextvars import ContextVar + from contextvars import ContextVar # noqa: PLC0415 return True, ContextVar except ImportError: @@ -1470,7 +1470,7 @@ def _get_contextvars() -> "Tuple[bool, type]": # Fall back to basic thread-local usage. - from threading import local + from threading import local # noqa: PLC0415 return False, _make_threadlocal_contextvars(local) @@ -1799,7 +1799,7 @@ def is_sentry_url(client: "sentry_sdk.client.BaseClient", url: str) -> bool: def _generate_installed_modules() -> "Iterator[Tuple[str, str]]": try: - from importlib import metadata + from importlib import metadata # noqa: PLC0415 yielded = set() for dist in metadata.distributions(): @@ -1817,7 +1817,7 @@ def _generate_installed_modules() -> "Iterator[Tuple[str, str]]": except ImportError: # < py3.8 try: - import pkg_resources + import pkg_resources # noqa: PLC0415 except ImportError: return From bc7834cd6cf5e507bc88d193b64ad281612d9d2d Mon Sep 17 00:00:00 2001 From: "sentry-junior[bot]" <264270552+sentry-junior[bot]@users.noreply.github.com> Date: Mon, 16 Nov 2026 09:54:49 +0000 Subject: [PATCH 2/2] ref: Move inline imports to the top level where possible 16 of the inline imports that PLC0415 flags don't need to be inline: stdlib modules that are already loaded on import sentry_sdk, internal modules with no circular import, names that can join an existing module-level import, and third-party imports from packages that the integration already imports at the top. Co-Authored-By: Ivana Kellyer <131587164+sentrivana@users.noreply.github.com> --- sentry_sdk/_compat.py | 9 +++------ sentry_sdk/consts.py | 3 +-- sentry_sdk/integrations/__init__.py | 3 +-- sentry_sdk/integrations/celery/__init__.py | 11 ++++------- sentry_sdk/integrations/grpc/__init__.py | 2 -- sentry_sdk/integrations/pyramid.py | 3 +-- sentry_sdk/scope.py | 4 +--- sentry_sdk/traces.py | 12 +++++------- sentry_sdk/tracing.py | 3 +-- sentry_sdk/transport.py | 4 +--- sentry_sdk/utils.py | 5 +---- 11 files changed, 19 insertions(+), 40 deletions(-) diff --git a/sentry_sdk/_compat.py b/sentry_sdk/_compat.py index 64dcabddcf..9ba466b78d 100644 --- a/sentry_sdk/_compat.py +++ b/sentry_sdk/_compat.py @@ -1,5 +1,8 @@ import sys from typing import TYPE_CHECKING +from warnings import warn + +from sentry_sdk.consts import FALSE_VALUES if TYPE_CHECKING: from typing import Any, TypeVar @@ -39,8 +42,6 @@ def check_uwsgi_thread_support() -> bool: except ImportError: return True - from sentry_sdk.consts import FALSE_VALUES # noqa: PLC0415 - def enabled(option: str) -> bool: value = opt.get(option, False) if isinstance(value, bool): @@ -61,8 +62,6 @@ def enabled(option: str) -> bool: lazy_mode = enabled("lazy-apps") or enabled("lazy") if lazy_mode and not threads_enabled: - from warnings import warn # noqa: PLC0415 - warn( Warning( "IMPORTANT: " @@ -75,8 +74,6 @@ def enabled(option: str) -> bool: return False elif not lazy_mode and (not threads_enabled or not fork_hooks_on): - from warnings import warn # noqa: PLC0415 - warn( Warning( "IMPORTANT: " diff --git a/sentry_sdk/consts.py b/sentry_sdk/consts.py index 05f179e32e..45776a31d3 100644 --- a/sentry_sdk/consts.py +++ b/sentry_sdk/consts.py @@ -1,3 +1,4 @@ +import inspect import itertools from enum import Enum from typing import TYPE_CHECKING @@ -1912,8 +1913,6 @@ def __init__( def _get_default_options() -> "dict[str, Any]": - import inspect # noqa: PLC0415 - a = inspect.getfullargspec(ClientConstructor.__init__) defaults = a.defaults or () kwonlydefaults = a.kwonlydefaults or {} diff --git a/sentry_sdk/integrations/__init__.py b/sentry_sdk/integrations/__init__.py index 1b8fdc7fcb..0e2d7a6af1 100644 --- a/sentry_sdk/integrations/__init__.py +++ b/sentry_sdk/integrations/__init__.py @@ -1,4 +1,5 @@ from abc import ABC, abstractmethod +from importlib import import_module from itertools import zip_longest from threading import Lock from typing import TYPE_CHECKING @@ -30,8 +31,6 @@ def iter_default_integrations( with_auto_enabling_integrations: bool, ) -> "Iterator[Type[Integration]]": """Returns an iterator of the default integration classes:""" - from importlib import import_module # noqa: PLC0415 - if with_auto_enabling_integrations: all_import_strings = integrations + auto_enabling_integrations else: diff --git a/sentry_sdk/integrations/celery/__init__.py b/sentry_sdk/integrations/celery/__init__.py index 69c5751bea..28708e1d81 100644 --- a/sentry_sdk/integrations/celery/__init__.py +++ b/sentry_sdk/integrations/celery/__init__.py @@ -37,7 +37,10 @@ try: - from celery import __version__ as CELERY_VERSION # type: ignore + import celery.app.trace as trace # type: ignore + from billiard.pool import Worker # type: ignore + from celery import Celery + from celery import __version__ as CELERY_VERSION from celery.app.task import Task # type: ignore from celery.app.trace import task_has_custom from celery.exceptions import ( # type: ignore @@ -497,8 +500,6 @@ def _inner(*args: "Any", **kwargs: "Any") -> "Any": def _patch_build_tracer() -> None: - import celery.app.trace as trace # type: ignore # noqa: PLC0415 - original_build_tracer = trace.build_tracer def sentry_build_tracer( @@ -527,16 +528,12 @@ def _patch_task_apply_async() -> None: def _patch_celery_send_task() -> None: - from celery import Celery # noqa: PLC0415 - Celery.send_task = _wrap_task_run(Celery.send_task) def _patch_worker_exit() -> None: # Need to flush queue before worker shutdown because a crashing worker will # call os._exit - from billiard.pool import Worker # type: ignore # noqa: PLC0415 - original_workloop = Worker.workloop def sentry_workloop(*args: "Any", **kwargs: "Any") -> "Any": diff --git a/sentry_sdk/integrations/grpc/__init__.py b/sentry_sdk/integrations/grpc/__init__.py index 5e074f0e41..d5039e183f 100644 --- a/sentry_sdk/integrations/grpc/__init__.py +++ b/sentry_sdk/integrations/grpc/__init__.py @@ -175,8 +175,6 @@ class GRPCIntegration(Integration): @staticmethod def setup_once() -> None: - import grpc # noqa: PLC0415 - grpc.insecure_channel = _wrap_channel_sync(grpc.insecure_channel) grpc.secure_channel = _wrap_channel_sync(grpc.secure_channel) grpc.intercept_channel = _wrap_intercept_channel(grpc.intercept_channel) diff --git a/sentry_sdk/integrations/pyramid.py b/sentry_sdk/integrations/pyramid.py index d1bc6e81e1..9e8f7b31ed 100644 --- a/sentry_sdk/integrations/pyramid.py +++ b/sentry_sdk/integrations/pyramid.py @@ -21,6 +21,7 @@ ) try: + from pyramid import router from pyramid.httpexceptions import HTTPException from pyramid.request import Request except ImportError: @@ -69,8 +70,6 @@ def __init__(self, transaction_style: str = "route_name") -> None: @staticmethod def setup_once() -> None: - from pyramid import router # noqa: PLC0415 - old_call_view = router._call_view @functools.wraps(old_call_view) diff --git a/sentry_sdk/scope.py b/sentry_sdk/scope.py index e7e044ab0b..7f8ae58cb7 100644 --- a/sentry_sdk/scope.py +++ b/sentry_sdk/scope.py @@ -378,8 +378,6 @@ def get_global_scope(cls) -> "Scope": return _global_scope def set_global_attributes(self) -> None: - from sentry_sdk.client import SDK_INFO # noqa: PLC0415 - self.set_attribute(SPANDATA.SENTRY_SDK_NAME, SDK_INFO["name"]) self.set_attribute(SPANDATA.SENTRY_SDK_VERSION, SDK_INFO["version"]) @@ -2253,7 +2251,7 @@ def should_send_default_pii() -> bool: # Circular imports -from sentry_sdk.client import NonRecordingClient +from sentry_sdk.client import SDK_INFO, NonRecordingClient if TYPE_CHECKING: import sentry_sdk.client diff --git a/sentry_sdk/traces.py b/sentry_sdk/traces.py index 30a8eac35c..63b47d979a 100644 --- a/sentry_sdk/traces.py +++ b/sentry_sdk/traces.py @@ -32,7 +32,11 @@ try_autostart_continuous_profiler, try_profile_lifecycle_trace_start, ) -from sentry_sdk.tracing_utils import Baggage +from sentry_sdk.tracing_utils import ( + Baggage, + create_streaming_span_decorator, + has_span_streaming_enabled, +) from sentry_sdk.utils import ( capture_internal_exceptions, format_attribute, @@ -174,8 +178,6 @@ def start_span( :return: The span that has been started. :rtype: StreamedSpan """ - from sentry_sdk.tracing_utils import has_span_streaming_enabled # noqa: PLC0415 - client = sentry_sdk.get_client() if client.is_active() and not has_span_streaming_enabled(client.options): warnings.warn( @@ -864,10 +866,6 @@ def make_db_query(sql): # Function implementation pass """ - from sentry_sdk.tracing_utils import ( # noqa: PLC0415 - create_streaming_span_decorator, - ) - decorator = create_streaming_span_decorator( name=name, attributes=attributes, diff --git a/sentry_sdk/tracing.py b/sentry_sdk/tracing.py index c55b3ab5be..dfc72d4306 100644 --- a/sentry_sdk/tracing.py +++ b/sentry_sdk/tracing.py @@ -1466,8 +1466,6 @@ def calculate_interest_rate(amount, rate, years): # Function implementation pass """ - from sentry_sdk.tracing_utils import create_span_decorator # noqa: PLC0415 - decorator = create_span_decorator( op=op, name=name, @@ -1487,6 +1485,7 @@ def calculate_interest_rate(amount, rate, years): Baggage, EnvironHeaders, _generate_sample_rand, + create_span_decorator, extract_sentrytrace_data, has_span_streaming_enabled, has_tracing_enabled, diff --git a/sentry_sdk/transport.py b/sentry_sdk/transport.py index ed7715386e..b725337f1d 100644 --- a/sentry_sdk/transport.py +++ b/sentry_sdk/transport.py @@ -43,7 +43,7 @@ import urllib3 import sentry_sdk -from sentry_sdk.consts import EndpointType +from sentry_sdk.consts import VERSION, EndpointType from sentry_sdk.envelope import Envelope, Item, PayloadRef from sentry_sdk.utils import ( Dsn, @@ -217,8 +217,6 @@ class HttpTransportCore(Transport): TIMEOUT = 30 # seconds def __init__(self: "Self", options: "Dict[str, Any]") -> None: - from sentry_sdk.consts import VERSION # noqa: PLC0415 - Transport.__init__(self, options) assert self.parsed_dsn is not None self.options: "Dict[str, Any]" = options diff --git a/sentry_sdk/utils.py b/sentry_sdk/utils.py index bef8993e97..4a6e21e5aa 100644 --- a/sentry_sdk/utils.py +++ b/sentry_sdk/utils.py @@ -1469,10 +1469,7 @@ def _get_contextvars() -> "Tuple[bool, type]": pass # Fall back to basic thread-local usage. - - from threading import local # noqa: PLC0415 - - return False, _make_threadlocal_contextvars(local) + return False, _make_threadlocal_contextvars(threading.local) HAS_REAL_CONTEXTVARS, ContextVar = _get_contextvars()