python / python/mypy

Mypy not detecting abstract methods returning undefined types

Đang mở
#14,545 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 topic-runtime-semantics
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ả

Bug Report

I have a class with a couple of abstract methods that return a particular custom type. That custom type is then defined right after the class. Then a global variable referencing that class is created:

To Reproduce

# test.py
from abc import ABC, abstractmethod
from typing import NamedTuple, List

class F(ABC):
    @abstractmethod
    async def m1(self) -> Result:
        pass
    
    @abstractmethod
    async def m2(self) -> Result:
        pass

class Result(NamedTuple):
    f1: str
    f2: int
    
foo: List[F] = []
> mypy --strict test.py
Success: no issues found in 1 source file
> python test.py
Traceback (most recent call last):
  File "test.py", line 4, in <module>
    class F(ABC):
  File "test.py", line 6, in F
    async def m1(self) -> Result:
NameError: name 'Result' is not defined

Expected Behavior

I would expect mypy to detect that Result is not defined before its use in class F.

Actual Behavior

Mypy is happy with the code as it is, even under --strict, while Python can't even run the code as is. Moving the declaration of Result above class F solves the problem and both Python and mypy are then happy.

Your Environment

  • Mypy version used: 0.991
  • Mypy command-line flags: --strict
  • Mypy configuration options from mypy.ini (and other config files): N/A
  • Python version used: 3.9.13

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

Tái hiện hành vi từ test.py bằng cách chạy mypy --strict rồi Python để so sánh kết quả tĩnh với NameError khi chạy. Theo dõi cách mypy phân tích các chú thích kiểu trả về của phương thức trừu tượng trước khi Result được khai báo. Được xem là hoàn tất khi mypy báo cáo tham chiếu Result chưa được định nghĩa trong trường hợp này mà không làm hỏng các chú thích hợp lệ.

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
Lỗi
Độ khó
3/5
Thời gian dự kiến
1-2 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
45/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.