diff --git a/pyproject.toml b/pyproject.toml index c98f3d62cc..dd6b9a9dc4 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -302,6 +302,7 @@ select = [ "I", "T20", # print() and pprint() calls "PT011", # pytest.raises() too broad + "PLC0415", # Import not at the top level of the file "RUF100", # Unused noqa directive ] @@ -318,7 +319,7 @@ ignore = [ [tool.ruff.lint.per-file-ignores] "scripts/**" = ["T20"] -"tests/**" = ["T20"] +"tests/**" = ["T20", "PLC0415"] [tool.ruff.format] # ruff format already excludes the same files as specified in extend-exclude diff --git a/sentry_sdk/_compat.py b/sentry_sdk/_compat.py index f62175c09f..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 @@ -35,12 +38,10 @@ 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 - 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 - 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 - warn( Warning( "IMPORTANT: " diff --git a/sentry_sdk/client.py b/sentry_sdk/client.py index b281ccdad5..eec943176c 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 acd0598bde..3d89c260f3 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 @@ -1910,8 +1911,6 @@ def __init__( def _get_default_options() -> "dict[str, Any]": - import inspect - 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 ad250acf42..4cd4595c5f 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 - if with_auto_enabling_integrations: all_import_strings = integrations + auto_enabling_integrations else: 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..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 - 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 - 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 - original_workloop = Worker.workloop def sentry_workloop(*args: "Any", **kwargs: "Any") -> "Any": 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..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 - 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/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..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 - old_call_view = router._call_view @functools.wraps(old_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 2bcc3fe367..349ee5bed6 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: ) 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 e614b6762f..620845ad05 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: _set_app_properties() def onStageCompleted(self, stageCompleted: "Any") -> None: - 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 5f1e2e1bf1..4fde3a3d14 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 + from django import VERSION as django_version # noqa: 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..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 - 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/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..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 - 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 ( - 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 38922773ea..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 - 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 f459c87c01..a3a046ea3d 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 - Transport.__init__(self, options) assert self.parsed_dsn is not None self.options: "Dict[str, Any]" = options @@ -821,7 +819,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 a6faf613ee..b1acf95bc5 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,17 +1462,14 @@ 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: pass # Fall back to basic thread-local usage. - - from threading import local - - return False, _make_threadlocal_contextvars(local) + return False, _make_threadlocal_contextvars(threading.local) HAS_REAL_CONTEXTVARS, ContextVar = _get_contextvars() @@ -1799,7 +1796,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 +1814,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