Skip to content

Reference before assignment errors #13976

Not planned
Not planned
@jrab89

Description

@jrab89

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!

Activity

hauntsaninja

hauntsaninja commented on Oct 31, 2022

@hauntsaninja
Collaborator

Thanks, duplicate of #2400 , #686 , etc. Is actively being worked on these days

AlexWaygood

AlexWaygood commented on Oct 31, 2022

@AlexWaygood
Member

(Sorry, reopened by accident...)

PeterJCLaw

PeterJCLaw commented on Nov 29, 2022

@PeterJCLaw
Contributor

Connecting the dots as the linked issues are closed: looks like #4019 tracks this case now.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugmypy got something wrong

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

      Development

      No branches or pull requests

        Participants

        @PeterJCLaw@jrab89@hauntsaninja@AlexWaygood

        Issue actions

          Reference before assignment errors · Issue #13976 · python/mypy