python / python/mypy

Mypy fails to infer the type of the decorated function used in the decorator

Đang mở
#12,944 3 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-usability
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ả

Hi mypy team,

Bug Report
I'm looking into the issue with design-by-contract library icontract which heavily uses decorators to formalize contracts. For many functions and methods, the contracts involve the decorated function (or method) itself.

See the example from the issue https://github.com/Parquery/icontract/issues/243:

from icontract import ensure

@ensure(
    lambda a, b, result: 
    result == myadd(b, a), 
    "Commutativity violated!"
)
def myadd(a: int, b: int) -> int:
    return a + b

Mypy 0.960 says:

tests_3_10\deleteme.py:5: error: Cannot determine type of "myadd"

If I add # type: ignore:

from icontract import ensure

@ensure(
    lambda a, b, result: 
    result == myadd(b, a),   # type: ignore
    "Commutativity violated!"
)
def myadd(a: int, b: int) -> int:
    return a + b

mypy does not complain any more.

I was actually a bit surprised that mypy tried to infer the types in the lambda. @claudio-ebel tried a couple of fixes using casting (see his comment https://github.com/Parquery/icontract/issues/243#issue-1229622746), but none of them worked.

I am actually not sure if this is a misunderstanding on our part or a bug in mypy. Any pointers about how to resolve the issue are very much appreciated! Please let us know if you need more information, or if there is anything we can do to help to fix this.

Your Environment

  • Mypy version used: 0.960
  • Mypy command-line flags: `--strict``
  • Python version used: 3.10.0

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 ví dụ icontract được cung cấp với mypy 0.960 và --strict, sau đó lần theo các điểm truy nhập của quá trình suy luận kiểu cho decorator và lambda có liên quan đến lỗi. So sánh hành vi khi có và không có chú thích type: ignore; công việc được xem là hoàn tất khi xác định được chẩn đoán đó có được mong đợi hay không, hoặc sửa suy luận để ví dụ được kiểm tra mà không cần cơ chế suppression đó.

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
tooling
Loại issue
Lỗi
Độ khó
4/5
Thời gian dự kiến
3-5 ngày
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
35/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.