Skip to content

Conversation

@visz11
Copy link
Collaborator

@visz11 visz11 commented Dec 24, 2025

CodeAnt-AI Description

Fix match subject type inference for complex expressions

What Changed

  • When a match's subject is a complex expression (calls, attributes, arithmetic, dict/item access, unary ops, await, etc.), the checker now creates a synthetic, unique named subject so pattern capture variables are inferred correctly and exhaustivity/unreachability checks are accurate.
  • Primitive literals and already-named expressions are left as-is; inline collection literals are now allowed for inference too.
  • Inferred type mappings for the synthetic subject are propagated back to the original subject expression when available.
  • Tests updated: one previously xfailed test is enabled and multiple new match-case tests were added to cover function calls, attribute access, operations, dict item access, and literal edge cases.

Impact

✅ Clearer pattern capture types in match statements
✅ Fewer false "unreachable" match branches
✅ More accurate reveal_type results in match tests

💡 Usage Guide

Checking Your Pull Request

Every time you make a pull request, our system automatically looks through it. We check for security issues, mistakes in how you're setting up your infrastructure, and common code problems. We do this to make sure your changes are solid and won't cause any trouble later.

Talking to CodeAnt AI

Got a question or need a hand with something in your pull request? You can easily get in touch with CodeAnt AI right here. Just type the following in a comment on your pull request, and replace "Your question here" with whatever you want to ask:

@codeant-ai ask: Your question here

This lets you have a chat with CodeAnt AI about your pull request, making it easier to understand and improve your code.

Example

@codeant-ai ask: Can you suggest a safer alternative to storing this secret?

Preserve Org Learnings with CodeAnt

You can record team preferences so CodeAnt AI applies them in future reviews. Reply directly to the specific CodeAnt AI suggestion (in the same thread) and replace "Your feedback here" with your input:

@codeant-ai: Your feedback here

This helps CodeAnt AI learn and adapt to your team's coding style and standards.

Example

@codeant-ai: Do not flag unused imports.

Retrigger review

Ask CodeAnt AI to review the PR again, by typing:

@codeant-ai: review

Check Your Repository Health

To analyze the health of your code repository, visit our dashboard at https://app.codeant.ai. This tool helps you identify potential issues and areas for improvement in your codebase, ensuring your repository maintains high standards of code health.

Summary by CodeRabbit

  • New Features

    • Enhanced type checking for Python 3.10 match statements with improved handling of complex patterns including function calls, attributes, operations, and dictionary items.
  • Tests

    • Expanded test coverage for pattern matching scenarios, including new cases for named tuples, literals, and various match statement constructs.

✏️ Tip: You can customize this high-level summary in your review settings.

@codeant-ai
Copy link

codeant-ai bot commented Dec 24, 2025

CodeAnt AI is reviewing your PR.


Thanks for using CodeAnt! 🎉

We're free for open-source projects. if you're enjoying it, help us grow by sharing.

Share on X ·
Reddit ·
LinkedIn

Copy link

@greptile-apps greptile-apps bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Your free trial has ended. If you'd like to continue receiving code reviews, you can add a payment method here.

@coderabbitai
Copy link

coderabbitai bot commented Dec 24, 2025

Note

Other AI code review bot(s) detected

CodeRabbit has detected other AI code review bot(s) in this pull request and will avoid duplicating their findings in the review comments. This may lead to a less comprehensive review.

📝 Walkthrough

Walkthrough

This change enhances mypy's match statement type checking by introducing a unique ID generator in the TypeChecker class to create deterministic, collision-free dummy names. A new public method new_unique_dummy_name() and a private helper _make_named_statement_for_match() centralize the logic for synthesizing named subjects in pattern matching, replacing ad-hoc string construction with a systematic approach.

Changes

Cohort / File(s) Summary
TypeChecker enhancement
mypy/checker.py
Added _unique_id: int field for tracking unique dummy names. Introduced public method new_unique_dummy_name(namespace: str) to generate guaranteed-unique identifiers. Added private helper _make_named_statement_for_match() to construct or reuse synthetic named subjects. Modified visit_match_stmt() to leverage the new helper for pattern-type propagation and exhaustivity checks.
Pattern matching test expansion
test-data/unit/check-python310.test
Renamed existing xfail test case testMatchCapturePatternFromAsyncFunctionReturningUnion. Added six new test blocks: testMatchFunctionCall, testMatchAttribute, testMatchOperations, testMatchDictItem, testMatchLiteralValuePathological, and testMatchNamedTupleSequence to cover function calls, attributes, operations, dictionary access, literal values, and NamedTuple patterns in match statements.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Poem

🐰 A tale of dummies, unique and true,
No more collisions in the matching queue,
With IDs spinning and helpers at hand,
Pattern matching stands proud and grand!
Tests multiply like carrots in spring, 🥕
Exhaustivity checks shall truly sing!

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 44.44% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (2 passed)
Check name Status Explanation
Title check ✅ Passed The title references a clone bugfix related to synthetic named expressions in match statements, which directly corresponds to the main changes: introducing unique dummy name generation and a helper for named subjects in match pattern matching.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch clone-bugfix/st-synthetic-named-expr-in-match

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@gemini-code-assist
Copy link

Summary of Changes

Hello @visz11, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request significantly enhances MyPy's type checking capabilities for match statements, particularly when the subject of the match is a complex expression rather than a simple variable or literal. By introducing a robust mechanism to create and manage synthetic named expressions for these complex subjects, the changes improve type inference and exhaustiveness checking, ensuring more accurate and reliable static analysis for pattern matching in Python 3.10+.

Highlights

  • Refactored Match Statement Subject Handling: The logic for creating synthetic named expressions for complex match subjects has been extracted into a new dedicated helper method, _make_named_statement_for_match, improving code organization and maintainability within visit_match_stmt.
  • Improved Type Inference for Complex Match Subjects: A mechanism has been introduced to generate unique temporary names for non-literal match subjects (e.g., function calls, attribute access, binary operations). This allows MyPy to perform more accurate type narrowing and exhaustiveness checking in these complex scenarios.
  • Enhanced Type Information Propagation: Type inference results derived from the synthetic named expressions are now correctly propagated back to the original complex match subjects within the pattern_map and else_map, ensuring that the inferred types are applied consistently.
  • Expanded Test Coverage: New test cases have been added to validate the correct type inference for various complex match statement subjects, including function calls, attribute access, different binary operations, and dictionary item access, confirming the effectiveness of the bugfix.
  • Fixed Previously Failing Test: A test case related to async functions returning unions within match statements, previously marked as xfail, is now expected to pass, indicating a resolution to a known issue.

🧠 New Feature in Public Preview: You can now enable Memory to help Gemini Code Assist learn from your team's feedback. This makes future code reviews more consistent and personalized to your project's style. Click here to enable Memory in your admin console.

Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

@codeant-ai codeant-ai bot added the size:L This PR changes 100-499 lines, ignoring generated files label Dec 24, 2025
@codeant-ai
Copy link

codeant-ai bot commented Dec 24, 2025

Sequence Diagram

The PR creates synthetic (unique) named expressions for complex match subjects, uses them when inferring pattern capture types, and copies inferred constraints back to the original subject so narrowing works for attribute/item/call subjects. This diagram shows the main success path added by the changes.

sequenceDiagram
    participant AST as MatchStmt (AST)
    participant Checker as TypeChecker
    participant Pattern as PatternChecker

    AST->>Checker: visit_match_stmt(s)
    Checker->>Checker: _make_named_statement_for_match(s) -> create or reuse dummy NameExpr for subject
    Checker->>Checker: evaluate subject type (expr_checker.accept)
    Checker->>Pattern: infer patterns using named_subject
    Pattern-->>Checker: pattern_map keyed by named_subject (and captures)
    Checker->>Checker: copy constraints from named_subject -> original s.subject; propagate and push typemaps
    Checker->>AST: type-check match arms using pushed typemaps (accept bodies)
Loading

Generated by CodeAnt AI

@refacto-visz
Copy link

refacto-visz bot commented Dec 24, 2025

Refacto PR Summary

Enhanced match statement type inference by improving synthetic named expression handling for complex subjects. The implementation creates unique dummy variables for non-literal match subjects and propagates type constraints between original and synthetic expressions to enable better type narrowing and exhaustivity checking.

Key Changes:

  • Refactored match statement subject handling to support broader expression types beyond just function calls
  • Added unique ID generation system to prevent naming conflicts in synthetic variables
  • Implemented type constraint propagation between original subjects and their synthetic counterparts
  • Enhanced pattern matching to preserve primitive literals while creating named expressions for complex subjects

Change Highlights

Click to expand
  • mypy/checker.py: Added _unique_id counter and new_unique_dummy_name() method for collision-free naming
  • mypy/checker.py: Refactored visit_match_stmt() to use new _make_named_statement_for_match() helper
  • mypy/checker.py: Enhanced type constraint propagation between synthetic and original expressions in pattern maps
  • mypy/checker.py: Expanded expression preservation logic to include all primitive literals (int, str, bytes, float, complex, ellipsis)

Sequence Diagram

sequenceDiagram
    participant MS as MatchStmt
    participant TC as TypeChecker
    participant NE as NamedExpr
    participant PM as PatternMatcher
    
    MS->>TC: visit_match_stmt(complex_subject)
    TC->>TC: _make_named_statement_for_match()
    alt Complex Expression
        TC->>TC: new_unique_dummy_name("match")
        TC->>NE: Create synthetic NameExpr
        TC->>MS: Store as subject_dummy
    else Primitive Literal
        TC->>TC: Return original subject
    end
    TC->>PM: Process patterns with named_subject
    PM->>TC: Return pattern_map, else_map
    TC->>TC: Propagate constraints to original subject
    TC-->>MS: Complete type inference
Loading

Testing Guide

Click to expand
  1. Function Call Matching: Test match fn(): where fn() returns union types, verify type narrowing works correctly
  2. Attribute Access: Test match obj.attr: with union-typed attributes, confirm exhaustivity checking
  3. Complex Expressions: Test match -x: and match 1 + 2: operations, verify synthetic naming doesn't conflict
  4. Literal Preservation: Test match 42: and match "string": to ensure primitives bypass synthetic naming
  5. Nested Match Statements: Test multiple match statements to verify unique ID generation prevents collisions

@refacto-visz
Copy link

refacto-visz bot commented Dec 24, 2025

Refacto is reviewing this PR. Please wait for the review comments to be posted.

Copy link

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request introduces a bugfix for type checking match statements with complex subjects, such as function calls or attribute access. The core idea is to create a synthetic named expression for these complex subjects, allowing the existing type narrowing logic to function correctly. The changes are well-implemented, and the new helper methods _make_named_statement_for_match and new_unique_dummy_name improve code organization. The added tests are comprehensive and cover a good range of cases.

I have one suggestion to improve maintainability and performance by moving a constant tuple to the class level.

Comment on lines +5509 to +5520
expressions_to_preserve = (
# Already named - we should infer type of it as given
NameExpr,
AssignmentExpr,
# Primitive literals - their type is known, no need to name them
IntExpr,
StrExpr,
BytesExpr,
FloatExpr,
ComplexExpr,
EllipsisExpr,
)

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

For better performance and maintainability, consider defining expressions_to_preserve as a class-level constant on TypeChecker, since it's a constant value. This avoids recreating the tuple on every call to _make_named_statement_for_match.

For example:

class TypeChecker(...):
    _MATCH_SUBJECT_EXPRESSIONS_TO_PRESERVE: Final = (
        NameExpr,
        AssignmentExpr,
        # ...
    )

    # ...

    def _make_named_statement_for_match(self, s: MatchStmt) -> Expression:
        subject = s.subject
        if isinstance(subject, self._MATCH_SUBJECT_EXPRESSIONS_TO_PRESERVE):
            return subject
        # ...

@codeant-ai
Copy link

codeant-ai bot commented Dec 24, 2025

Nitpicks 🔍

🔒 No security issues identified
⚡ Recommended areas for review

  • Large Test Additions
    A large block of new test cases was added (multiple match-related cases). These introduce many new expectations (unreachable errors, reveal_type expectations, and flags). Validate each added test's expected diagnostics and that fixtures/flags included are correct to avoid spurious failures or false positives in CI.

  • Test Marker Change
    The async capture-pattern test header was changed from an xfail variant to a regular case. Confirm this was intentional — it will change CI expectations (the test will now be considered passing instead of expected-failing). Verify the runtime/test harness doesn't require the previous xfail marker and that the test actually passes on the target platforms.

  • Fixture / Flag Consistency
    The additions include multiple repeated fixture and flag declarations (e.g. builtins fixtures and '--warn-unreachable' flags). Ensure fixtures are the intended versions and that repeated declarations don't create inconsistent test contexts or mask intended errors.

@codeant-ai
Copy link

codeant-ai bot commented Dec 24, 2025

CodeAnt AI finished reviewing your PR.

@refacto-visz
Copy link

refacto-visz bot commented Dec 24, 2025

Code Review: Match Statement Type Inference Enhancement

PR Confidence Score: 🟨 4 / 5

👍 Well Done
Unique Name Generation

Counter-based dummy name generation effectively prevents variable collisions in match statements

Expression Type Preservation

Comprehensive literal type handling maintains correct type inference patterns for complex expressions

📁 Selected files for review (2)
  • mypy/checker.py
  • test-data/unit/check-python310.test
🎯 Custom Instructions
❌ Unapplied Instructions
Organization Guidelines

Reason: Your set path patterns [src/, config/] don't match any selected files for review; Your set extension patterns [.java] don't match any selected files for review

📝 Additional Comments
mypy/checker.py (6)
Pattern Map Validation

Type map propagation logic assumes pattern_map[named_subject] and else_map[named_subject] contain valid type information without validation. If type inference fails or produces invalid types, this could propagate incorrect type constraints.

Standards:

  • Data-Validation-Input-Checking
  • Type-Safety-Constraint-Validation
Expression Tuple Maintenance

Hardcoded expression type tuple requires manual maintenance when new expression types are added. This creates a maintenance burden where developers must remember to update this list.

Standards:

  • Clean-Code-Class-Organization
  • SOLID-OCP
  • Maintainability-Quality-Configuration
Context References
  • filepath -> mypy/nodes.py
  • definition -> ComplexExpr - Complex literal expression type confirms tuple completeness
Redundant Type Mapping

Dictionary lookups and assignments executed for each match pattern even when maps may be empty or subject already processed. The conditional checks prevent unnecessary operations but still perform map lookups.

Standards:

  • ISO-IEC-25010-Performance-Efficiency-Resource-Utilization
  • Optimization-Pattern-Conditional-Processing
Expression Type Checking

Multiple isinstance checks against tuple of expression types performed for each match statement. The tuple comparison requires iterating through all expression types until match found.

Standards:

  • ISO-IEC-25010-Performance-Efficiency-Time-Behavior
  • Algorithmic-Complexity-Constant-Time-Lookup
Method Responsibility Clarity

Method handles both decision logic (whether to preserve expression) and creation logic (dummy name generation). This mixed responsibility pattern makes the method harder to test and modify independently.

Standards:

  • SOLID-SRP
  • Clean-Code-Functions
  • Maintainability-Quality-Cohesion
Context References
  • filepath -> mypy/nodes.py
  • definition -> MatchStmt - subject_dummy field confirms method's dual responsibility
Counter Overflow Protection

Unique ID counter increments indefinitely without overflow protection. In long-running type checking sessions with many match statements, integer overflow could theoretically cause name collisions.

Standards:

  • Algorithm-Correctness-Bounds-Checking
  • Logic-Verification-State-Management
🧰 Additional context used
mypy/checker.py (13)
mypy/checker.py (2)
  • _make_named_statement_for_match (5506-5534)
  • new_unique_dummy_name (7915-7919)
mypy/nodes.py (11)
  • MatchStmt (1640-1667)
  • Expression (201-207)
  • NameExpr (1875-1895)
  • AssignmentExpr (2074-2087)
  • IntExpr (1696-1710)
  • StrExpr (1719-1733)
  • BytesExpr (1740-1763)
  • FloatExpr (1766-1780)
  • ComplexExpr (1783-1797)
  • EllipsisExpr (1800-1806)
  • Var (973-1118)

CallExpr,
ClassDef,
ComparisonExpr,
ComplexExpr,
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Missing ComplexExpr Import

Code adds ComplexExpr to imports and uses it in expressions_to_preserve tuple, but the import may not be properly resolved. This could cause NameError at runtime when type checker processes complex number literals in match statements.

    ComplexExpr,
Commitable Suggestion
Suggested change
ComplexExpr,
ComplexExpr,
Standards
  • Type-Safety-Import-Resolution
  • API-Contract-Consistency
Context References
  • mypy/nodes.py - ComplexExpr class definition confirms it exists and should be importable


def new_unique_dummy_name(self, namespace: str) -> str:
"""Generate a name that is guaranteed to be unique for this TypeChecker instance."""
name = f"dummy-{namespace}-{self._unique_id}"
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Magic String Pattern

Hardcoded string format creates coupling between dummy name generation and string parsing logic. Changes to naming convention require coordinated updates across multiple locations.

Standards
  • Clean-Code-Functions
  • SOLID-OCP
  • Maintainability-Quality-Coupling
Context References
  • filepath - ``
  • definition - ``

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (3)
test-data/unit/check-python310.test (1)

2661-2671: Question: Is Literal[0]? the expected type here?

The test expects reveal_type(i) to show Literal[0]?. The ? suffix typically indicates an optional/nullable type, which seems unusual for matching against a literal 0. Can you confirm this is the intended behavior for this edge case?

If this is indeed the correct expected output, consider adding a comment explaining why the type is Literal[0]? rather than just Literal[0] to help future maintainers understand this pathological case.

mypy/checker.py (2)

5420-5458: Match subject aliasing via synthetic NameExpr looks sound; consider copying source location onto the dummy

The new _make_named_statement_for_match helper plus named_subject usage in visit_match_stmt nicely centralize the “synthetic subject name” logic:

  • Simple/“already named” or literal subjects (NameExpr, AssignmentExpr, primitive literal exprs including ComplexExpr and EllipsisExpr) are preserved, avoiding unnecessary indirection.

  • Complex subjects now get a cached NameExpr stored in MatchStmt.subject_dummy, ensuring we reuse the same Expression object across pattern passes and when building pattern_map/else_map.

  • The extra remapping

    if pattern_map and named_subject in pattern_map:
        pattern_map[s.subject] = pattern_map[named_subject]
    if else_map and named_subject in else_map:
        else_map[s.subject] = else_map[named_subject]

    bridges from the synthetic NameExpr back to the original subject expression so downstream logic (including propagate_up_typemap_info and later binder state) still sees constraints keyed by the real subject as well. This avoids losing information on the original expression while giving you a stable key for the synthetic one.

One small improvement you might want (mainly for debugging and error reporting) is to copy source location from the original subject onto the synthetic NameExpr and its backing Var, so any diagnostics that happen to mention this dummy node don’t show line -1:

Optional tweak to preserve subject location on the dummy name
 def _make_named_statement_for_match(self, s: MatchStmt) -> Expression:
@@
-        else:
-            # Create a dummy subject expression to handle cases where a match statement's subject
-            # is not a literal value. This lets us correctly narrow types and check exhaustivity
-            # This is hack!
-            name = self.new_unique_dummy_name("match")
-            v = Var(name)
-            named_subject = NameExpr(name)
-            named_subject.node = v
-            s.subject_dummy = named_subject
-            return named_subject
+        else:
+            # Create a dummy subject expression to handle cases where a match statement's subject
+            # is not a literal value. This lets us correctly narrow types and check exhaustivity.
+            name = self.new_unique_dummy_name("match")
+            v = Var(name)
+            v.line = subject.line
+            named_subject = NameExpr(name)
+            named_subject.set_line(subject)
+            named_subject.node = v
+            s.subject_dummy = named_subject
+            return named_subject

This is purely optional; the existing behavior is functionally correct.

Also applies to: 5506-5534


7915-7919: new_unique_dummy_name helper is fine; could be reused if more synthetic names are needed

The new_unique_dummy_name(self, namespace: str) helper is a clean, low‑overhead way to generate reproducible dummy identifiers (dummy-<ns>-<n>) per TypeChecker instance. It’s appropriately narrow in scope and decoupled from symbol tables, which is fine for non‑declared internal names like the synthetic match subjects.

If you later find yourself needing symbol‑table‑aware uniqueness (e.g. for fake TypeInfos), you could consider layering this over gen_unique_name and a relevant SymbolTable, but that’s not necessary for the current match‑subject use case.

📜 Review details

Configuration used: defaults

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 380cb8d and ded98cb.

📒 Files selected for processing (2)
  • mypy/checker.py
  • test-data/unit/check-python310.test
🧰 Additional context used
🧬 Code graph analysis (1)
mypy/checker.py (1)
mypy/nodes.py (23)
  • ComplexExpr (1783-1797)
  • MatchStmt (1640-1667)
  • Expression (201-207)
  • NameExpr (1875-1895)
  • AssignmentExpr (2074-2087)
  • IntExpr (1696-1710)
  • StrExpr (1719-1733)
  • BytesExpr (1740-1763)
  • FloatExpr (1766-1780)
  • EllipsisExpr (1800-1806)
  • name (234-235)
  • name (353-354)
  • name (532-533)
  • name (571-577)
  • name (809-810)
  • name (907-908)
  • name (1068-1069)
  • name (2287-2288)
  • name (2572-2573)
  • name (3205-3207)
  • name (3752-3753)
  • name (3864-3865)
  • Var (973-1118)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (15)
  • GitHub Check: Type check our own code (py39-ubuntu)
  • GitHub Check: Test suite with py39-ubuntu, mypyc-compiled
  • GitHub Check: Formatting and code style with Black + ruff
  • GitHub Check: Test suite with py312-ubuntu, mypyc-compiled
  • GitHub Check: Test suite with py310-ubuntu
  • GitHub Check: Test suite with py313-ubuntu, mypyc-compiled
  • GitHub Check: Type check our own code (py39-windows-64)
  • GitHub Check: Test suite with py39-windows-64
  • GitHub Check: Test suite with py311-ubuntu, mypyc-compiled
  • GitHub Check: Run mypy_primer (2)
  • GitHub Check: Test mypyc suite with 32-bit Python
  • GitHub Check: Run mypy_primer (1)
  • GitHub Check: Run mypy_primer (4)
  • GitHub Check: Run mypy_primer (0)
  • GitHub Check: Run mypy_primer (3)
🔇 Additional comments (7)
test-data/unit/check-python310.test (5)

1305-1305: Good: Previously failing test now passes.

The removal of the -xfail suffix confirms this test case now passes after the bugfix for synthetic named expressions in match statements. This validates that match statements on async function calls returning unions are now handled correctly.


2589-2601: Well-designed test for function call match subjects.

This test case properly validates that matching on a function call result correctly narrows types in each branch and detects unreachable code when all union alternatives are exhausted.


2602-2615: LGTM: Attribute access match subject test.

This test case validates that matching on attribute access expressions correctly generates synthetic named expressions and performs proper type narrowing.


2616-2644: Comprehensive test for operation match subjects.

This test case thoroughly validates matching on various operation types (unary, binary, comparison) and confirms that synthetic named expressions work correctly for these complex subjects.


2645-2659: LGTM: Dictionary item match subject test.

This test case validates that matching on dictionary subscript expressions correctly handles synthetic named expressions and type narrowing.

mypy/checker.py (2)

70-70: Importing ComplexExpr is consistent with new match-subject handling

Bringing ComplexExpr into this module so it can be treated as a primitive literal in _make_named_statement_for_match aligns with how other literal expr nodes are handled. No change needed.


354-356: Per‑instance _unique_id counter is correctly scoped and initialized

Using an instance field _unique_id plus initializing it to 0 in __init__ gives deterministic, collision‑free dummy names within a TypeChecker and works fine with the incremental reset() flow (which reuses existing subject_dummy nodes instead of regenerating them).

Also applies to: 421-421

@github-actions
Copy link

Diff from mypy_primer, showing the effect of this PR on open source code:

core (https://github.com/home-assistant/core)
- homeassistant/components/asuswrt/bridge.py:114: error: Incompatible return value type (got "dict[str, object]", expected "dict[str, float | str | None] | dict[str, float]")  [return-value]

discord.py (https://github.com/Rapptz/discord.py)
- discord/ext/commands/hybrid.py:510: error: Overlap between argument names and ** TypedDict items: "name", "description"  [misc]
+ discord/ext/commands/hybrid.py:510: error: Overlap between argument names and ** TypedDict items: "description", "name"  [misc]
- discord/ext/commands/hybrid.py:631: error: Overlap between argument names and ** TypedDict items: "name", "description"  [misc]
+ discord/ext/commands/hybrid.py:631: error: Overlap between argument names and ** TypedDict items: "description", "name"  [misc]

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

Labels

size:L This PR changes 100-499 lines, ignoring generated files

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants