python / python/mypy

Covariant type variable error in nested function

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

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

bug false-positive priority-1-normal topic-type-variables
Ngôn ngữ chính
Python
Star
20.6k
Fork
3.3k
Chỉ số merge pull request
Chỉ số pull request đang chờ

Mô tả

I believe the below code should be allowed:

from typing import *

T_co = TypeVar('T_co', covariant=True)

class Col(Generic[T_co]):
  def __init__(self, items: Iterable[T_co]) -> None:
    self.items = items

  def any(self, pred: Callable[[T_co], bool]) -> bool:
    return any(map(pred, self.items))

  def any_zero(self, fn: Callable[[T_co], int]) -> bool:
    def pred(x: T_co) -> bool: # error: Cannot use type variable as a parameter
      return fn(x) == 0
    return self.any(pred)

I believe the purpose of this error is to disallow breaking variance, e.g.:

  def unsafe(self) -> Callable[[T_co], int]:
    def fn(t: T_co) -> int:
      return id(t)
    return fn

However, restricting variance on nested functions has both false positives (first example), and false negatives:

class Unsafe(Generic[T_co]):
  def __init__(self, fn: Callable[[T_co], int]) -> None:
    self.fn = fn

  def get_fn(self) -> Callable[[T_co], int]:
    return self.fn

The above code has no error, but is not type safe. I believe the proper way to check for this is to look at the signatures of each exposed method and verify that the type parameter is not used with the wrong parity.

mypy 0.740, python 3.7.5

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

Mở hướng dẫn đóng góp

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 bằng cách tái hiện các ví dụ về hàm lồng nhau với mypy 0.740 và so sánh lỗi phương sai được báo cáo với ví dụ về phương thức exposed không an toàn. Truy vết các bước kiểm tra phương sai cho các hàm lồng nhau và chữ ký phương thức exposed. Được xem là hoàn thành khi ví dụ an toàn được chấp nhận, còn các trường hợp không an toàn bị từ chối mà không tạo ra false negative.

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
compilers
Loại issue
Lỗi
Độ 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
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.