python / python/mypy

False positive on `_` (underscore) as variable name with `disallow-any-expr`

Open
#15,253 11 comments 3 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

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

Description

Bug Report

mypy gives a false positive with variable _ (underscore) under certain circumstances (see repro).

To Reproduce

https://mypy-play.net/?mypy=latest&python=3.8&flags=disallow-any-expr&gist=bca874771ec5eba30815133c9bbd4ab7

from typing import Callable, Tuple, TypeVar

T = TypeVar("T")

def wrapper(fn: Callable[[], T]) -> Tuple[T, float]:
    return fn(), 1

def wrapper2(fn: Callable[[], T]) -> T:
    return fn()

def func() -> int:
    x = 1
    return x

def a() -> None:
    _, c = wrapper(func)  # <- 2 errors here
    b, c = wrapper(func)
    _ = wrapper2(func)

_, c = wrapper(func)

Interestingly only one line causes the error:

  • statement inside a function
  • variable named _
  • wrapper returns a tuple

Actual Behavior

main.py:16: error: Expression type contains "Any" (has type "Tuple[Any, float]")  [misc]
main.py:16: error: Expression has type "Any"  [misc]
Found 2 errors in 1 file (checked 1 source file)

Your Environment

(environment of the playground)

  • Mypy version used: 1.3.0
  • Mypy command-line flags: --disallow-any-expr
  • Python version used: 3.8 (same for other versions)

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 run it using Python 3.8 with --disallow-any-expr, checking the diagnostic on the underscore tuple assignment inside a function. Trace the type-checking entry point for tuple unpacking and underscore variables; done means this case produces no false positives while the other assignments retain their expected diagnostics.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
devtools
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 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.