Skip to content

ci(mypy): Enable redundant-expr error code - #8292

Draft
sentry-junior[bot] wants to merge 2 commits into
masterfrom
ci/mypy-redundant-expr
Draft

sentry-junior[bot] wants to merge 2 commits into
masterfrom
ci/mypy-redundant-expr

Conversation

@sentry-junior

@sentry-junior sentry-junior Bot commented Nov 16, 2026 •

Copy link
Copy Markdown
Contributor

Description

Turns on mypy's redundant-expr error code. It flags and/or operands and conditional-expression or comprehension conditions that are always true or always false according to the types. That catches dead checks, and it also catches places where an annotation is narrower than the value really is.

It reported 56 errors on master. Here's how they were fixed:

Annotation fixes (16)

  • capture_internal_exceptions() was typed as returning ContextManager[Any]. That type's __exit__ returns bool | None, so mypy assumed the block never swallows exceptions. Code like parsed_url = None; with capture_internal_exceptions(): parsed_url = parse_url(...) then looked as if parsed_url could never be None. It now returns CaptureInternalException, whose __exit__ returns bool. That fixes 14 findings in httpx, httpx2, stdlib, pyreqwest, aiohttp, and falcon.
  • langgraph._set_usage_data now accepts Union[Span, StreamedSpan], since it already handles both.
  • anthropic _set_common_input_data(max_tokens=...) is now Optional[int], because callers pass kwargs.get("max_tokens"). That removes a blanket # type: ignore.

Redundant code removed (8)
These checks really are dead at runtime, not just according to the annotations:

  • len() result checked against None in strip_string.
  • isinstance(span, dict) on spans that _split_gen_ai_spans has already filtered to dicts.
  • exc_info and before all(exc_info). sys.exc_info() always returns a 3-tuple.
  • span is not None right after isinstance(span, StreamedSpan) in ASGI.
  • iscoroutinefunction is not None in Django middleware. It is always defined.
  • x is not None on Baggage.third_party_items, which is always a str.
  • Two isinstance(part_result, dict) checks in google_genai. _extract_part_content only returns dicts or None.

Targeted # type: ignore[redundant-expr] (32 errors, 31 comments)
Each one has a short reason. They keep checks against values that can be wider at runtime than their annotations: user or third-party input in the AI integrations, non-str keys in headers and record attributes, serialize() returning None on internal errors, logging globals becoming None at interpreter shutdown, HTTPResponse.fp being set to None on close, dist.version being None, and similar cases. I didn't remove any of these defensive checks.

Bug found

The precise capture_internal_exceptions() type made mypy flag two functions that could fall off the end of a with block:

  • GnuBacktraceIntegration: if _process_gnu_backtrace raised, the event processor returned None, and the scope then dropped the user's event. It now returns the unmodified event.
  • StarletteRequestExtractor.extract_request_info: this was already implicitly returning None on an internal error. I added an explicit return None, so behavior doesn't change.

Notes

  • Changing the return type of capture_internal_exceptions() only affects typing. Downstream code that type-checks against it may now see variables assigned inside the block as possibly unset.
  • ci(mypy): Enable unused-awaitable error code #8281 has merged, so the enable_error_code list is now ["redundant-expr", "unused-awaitable"]. The sibling follow-up PRs edit the same line, so expect trivial conflicts there.

Follow-up from #8281.

via @sentrivana.

--

View Session [Sentry]

Co-Authored-By: Ivana Kellyer <131587164+sentrivana@users.noreply.github.com>
Co-Authored-By: Ivana Kellyer <131587164+sentrivana@users.noreply.github.com>

# Conflicts:
#	pyproject.toml
@github-actions

Copy link
Copy Markdown
Contributor

Coverage Results 📊

✅ 139266 passed | ⏭️ 7853 skipped | Total: 147119 | Pass Rate: 94.66% | Execution Time: 445m 42s

📊 Comparison with Base Branch

Metric Change
Total Tests —
Passed Tests —
Failed Tests —
Skipped Tests —

✨ Test counts unchanged from base.

All tests are passing successfully.

✅ Patch coverage is 90.00% (27 of 30 changed executable lines covered; target 80%).
Project statement coverage is 90.21% (down 0.01 percentage points from base (4c1a136) to head (8d08a77)).

Changed files with executable lines (17)
File Patch coverage Changed executable lines
sentry_sdk/ai/_openai_responses_api.py 100.00% 4/4 covered; partial branches: 57, 77, 91
sentry_sdk/integrations/openai.py 100.00% 2/2 covered; partial branches: 601, 680
sentry_sdk/ai/_openai_completions_api.py 100.00% 3/3 covered; partial branches: 85
sentry_sdk/integrations/aws_lambda.py 0.00% 0/1 covered; missed: 78
sentry_sdk/integrations/boto3/_services/bedrock.py 100.00% 1/1 covered; partial branches: 382
sentry_sdk/integrations/gnu_backtrace.py 0.00% 0/1 covered; missed: 38
sentry_sdk/integrations/google_genai/utils.py 100.00% 2/2 covered; partial branches: 290
sentry_sdk/integrations/langchain.py 100.00% 1/1 covered; partial branches: 209
sentry_sdk/integrations/redis/redis_cluster.py 100.00% 1/1 covered; partial branches: 38
sentry_sdk/integrations/starlette.py 0.00% 0/1 covered; missed: 863
sentry_sdk/integrations/stdlib.py 100.00% 3/3 covered; partial branches: 283
sentry_sdk/ai/utils.py 100.00% 1/1 covered
sentry_sdk/data_collection.py 100.00% 1/1 covered
sentry_sdk/integrations/_wsgi_common.py 100.00% 1/1 covered
sentry_sdk/integrations/django/middleware.py 100.00% 1/1 covered
sentry_sdk/integrations/langgraph.py 100.00% 2/2 covered
sentry_sdk/utils.py 100.00% 4/4 covered
Coverage diff
@@            Coverage Diff             @@
##        master     #8292       +/-##
==========================================
- Coverage    90.22%    90.21%    -0.01%
==========================================
  Files          203       203         —
  Tracked lines     27335     27337        +2
  Branches     10246     10246         —
==========================================
  Hits         24660     24660         —
- Misses        2675      2677        +2
  Partials      1559      1559         —

Generated by Coverage Action

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant