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.

Đang mở
#1,562 6 bình luận 1 reaction 0 người được giao Xem trên GitHub

Chưa có ai nhận issue này.

topic: feature
Ngôn ngữ chính
Python
Star
1.8k
Fork
302
Merge trung bình
23 giờ
Pull request đã merge (30 ngày)
8

Mô tả

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

Hướng dẫn đóng góp

Chưa lập chỉ mục được hướng dẫn đóng góp cho kho mã nguồn này

Bắt đầu từ đâu

  1. Đọc hết issue, rồi đọc hướng dẫn đóng góp của dự án.
  2. Bình luận trên issue rằng bạn sẽ nhận — tránh hai người làm cùng một việc.
  3. Fork repository và làm thay đổi trên một nhánh.
  4. Mở pull request có tham chiếu số hiệu của issue.

Hướng nghiên cứu

Bắt đầu với các ví dụ pyright-play và mypy-play được liên kết, tập trung vào Python 3.9, TYPE_CHECKING và các TypeAliases được chú thích rõ ràng. Chưa xác định được tệp nào trong repository hoặc bài kiểm thử nào; công việc chỉ được xem là hoàn tất khi có đặc tả thống nhất về cách diễn giải các trường hợp này, cùng với sự thống nhất hoặc công việc triển khai tương ứng trong các công cụ kiểm tra kiểu liên quan.

Do mô hình lập chỉ mục viết ra từ nội dung của issue.

Đánh giá

Công nghệ
python
Lĩnh vực
devtools
Loại issue
Tính năng
Độ khó
5/5
Thời gian dự kiến
Hơn một tuần
Mức độ hoạt động
Đình trệ
Độ rõ ràng
Khá rõ ràng
Mức phù hợp với người mới
28/100

Nhận issue mới trong hộp thư của bạn

Bản tóm tắt ngắn những issue GitHub phù hợp với người mới.