python / python/mypy

mypy accepts invalid PEP 604 syntax with forward reference

Open
#14,397 1 comment 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

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

Description

Bug Report

PEP 604 introduced the | syntax, however it's not entirely equivalent to the Union syntax. Forward references with | are not supported and result in TypeErrors TypeError: unsupported operand type(s) for |: 'type' and 'str'. Mypy doesn't warn the user about this and accepts | with forward references.

To Reproduce

T = list[int | "T"]

Playground

Expected Behavior

Some kind of error telling me that this syntax is not supported.

Actual Behavior

No errors reported.

Your Environment

  • Mypy version used: 0.991
  • Mypy command-line flags: --strict or no flags, doesn't matter
  • Mypy configuration options from mypy.ini (and other config files): None
  • Python version used: 3.11

I originally raised this as a discussion in pyright repo. And since then pyright has implemented https://github.com/microsoft/pyright/commit/6eb846709f4fec0180593f3e89f1dd5b20f41956 to detect this incorrect usage of | (available in release 1.1.285). I have to admit that documentation on this is a bit murky as I was expecting | to be equivalent to Union and I wasn't the only one, see https://github.com/python/cpython/issues/90015. From what I can gather in this CPython issue runtime won't be changed to make this syntax valid and docs should be changed instead (but neither happened yet).

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 mypy on the provided reproducer, T = list[int | "T"], and trace how forward references in PEP 604 unions are analyzed. Add a regression test for this example and ensure mypy reports that the syntax is unsupported, while preserving valid union handling.

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

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.