python / python/mypy

False negative with a constrained generic type in the presence of `Any`

Open
#9,186 1 comment 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

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

Description

from typing import Any, AnyStr
def foo(arg1: AnyStr, arg2: AnyStr) -> None: ...
bar: Any = ""
foo(1, "") # Error correctly reported
foo(b"", bar) # No error (correct)
foo(1, bar) # No error (false negative)

In the presence of Any, I would expect mypy to allow any of the values of the constraint (in this case, str or bytes), but not any arbitrary type.

Playground link: https://mypy-play.net/?mypy=latest&python=3.8&flags=strict&gist=6970b49fa90d7767b0ef26c9f977e182

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 reproducing the three calls in the linked mypy playground with strict mode, then trace constrained generic inference when one argument has type Any. Done means foo(1, bar) is rejected while the valid str/bytes cases remain accepted, with a regression test covering the behavior.

Written by the indexing model from the issue text.

Assessment

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

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.