python / python/mypy

Unexpected order dependence when assigning to multiple targets

Open
#19,553 0 comments 1 reaction 0 assignees View on GitHub

Nobody has claimed this yet.

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

Description

Bug Report

When assigning an empty generic type to both a typed target and a new not-yet-typed target, typed targets to the left of the not-yet-typed target do not appear to be considered when determining whether or not the not-yet-typed target needs an explicit type annotation.

To Reproduce

typed_list: list[int]

untyped_target = typed_list = [] # All good

typed_list = another_untyped_target = [] # var-annotated error

https://mypy-play.net/?mypy=latest&python=3.12&gist=7d4ec0816e1ea43a3bb6def3f55b3296

The same problem occurs when the typed target is a structured target like self.attr_name or container[key].

Expected Behavior

When assigning to both a structured target and a new local variable name, I prefer to put the structured target first.
I expected to be able to do that without having to put an explicit annotation on the local variable name.

Actual Behavior

Mypy reports the following error when the untyped target is to the right of

error: Need type annotation for "another_untyped_target" (hint: "another_untyped_target: list[<type>] = ...")  [var-annotated]

Your Environment

Local environment where the issue was originally noted:

  • Mypy version used: 1.16.1
  • Mypy command-line flags: --strict
  • Python version used: 3.11

Simplified example comes from the MyPy Playground link above (Python 3.12, MyPy 1.17.0)

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

Reproduce the assignment-ordering examples in the linked mypy-playground case using mypy 1.16.1 or later with --strict. Trace how multiple-target assignments infer types for local and structured targets; done means the untyped target is accepted when the typed target appears first, without regressing the opposite ordering.

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
45/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.