Not planned
Description
Bug Report
mypy doesn't catch "reference before assignment" errors
To Reproduce
import os
from typing import Optional
def greet(name: Optional[str]) -> None:
if name:
name_str = f", {name}."
print(f"Hello{name_str}")
name_str = "bar"
def main() -> None:
greet(os.environ.get("NAME"))
if __name__ == "__main__":
main()
Expected Behavior
If the above program is ran without NAME
set, it'll crash:
$ NAME='Jeff' python reference_before_assign.py
Hello, Jeff.
$ python reference_before_assign.py
Traceback (most recent call last):
File "/Users/jeff.rabovsky/git_repos/notes/reference_before_assign.py", line 17, in <module>
main()
File "/Users/jeff.rabovsky/git_repos/notes/reference_before_assign.py", line 13, in main
greet(os.environ.get("NAME"))
File "/Users/jeff.rabovsky/git_repos/notes/reference_before_assign.py", line 9, in greet
print(f"Hello{name_str}")
UnboundLocalError: local variable 'name_str' referenced before assignment
My expectation was that mypy would catch this error.
Actual Behavior
$ mypy --strict reference_before_assign.py
Success: no issues found in 1 source file
Your Environment
- Mypy version used:
0.982
- Mypy command-line flags:
--strict
- Mypy configuration options from
mypy.ini
(and other config files): none - Python version used: 3.10.5
Thanks for your help!
Metadata
Metadata
Assignees
Labels
Projects
Milestone
Relationships
Development
No branches or pull requests
Activity
hauntsaninja commentedon Oct 31, 2022
Thanks, duplicate of #2400 , #686 , etc. Is actively being worked on these days
AlexWaygood commentedon Oct 31, 2022
(Sorry, reopened by accident...)
PeterJCLaw commentedon Nov 29, 2022
Connecting the dots as the linked issues are closed: looks like #4019 tracks this case now.