Skip to content

Admit that Final variables are never redefined #19083

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

Merged
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
4 changes: 4 additions & 0 deletions mypy/checker.py
Original file line number Diff line number Diff line change
Expand Up @@ -1557,6 +1557,10 @@ def is_var_redefined_in_outer_context(self, v: Var, after_line: int) -> bool:
Note that this doesn't do a full CFG analysis but uses a line number based
heuristic that isn't correct in some (rare) cases.
"""
if v.is_final:
# Final vars are definitely never reassigned.
return False

outers = self.tscope.outer_functions()
if not outers:
# Top-level function -- outer context is top level, and we can't reason about
Expand Down
22 changes: 22 additions & 0 deletions test-data/unit/check-final.test
Original file line number Diff line number Diff line change
Expand Up @@ -1250,3 +1250,25 @@ def check_final_init() -> None:
new_instance = FinalInit()
new_instance.__init__()
[builtins fixtures/tuple.pyi]

[case testNarrowingOfFinalPersistsInFunctions]
from typing import Final, Union

def _init() -> Union[int, None]:
return 0

FOO: Final = _init()

class Example:

if FOO is not None:
reveal_type(FOO) # N: Revealed type is "builtins.int"

def fn(self) -> int:
return FOO

if FOO is not None:
reveal_type(FOO) # N: Revealed type is "builtins.int"

def func() -> int:
return FOO