python / python/typing

[@overload]: What is the effect of the *implementation* type-signature?

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

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

topic: documentation
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ả

One thing that I've found underspecified when using @overload is what the type signature of the actual function should be.

For example, let's say I have a function like:

from typing import overload, Literal

@overload
def f(x: int, z: Literal[True]) -> str: ...
@overload
def f(x: int, z: Literal[False] = ...) -> int: ...
def f(x: int, z: bool = False) -> str | int:
    if z:
        return "hello"
    return 1

What is the effect of the last line? In particular:

  • The documentation and examples often just use no annotations for the implementation signature (def f(x, z):). Is that the right thing to do (I sometimes get Overloaded implementation is not consistent with signature of overload 1 errors if I leave out the type annotations)?
  • If I do specify types on the last, do I also have to add it to @overload list -- in other words:
@overload
def f(x: int, z: Literal[True]) -> str: ...
@overload
def f(x: int, z: Literal[False] = ...) -> int: ...
@overload
def f(x: int, z: bool = ...) -> str | int   # is this overload necessary?
def f(x: int, z: bool = False) -> str | int:
    if z:
        return "hello"
    return 1

Both pyright and mypy seem to interpret things differently with and without it (e.g. see this play link).

I understand that @overload is a complicated feature, but I'm hoping this is a small corner we can start with.

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ụ @overload trong issue này và chạy chúng trong Pyright playground được liên kết, sau đó so sánh kết quả với mypy. Xem xét cách hai công cụ diễn giải các chữ ký triển khai và danh sách overload. Công việc được xem là hoàn tất khi đạt được một giải thích đã thống nhất về ngữ nghĩa và ghi lại hành vi dự kiến cũng như các ví dụ.

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
documentation
Loại issue
Tài liệu
Độ 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
Cần làm rõ
Mức phù hợp với người mới
25/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.