python / python/mypy

Within Annotated[T, x], type errors in x are completely ignored

Open
#16,094 2 comments 2 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

feature topic-runtime-semantics
Dominant language
Python
Stars
20.6k
Forks
3.3k
PR merge metrics
PR metrics pending

Description

Bug Report

mypy ignores the x expression in Annotated[T, x] without type-checking it. Although x has no effect on the typing interpretation of T, the expression x is still code that’s going to be executed at runtime*, so mypy should type-check x (as a separate object) before ignoring it.

(* Although it might not be executed immediately if from __future__ import annotations is in effect, it will be executed when typing.get_type_hints is used, so it’s still important for mypy to check it.)

An example of a real subtle bug that was missed because of this is zulip/zulip#26710.

To Reproduce

from typing import Annotated

def f(p: Annotated[int, 2 + "oops"]) -> None:
    pass

mypy Playground, Pyright playground

Expected Behavior

I expect a type error at 2 + "oops". (Pyright agrees.)

Actual Behavior

mypy finds no errors.

Your Environment

  • Mypy version used: 1.5.1
  • Mypy command-line flags: --strict
  • Mypy configuration options from mypy.ini (and other config files): none
  • Python version used: 3.11.4

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 Annotated[int, 2 + "oops"] example under Python 3.11 with --strict, then trace mypy's handling of Annotated metadata. Done means mypy reports a type error for the metadata expression while preserving the typing interpretation of int.

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

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.