Skip to content
Draft
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
1 change: 1 addition & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -152,6 +152,7 @@ python_version = "3.11"
strict_equality = true
strict_optional = true
warn_redundant_casts = true
warn_unreachable = true
warn_unused_configs = true
warn_unused_ignores = true

Expand Down
16 changes: 8 additions & 8 deletions sentry_sdk/ai/_openai_completions_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ def _get_system_instructions(
messages: "Iterable[ChatCompletionMessageParam]",
) -> "list[ChatCompletionSystemMessageParam]":
if not isinstance(messages, Iterable):
return []
return [] # type: ignore[unreachable] # defensive check on user input

return [message for message in messages if _is_system_instruction(message)]

Expand All @@ -38,7 +38,7 @@ def _get_text_items(
return [content]

if not isinstance(content, Iterable):
return []
return [] # type: ignore[unreachable] # defensive check on user input

text_items: "list[str]" = []
for part in content:
Expand All @@ -57,11 +57,11 @@ def _transform_system_instructions(

for instruction in system_instructions:
if not isinstance(instruction, dict):
continue
continue # type: ignore[unreachable] # defensive check on user input

content = instruction.get("content")
if content is None:
continue
continue # type: ignore[unreachable] # defensive check on user input

text_parts: "list[TextPart]" = [
{"type": "text", "content": text} for text in _get_text_items(content)
Expand All @@ -78,20 +78,20 @@ def _transform_tool_definitions(
Transform tool definitions to the schema used by the "gen_ai.tool.definitions" attribute.
"""
if not isinstance(tools, Iterable):
return []
return [] # type: ignore[unreachable] # defensive check on user input

tool_definitions = []
for tool in tools:
if not isinstance(tool, dict) or "type" not in tool:
continue
continue # type: ignore[unreachable] # defensive check on user input

if tool["type"] == "function":
tool_definition: "ToolDefinition" = {
"type": "function",
}

if "function" not in tool:
tool_definitions.append(tool_definition)
tool_definitions.append(tool_definition) # type: ignore[unreachable] # defensive check on user input
continue

if "name" in tool["function"]:
Expand All @@ -112,7 +112,7 @@ def _transform_tool_definitions(
}

if "custom" not in tool:
tool_definitions.append(tool_definition)
tool_definitions.append(tool_definition) # type: ignore[unreachable] # defensive check on user input
continue

if "name" in tool["custom"]:
Expand Down
10 changes: 5 additions & 5 deletions sentry_sdk/ai/_openai_responses_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,18 +40,18 @@ def _transform_system_instructions(

for instruction in system_instructions:
if not isinstance(instruction, dict):
continue
continue # type: ignore[unreachable] # defensive check on user input

content = instruction.get("content")
if content is None:
continue
continue # type: ignore[unreachable] # defensive check on user input

if isinstance(content, str):
instruction_text_parts.append({"type": "text", "content": content})
continue

if not isinstance(content, Iterable):
continue
continue # type: ignore[unreachable] # defensive check on user input

for part in content:
if not isinstance(part, dict) or part.get("type") != "input_text":
Expand All @@ -70,12 +70,12 @@ def _transform_tool_definitions(tools: "Iterable[ToolParam]") -> "list[ToolDefin
Includes special handling for tools where the type includes a name, description or parameters.
"""
if not isinstance(tools, Iterable):
return []
return [] # type: ignore[unreachable] # defensive check on user input

tool_definitions = []
for tool in tools:
if not isinstance(tool, dict) or "type" not in tool:
continue
continue # type: ignore[unreachable] # defensive check on user input

if tool["type"] == "function":
tool_definition: "ToolDefinition" = {
Expand Down
16 changes: 8 additions & 8 deletions sentry_sdk/ai/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -130,7 +130,7 @@ def transform_openai_content_part(
is not OpenAI image_url format or transformation fails.
"""
if not isinstance(content_part, dict):
return None
return None # type: ignore[unreachable] # defensive check on SDK input

block_type = content_part.get("type")

Expand Down Expand Up @@ -203,7 +203,7 @@ def transform_anthropic_content_part(
is not Anthropic format or transformation fails.
"""
if not isinstance(content_part, dict):
return None
return None # type: ignore[unreachable] # defensive check on SDK input

block_type = content_part.get("type")

Expand Down Expand Up @@ -271,7 +271,7 @@ def transform_google_content_part(
is not Google format or transformation fails.
"""
if not isinstance(content_part, dict):
return None
return None # type: ignore[unreachable] # defensive check on SDK input

# Handle Google inline_data format
if "inline_data" in content_part:
Expand Down Expand Up @@ -330,7 +330,7 @@ def transform_generic_content_part(
is not generic format or transformation fails.
"""
if not isinstance(content_part, dict):
return None
return None # type: ignore[unreachable] # defensive check on SDK input

block_type = content_part.get("type")

Expand Down Expand Up @@ -405,7 +405,7 @@ def transform_content_part(
is unrecognized or transformation fails.
"""
if not isinstance(content_part, dict):
return None
return None # type: ignore[unreachable] # defensive check on SDK input

# Try OpenAI format first (most common, clear indicator)
result = transform_openai_content_part(content_part)
Expand Down Expand Up @@ -526,7 +526,7 @@ def normalize_message_roles(messages: "list[dict[str, Any]]") -> "list[dict[str,
normalized_messages = []
for message in messages:
if not isinstance(message, dict):
normalized_messages.append(message)
normalized_messages.append(message) # type: ignore[unreachable] # defensive check on SDK input
continue
normalized_message = message.copy()
if "role" in message:
Expand Down Expand Up @@ -661,7 +661,7 @@ def redact_blob_message_parts(
has_blobs = False
for message in messages:
if not isinstance(message, dict):
continue
continue # type: ignore[unreachable] # defensive check on SDK input
content = message.get("content")
if isinstance(content, list):
for item in content:
Expand All @@ -683,7 +683,7 @@ def redact_blob_message_parts(
# Second pass: redact blob content in the copy
for message in messages_copy:
if not isinstance(message, dict):
continue
continue # type: ignore[unreachable] # defensive check on SDK input

content = message.get("content")
if isinstance(content, list):
Expand Down
12 changes: 6 additions & 6 deletions sentry_sdk/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -1125,8 +1125,8 @@ def _update_session_from_event(
if exceptions:
errored = True
for error in exceptions:
if isinstance(error, AnnotatedValue):
error = error.value or {}
if isinstance(error, AnnotatedValue): # type: ignore[unreachable] # the event may already contain annotated values
error = error.value or {} # type: ignore[unreachable]
mechanism = error.get("mechanism")
if isinstance(mechanism, Mapping) and mechanism.get("handled") is False:
crashed = True
Expand Down Expand Up @@ -1475,14 +1475,14 @@ async def close_async(
semantics as :py:meth:`Client.flush_async`.
"""
if self.transport is not None:
if not self._has_async_transport():
if not isinstance(self.transport, AsyncHttpTransport):
logger.debug(
"close_async() used with non-async transport, aborting. Please use close() instead."
)
return
await self.flush_async(timeout=timeout, callback=callback)
self._close_components()
kill_task = self.transport.kill() # type: ignore
kill_task = self.transport.kill()
if kill_task is not None:
await kill_task
self.transport = None
Expand Down Expand Up @@ -1525,15 +1525,15 @@ async def flush_async(
:param callback: Is invoked with the number of pending events and the configured timeout.
"""
if self.transport is not None:
if not self._has_async_transport():
if not isinstance(self.transport, AsyncHttpTransport):
logger.debug(
"flush_async() used with non-async transport, aborting. Please use flush() instead."
)
return
if timeout is None:
timeout = self.options["shutdown_timeout"]
self._flush_components()
flush_task = self.transport.flush(timeout=timeout, callback=callback) # type: ignore
flush_task = self.transport.flush(timeout=timeout, callback=callback)
if flush_task is not None:
await flush_task

Expand Down
2 changes: 1 addition & 1 deletion sentry_sdk/feature_flags.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ def get(self) -> "list[FlagData]":
]

def set(self, flag: str, result: bool) -> None:
if isinstance(result, FlagBuffer):
if isinstance(result, FlagBuffer): # type: ignore[unreachable] # guard against misuse
# If someone were to insert `self` into `self` this would create a circular dependency
# on the lock. This is of course a deadlock. However, this is far outside the expected
# usage of this class. We guard against it here for completeness and to document this
Expand Down
8 changes: 6 additions & 2 deletions sentry_sdk/integrations/aiohttp.py
Original file line number Diff line number Diff line change
Expand Up @@ -492,7 +492,9 @@ async def on_request_start(
# `baggage` with Sentry members (e.g. merged by the boto3 integration
# before signing): skip so Sentry members are not duplicated.
with capture_internal_exceptions():
baggage = params.headers.get(BAGGAGE_HEADER_NAME)
baggage: "Optional[Union[str, bytes]]" = params.headers.get(
BAGGAGE_HEADER_NAME
)
if baggage:
if isinstance(baggage, bytes):
baggage = baggage.decode("latin-1")
Expand All @@ -503,7 +505,9 @@ async def on_request_start(
headers_to_skip.add(BAGGAGE_HEADER_NAME)

with capture_internal_exceptions():
authorization = params.headers.get("Authorization")
authorization: "Optional[Union[str, bytes]]" = params.headers.get(
"Authorization"
)
if authorization:
if isinstance(authorization, bytes):
authorization = authorization.decode("latin-1")
Expand Down
4 changes: 2 additions & 2 deletions sentry_sdk/integrations/anthropic.py
Original file line number Diff line number Diff line change
Expand Up @@ -138,7 +138,7 @@ class _PatchedMessageStreamManager(MessageStreamManager):
_integration: "AnthropicIntegration"

_max_tokens: int
_messages: Iterable[MessageParam]
_messages: Optional[Iterable[MessageParam]]
_model: Optional[ModelParam]
_system: Optional[Union[str, Iterable[TextBlockParam]]]
_temperature: Optional[float]
Expand All @@ -151,7 +151,7 @@ class _PatchedAsyncMessageStreamManager(AsyncMessageStreamManager[Any]):
_integration: "AnthropicIntegration"

_max_tokens: int
_messages: Iterable[MessageParam]
_messages: Optional[Iterable[MessageParam]]
_model: Optional[ModelParam]
_system: Optional[Union[str, Iterable[TextBlockParam]]]
_temperature: Optional[float]
Expand Down
2 changes: 1 addition & 1 deletion sentry_sdk/integrations/aws_lambda.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@

def _get_user_from_event(aws_event: "dict[str, Any]") -> "dict[str, Any]":
if not isinstance(aws_event, dict):
return {}
return {} # type: ignore[unreachable] # the event can be any JSON value

identity = aws_event.get("requestContext", {}).get("identity")
if identity is None:
Expand Down
2 changes: 1 addition & 1 deletion sentry_sdk/integrations/boto3/_services/bedrock.py
Original file line number Diff line number Diff line change
Expand Up @@ -583,7 +583,7 @@ def _transform_tool_definitions(
result: "list[ToolDefinition]" = []
for tool in tools:
if not isinstance(tool, dict):
continue
continue # type: ignore[unreachable] # defensive check on user input

if "toolSpec" in tool:
tool_definition: "ToolDefinition" = {"type": "function"}
Expand Down
2 changes: 1 addition & 1 deletion sentry_sdk/integrations/django/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -341,7 +341,7 @@ def _patch_drf() -> None:

with _DRF_PATCH_LOCK:
if _DRF_PATCHED:
return
return # type: ignore[unreachable] # another thread may have set it while we waited for the lock

# We set this regardless of whether the code below succeeds or fails.
# There is no point in trying to patch again on the next request.
Expand Down
10 changes: 6 additions & 4 deletions sentry_sdk/integrations/django/templates.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,8 +45,8 @@ def get_template_frame_from_exception(


def _get_template_name_description(template_name: str) -> str:
if isinstance(template_name, (list, tuple)):
if template_name:
if isinstance(template_name, (list, tuple)): # type: ignore[unreachable] # Django also accepts a list of names
if template_name: # type: ignore[unreachable]
return "[{}, ...]".format(template_name[0])
else:
return template_name
Expand Down Expand Up @@ -133,7 +133,9 @@ def render(
django.shortcuts.render = render


def _get_template_frame_from_debug(debug: "Dict[str, Any]") -> "Dict[str, Any]":
def _get_template_frame_from_debug(
debug: "Optional[Dict[str, Any]]",
) -> "Optional[Dict[str, Any]]":
if debug is None:
return None

Expand Down Expand Up @@ -176,7 +178,7 @@ def _get_template_frame_from_source(
source: "Tuple[Origin, Tuple[int, int]]",
) -> "Optional[Dict[str, Any]]":
if not source:
return None
return None # type: ignore[unreachable] # defensive check

origin, (start, end) = source
filename = getattr(origin, "loadname", None)
Expand Down
8 changes: 1 addition & 7 deletions sentry_sdk/integrations/flask.py
Original file line number Diff line number Diff line change
Expand Up @@ -215,15 +215,9 @@ def size_of_file(self, file: "FileStorage") -> int:


def _make_request_event_processor(
app: "Flask", request: "Callable[[], Request]", integration: "FlaskIntegration"
app: "Flask", request: "Request", integration: "FlaskIntegration"
) -> "EventProcessor":
def inner(event: "Event", hint: "dict[str, Any]") -> "Event":
# 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.
if request is None:
return event

with capture_internal_exceptions():
FlaskRequestExtractor(request).extract_into_event(event)

Expand Down
1 change: 1 addition & 0 deletions sentry_sdk/integrations/gnu_backtrace.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ def setup_once() -> None:
def process_gnu_backtrace(event: "Event", hint: "dict[str, Any]") -> "Event":
with capture_internal_exceptions():
return _process_gnu_backtrace(event, hint)
return event


def _process_gnu_backtrace(event: "Event", hint: "dict[str, Any]") -> "Event":
Expand Down
14 changes: 7 additions & 7 deletions sentry_sdk/integrations/google_genai/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -212,8 +212,8 @@ def extract_contents_messages(contents: "ContentListUnion") -> "List[Dict[str, A
return messages

# Handle dictionary case (ContentDict)
if isinstance(contents, dict):
role = contents.get("role", "user")
if isinstance(contents, dict): # type: ignore[unreachable] # dicts are accepted at runtime
role = contents.get("role", "user") # type: ignore[unreachable]
parts = contents.get("parts")

if parts:
Expand Down Expand Up @@ -881,12 +881,12 @@ def _transform_system_instruction_one_level(
return text_parts

for part in parts:
if isinstance(part, Part) and isinstance(part.text, str):
text_parts.append({"type": "text", "content": part.text})
if isinstance(part, Part) and isinstance(part.text, str): # type: ignore[unreachable] # parts can hold Part objects at runtime
text_parts.append({"type": "text", "content": part.text}) # type: ignore[unreachable]
continue

if not isinstance(part, dict):
continue
continue # type: ignore[unreachable] # defensive check on user input

text = part.get("text")
if isinstance(text, str):
Expand Down Expand Up @@ -975,8 +975,8 @@ def set_span_data_for_request(
system_instructions = None
if config and hasattr(config, "system_instruction"):
system_instructions = config.system_instruction
elif isinstance(config, dict) and "system_instruction" in config:
system_instructions = config.get("system_instruction")
elif isinstance(config, dict) and "system_instruction" in config: # type: ignore[unreachable] # dicts are accepted at runtime
system_instructions = config.get("system_instruction") # type: ignore[unreachable]

if system_instructions is not None:
set_on_span(
Expand Down
Loading
Loading