python / python/mypy

Calling a method of Union of two classes with class's attribute results in incompatible type error

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

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

feature priority-2-low
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ả

Honestly didn't know how to name this issue...

Issue type: Bug
Problematic code:

from typing import Union

class UserTypeA: ...
class UserTypeB: ...

class A:
    def permissions_for(self, user: UserTypeA) -> bool: ...
    
    @property
    def me(self) -> UserTypeA: ...

class B:
    def permissions_for(self, user: UserTypeB) -> bool: ...
    
    @property
    def me(self) -> UserTypeB: ...


def func(x: Union[A, B]) -> bool:
    return x.permissions_for(x.me)

Error message:

main.py:20: error: Argument 1 to "permissions_for" of "A" has incompatible type "Union[UserTypeA, UserTypeB]"; expected "UserTypeA"
main.py:20: error: Argument 1 to "permissions_for" of "B" has incompatible type "Union[UserTypeA, UserTypeB]"; expected "UserTypeB"

Expected behaviour:
No error as x.me matches the type expected by x.permissions_for - if instance of A is passed x.me will have type UserTypeA and x.permissions_for will expect UserTypeA and same for instance of B.

Also, if func looks like this, the errors are gone so if mypy could infer this without isinstance it would be great:

def func(x: Union[A, B]) -> bool:
    if isinstance(x, A):
        return x.permissions_for(x.me)
    else:
        return x.permissions_for(x.me)

Python version:: 3.8.1
Mypy version: 0.761, occurs on master as well
Mypy flags: No flags

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 ví dụ tối thiểu trong main.py bằng mypy 0.761 hoặc master hiện tại, tập trung vào lời gọi Union[A, B] thông qua x.permissions_for(x.me). Hoàn thành khi func được kiểm tra kiểu mà không cần isinstance khi thuộc tính của mỗi lớp khớp với tham số phương thức của lớp đó, trong khi các lời gọi thực sự không tương thích vẫn là lỗi.

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ó
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 tả 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.