Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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
]

Expand All @@ -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
Expand Down
11 changes: 4 additions & 7 deletions sentry_sdk/_compat.py
Original file line number Diff line number Diff line change
@@ -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
Expand Down Expand Up @@ -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):
Expand All @@ -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: "
Expand All @@ -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: "
Expand Down
2 changes: 1 addition & 1 deletion sentry_sdk/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"]:
Expand Down
3 changes: 1 addition & 2 deletions sentry_sdk/consts.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import inspect
import itertools
from enum import Enum
from typing import TYPE_CHECKING
Expand Down Expand Up @@ -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 {}
Expand Down
3 changes: 1 addition & 2 deletions sentry_sdk/integrations/__init__.py
Original file line number Diff line number Diff line change
@@ -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
Expand Down Expand Up @@ -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:
Expand Down
2 changes: 1 addition & 1 deletion sentry_sdk/integrations/anthropic.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
6 changes: 3 additions & 3 deletions sentry_sdk/integrations/beam.py
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand Down Expand Up @@ -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)

Expand Down
11 changes: 4 additions & 7 deletions sentry_sdk/integrations/celery/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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(
Expand Down Expand Up @@ -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":
Expand Down
2 changes: 1 addition & 1 deletion sentry_sdk/integrations/celery/beat.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
2 changes: 1 addition & 1 deletion sentry_sdk/integrations/chalice.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
34 changes: 17 additions & 17 deletions sentry_sdk/integrations/django/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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__

Expand All @@ -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

Expand Down Expand Up @@ -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

Expand Down Expand Up @@ -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:
Expand All @@ -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:
Expand Down Expand Up @@ -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

Expand All @@ -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

Expand All @@ -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)

Expand Down Expand Up @@ -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

Expand All @@ -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)

Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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:
Expand Down
10 changes: 5 additions & 5 deletions sentry_sdk/integrations/django/asgi.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
)
Expand Down Expand Up @@ -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__

Expand Down Expand Up @@ -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__
Expand Down Expand Up @@ -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(
Expand Down
8 changes: 4 additions & 4 deletions sentry_sdk/integrations/django/caching.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand Down Expand Up @@ -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)
Expand All @@ -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"]
Expand Down
Loading
Loading