python / python/mypy

mypy doesn't detect use before declaration when on the same line and there is a function call

Open
#15,644 1 comment 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

bug
Dominant language
Python
Stars
20.6k
Forks
3.3k
PR merge metrics
PR metrics pending

Description

Bug Report

mypy doesn't detect use before declaration when:

  • the use is on the same line as the declaration.
  • there is a function call around the used-before-declaration variable

To Reproduce

https://mypy-play.net/?mypy=latest&python=3.11&gist=0d661a8817115f77bed9a655fe21fba1

Expected Behavior
A "Name "i" is not defined" error is raised - since the code fails at runtime.

Actual Behavior
No errors reported

Note:

  • replacing int(...) with a different function (e.g., a user-defined one) also produces the bug as long as the argument of the function is int.
  • Removing the function call (i: int = i) makes mypy properly produce the error "Name "i" is not defined".

Your Environment

  • Mypy version used: 1.4.1
  • Mypy command-line flags: none
  • Mypy configuration options from mypy.ini (and other config files): none
  • Python version used: Python 3.10.6

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with the linked mypy-play reproduction and compare the same-line annotated assignment with and without the function call. Trace how mypy analyzes the annotation and initializer, then add a regression test covering the reported case and verify that it emits a "Name "i" is not defined" error.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
devtools
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.