python / python/mypy

mypy does not understand that in multiple assignment any involved expressions keep their type until the end of all assignments

Open
#19,891 0 comments 1 reaction 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

Example:

x: tuple[int, int]|int = (1, 2)
if isinstance(x, tuple):
    x, y = x[0], x[1]

main.py:3: error: Value of type "int" is not indexable [index]
Found 1 error in 1 file (checked 1 source file)

Another example I ran across (in an experimental version of checker.py I'm working on) involved two different objects, no tuples:

mypy/checker.py:7737: error: "str" has no attribute   "code"; maybe "encode"?  [attr-defined]
                msg, code = msg.value, msg.code
                                       ^~~~~~~~

These work at runtime so it's a problem with mypy.

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 by running mypy on the two examples in the issue, using main.py for the tuple case and the reported checker.py line 7737 for the second case. Trace how narrowing is preserved across multiple assignment, then verify that both examples type-check without weakening unrelated diagnostics.

Written by the indexing model from the issue text.

Assessment

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

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.