python / python/typing

Treat alternative syntax for unions (and other "new-semantics-old-syntax" typing features) in explicit `TypeAlias`es inside `if TYPE_CHECKING` blocks as stringized annotations.

オープン
#1,562 コメント 6 件 リアクション 1 件 担当者 0 名 GitHub で見る

まだ誰も着手していません。

topic: feature
主要言語
Python
スター
1.8k
フォーク
302
平均マージ
23時間
マージ済み PR(30日)
8

説明

The Problem

At runtime, TYPE_CHECKING is always False, only type checkers assume it is True. Therefore, if TYPE_CHECKING blocks are only parsed, but never evaluated by the Python interpreter. Since A = int | str is a valid syntax for all still-supported Python versions at the moment (all versions ever since typing was introduced, actually), it would make sense if type checkers were allowed to accept usage of "new-semantics-old-syntax" features (like the alternative union syntax) in explicitly-annotated TypeAliases inside of if TYPE_CHECKING blocks as long as the Python version specified [project.requires-python] (or it's equivalent in tools) can successfully parse that syntax. This is essentially the same as treating explicitly-annotated TypeAliases as stringized annotations by-default.

Examples

# Run on 3.9

from typing import TYPE_CHECKING

if TYPE_CHECKING:
    A = int | str  # Alternative syntax for unions requires Python 3.10 or newer # pyright
                   # Invalid type alias: expression is not a valid type          # mypy
                   # Unsupported left operand type for | ("type[int]")           # mypy

# With proposal
from typing import TYPE_CHECKING
from typing_extensions import TypeAlias

if TYPE_CHECKING:
    A: TypeAlias = int | str  # Treated as a stringized annotation because `: TypeAlias`
                              # is explicit, therefore valid.

pyright-play
mypy-play

コントリビューションガイド

このリポジトリのコントリビューションガイドは索引されていません

はじめの一歩

  1. issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
  2. 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
  3. リポジトリをフォークし、ブランチを切って変更します。
  4. issue 番号を参照したプルリクエストを送ります。

調査の方向性

リンクされている pyright-play と mypy-play の例から始め、Python 3.9、TYPE_CHECKING、および明示的にアノテーションされた TypeAlias に焦点を当てます。リポジトリ内のファイルやテストは特定されていません。完了とするには、これらのケースをどのように解釈すべきかについて仕様を確定し、関連する型チェックツールで合意または実装作業を行う必要があります。

索引モデルが issue の本文から書いたものです。

評価

技術スタック
python
領域
devtools
issue の種類
機能追加
難易度
5/5
見積もり時間
1週間以上
活発さ
停滞
明瞭さ
おおむね明確
初心者へのやさしさ
28/100

新しい issue をメールで受け取る

初心者向けの GitHub issue を短くまとめたダイジェスト。