Skip to content

Fix #19507 Prevent final reassignment in match case #19496

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Conversation

omerhadari
Copy link
Contributor

@omerhadari omerhadari commented Jul 24, 2025

Fixes #19507

This PR adds a check to prevent reassignment of final variables in a match statement.

Currently, the following passes without an error:

from typing import Final
FOO: Final = 8

a = 10

match a:
    case FOO:
        pass
print(FOO)  # FOO is reassigned, prints 10

MyPy already checks that the type of FOO isn't changed if used like this. I added a check in the same place that makes sure it's not Final either.

Since this tests the match syntax, I put the test where I did. If it's not the appropriate place for it I will move it as instructed :)

@omerhadari omerhadari force-pushed the prevent-final-reassignment-in-match-case branch 2 times, most recently from 5378cb1 to 421adbe Compare July 24, 2025 14:04

This comment has been minimized.

@omerhadari omerhadari force-pushed the prevent-final-reassignment-in-match-case branch from 421adbe to 7b6ad2d Compare July 25, 2025 11:20
@omerhadari omerhadari force-pushed the prevent-final-reassignment-in-match-case branch from 7b6ad2d to e2c9e6b Compare July 25, 2025 11:21
Copy link
Contributor

According to mypy_primer, this change doesn't affect type check results on a corpus of open source code. ✅

@omerhadari omerhadari changed the title Prevent final reassignment in match case Fix #19507 Prevent final reassignment in match case Jul 25, 2025
Copy link
Collaborator

@sterliakov sterliakov left a comment

Choose a reason for hiding this comment

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

Great, thanks!

Copy link
Collaborator

@hauntsaninja hauntsaninja left a comment

Choose a reason for hiding this comment

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

Thank you!

@hauntsaninja hauntsaninja merged commit c6b40df into python:master Jul 27, 2025
20 checks passed
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.

Assignment to final variables is allowed in a match statement
3 participants