-
-
Notifications
You must be signed in to change notification settings - Fork 2.8k
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
Error on conditional initialization of Final class variables #10736
Comments
Match-case statements are also affected: https://mypy-play.net/?mypy=master&python=3.11&gist=f0b81218a489585562acd1d8468c2f26 from typing import Final
class Foo:
bar: Final[tuple[int, ...]]
def __init__(self, bar: None | int | tuple[int, ...]) -> None:
match bar:
case None:
self.bar = (-1,)
case int():
self.bar = (bar,) # ✘ Cannot assign to final attribute "bar" [misc]
case tuple():
self.bar = bar # ✘ Cannot assign to final attribute "bar" [misc] |
I have a similar issue / conundrum. https://mypy-play.net/?mypy=master&python=3.11&gist=10f92cdd6e414525c63d25ae251f9afa
|
@merc1031 Try from typing import Final
class Foo:
bar: Final[tuple[int, ...]]
def __init__(self, foo: None | int | tuple[int, ...]) -> None:
bar: tuple[int, ...]
match foo:
case None:
bar = (-1,)
case int():
bar = (foo,)
case tuple():
bar = foo
case tuple():
bar = foo
self.bar = bar |
@randolf-scholz In a larger context it would be to protect from someone modifying bar before the end of the function https://mypy-play.net/?mypy=master&python=3.11&gist=372aa35d3e4f02d35aabe38a3b709473
|
I feel like there's 2 issues here.
if pytorch_is_available:
import torch
pytorch_gpu_is_available: Final = torch.cuda.is_available()
else:
# We only assign once
pytorch_gpu_is_available: Final = False # type: ignore[misc] |
Bug Report
Conditional initialization of a Final class variable is reported as a reassignment error on elif/else branches.
To Reproduce
tmp.py
:Expected Behavior
No errors on the first correct assignment of a final variable regardless of branching.
Actual Behavior
Reported
error: Cannot assign to final attribute "a" [misc]
during the else clause, even though it's only the first assignment of the variable.Your Environment
Mypy version used: 0.910
Mypy command-line flags:
mypy tmp.py
Mypy configuration options from
pyproject.toml
(and other config files):Python version used: 3.9.5
Operating system and version: macOS 11.4
Related
The text was updated successfully, but these errors were encountered: