python / python/mypy

Regression: Type of instance variable narrowed incorrectly after `is not` expression

Open
#20,736 2 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

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

Description

Bug Report

Type of a.foo in the example below is narrowed to what looks like a function type which results in a strange error on the call to append later.

Issue started with https://github.com/python/mypy/commit/ad30be89f146adaae398bd854146952158a53cad @hauntsaninja

To Reproduce


from typing import Any

def f(a: Any, x: Any) -> None:
    if x is not list:
        x = []
    reveal_type(x) # note: Revealed type is "Any"
    if a.foo is not list:
        a.foo = []
    reveal_type(a.foo) # note: Revealed type is "Any | Overload(def [_T] () -> builtins.list[_T`1], def [_T] (typing.Iterable[_T`1]) -> builtins.list[_T`1])"
    a.foo.append(x) # error: Too few arguments for "append" of "list"  [call-arg]

Expected Behavior

a.foo should probably be typed as Any.

Actual Behavior

/Users/psawicki/test.py:6: note: Revealed type is "Any"
/Users/psawicki/test.py:9: note: Revealed type is "Any | Overload(def [_T] () -> builtins.list[_T`1], def [_T] (typing.Iterable[_T`1]) -> builtins.list[_T`1])"
/Users/psawicki/test.py:10: error: Too few arguments for "append" of "list"  [call-arg]

Your Environment

  • Mypy version used: mypy 1.20.0+dev.ad30be89f146adaae398bd854146952158a53cad and up
  • Mypy command-line flags: mypy ~/test.py
  • Mypy configuration options from mypy.ini (and other config files): None
  • Python version used: 3.13.5

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 the supplied reproducer with mypy and compare the revealed types for x and a.foo. Trace the type-narrowing path for the a.foo is not list expression. Done means a.foo remains typed as Any and the later append(x) call no longer reports the shown argument error.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
compilers
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
38/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.