python / python/mypy

Wrong type hint after unpacking/swapping

Open
#9,731 3 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

bug priority-1-normal
Dominant language
Python
Stars
20.6k
Forks
3.3k
PR merge metrics
PR metrics pending

Description

Bug Report

Unpacking a tuple in the below scenario results in wrong assumed types.

To Reproduce


import typing as t

def spam(val: t.Union[t.Type, None] = None) -> None:

  def eggs(type_: t.Type) -> None:
    pass

  reveal_type(val)
  if isinstance(val, type):
    reveal_type(val)
    val, foo = None, val
    reveal_type(val)
    reveal_type(foo)
    return eggs(foo)

Expected Behavior

After the line val, foo = None, val, I would expect that

  1. val has type None (ok)
  2. foo has type Type[Any]
  3. the call to eggs() passes

Actual Behavior

$ mypy test.py 
test.py:9: note: Revealed type is 'Union[Type[Any], None]'
test.py:11: note: Revealed type is 'Type[Any]'
test.py:13: note: Revealed type is 'None'
test.py:14: note: Revealed type is 'None'
test.py:15: error: Argument 1 to "eggs" has incompatible type "None"; expected "Type[Any]"
Found 1 error in 1 file (checked 1 source file)

This does not match with my expectations 2 and 3.

Your Environment

Python 3.9
Mypy 0.790
MacOS 10.14.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 by running the reported Python example with mypy and compare the revealed types before and after val, foo = None, val. Investigate the type-checker's handling of tuple unpacking and narrowed variables. Done means foo remains Type[Any] and the call to eggs(foo) passes without an 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
Clearly specified
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.