Skip to content

Python: Fix cross-type literal matching in pattern comparator#6816

Merged
knutwannheden merged 1 commit intomainfrom
fix/python-literal-cross-type-matching
Feb 25, 2026
Merged

Python: Fix cross-type literal matching in pattern comparator#6816
knutwannheden merged 1 commit intomainfrom
fix/python-literal-cross-type-matching

Conversation

@knutwannheden
Copy link
Copy Markdown
Contributor

Summary

  • Strengthens _compare_literal in PatternMatchingComparator to prevent cross-type false positives
  • Adds value type checking before value equality (type(pattern.value) != type(target.value))
  • Falls back to value_source comparison when both values are None (disambiguates None keyword from ... and unicode-escaped literals which all store value=None)
  • Prevents patterns like {x} == None from incorrectly matching byte string comparisons like x == b""

Context

Running PythonBestPractices across 12 open-source projects showed NoneCompare and RemoveNoneFromDefaultGet incorrectly transforming byte string literals:

  • assert response.content == b"Hello"assert response.content is None
  • body += message.get("body", b"")body += message.get("body")

Test plan

  • 7 new cross-type literal matching tests (TestCrossTypeLiteralMatching)
  • All 1027 existing framework tests pass
  • All 717 recipe tests pass

Literal comparison (`_compare_literal`) previously only checked value
equality, which could produce false positives when different literal
types share the same internal representation (e.g., `None`, `...`, and
unicode-escaped strings all store `value=None`).

The fix adds two-level comparison:
1. Reject immediately when value types differ (NoneType vs bytes, etc.)
2. Fall back to `value_source` comparison when both values are `None`
   to distinguish `None` from `...` and unicode-escaped literals.

This prevents patterns like `{x} == None` from matching byte string
comparisons like `x == b""`.
@github-project-automation github-project-automation Bot moved this to In Progress in OpenRewrite Feb 25, 2026
@knutwannheden knutwannheden merged commit fc90cc8 into main Feb 25, 2026
1 check passed
@github-project-automation github-project-automation Bot moved this from In Progress to Done in OpenRewrite Feb 25, 2026
@knutwannheden knutwannheden deleted the fix/python-literal-cross-type-matching branch February 25, 2026 18:01
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Archived in project

Development

Successfully merging this pull request may close these issues.

1 participant