dict literals inferred like immutable Mapping

Đang mở
#11,090 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.

Đánh giá

Độ khó
4/5
Thời gian dự kiến
3-5 ngày
Mức phù hợp với người mới
38/100
Loại issue
Lỗi
Độ rõ ràng
Khá rõ ràng
Mức độ hoạt động
Đình trệ
Công nghệ
python
Lĩnh vực
tooling

Hướng nghiên cứu

Bắt đầu bằng cách chạy reproduction được cung cấp với mypy 0.910 và so sánh kiểu được suy luận của dict literal không có chú thích với phiên bản được chú thích tường minh. Theo dõi đường suy luận của dict literal và xác minh rằng phép gán chấp nhận union mong đợi mà không làm suy yếu tính an toàn kiểu; issue được giải quyết khi reproduction chạy thành công.

Do mô hình lập chỉ mục viết ra từ nội dung của issue.

Mô tả

bug topic-join-v-union

Bug Report

dict literal behaves as though it is inferred to be (immutable) Mapping

To Reproduce

class OrmBase:
    pass

class Orm1(OrmBase):
    pass

class Orm1Prime(OrmBase):
    pass

class Orm2(OrmBase):
    pass

class Orm2Prime(OrmBase):
    pass

def func(orm: Union[Orm1, Orm2]):
    orm_mapper = {
        Orm1: Orm1Prime, 
        Orm2: Orm2Prime,
    }
    mapped: Union[Type[Orm1Prime], Type[Orm2Prime]] = orm_mapper[orm.__class__]
    # Incompatible types in assignment (expression has type "Type[OrmBase]",
    # variable has type "Union[Type[Orm1Prime], Type[Orm2Prime]]") [E]
    return mapped

Expected Behavior

dict is a MutableMapping, which is invariant with respect to value types. The Union on mapped should be acceptable here. (Pyright has no issue with this.)

Actual Behavior

The Union is rejected, apparently because the parent class is expected (see the error message above).

Adding a plain dict annotation resolves the error:

orm_mapper: dict = { ...

I believe this resolves the error by telling Mypy that this is a MutableMapping with invariant VT and not a Mapping with covariant VT_co. typing's definitions of both

Your Environment

  • Mypy version used: 0.910
  • Mypy command-line flags: none
  • Mypy configuration options from mypy.ini (and other config files):
[mypy]
plugins = sqlalchemy.ext.mypy.plugin
ignore_missing_imports = True

[mypy-sqlalchemy.*]
  • Python version used: 3.9.6
  • Operating system and version: Fedora 34 (Workstation)
Ngôn ngữ chính
Python
Star
20.6k
Fork
3.3k
Merge trung bình
1 ngày 18 giờ
Pull request đã merge (30 ngày)
54

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.

Issue khác của python/mypy

Tất cả issue của python/mypy

Issue tương tự

Thêm issue về Python

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.