python / python/mypy

mypy infer incorrect types in frozen dataclass with descriptors as attributes.

Đang mở
#17,601 0 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
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 am having issues with frozen dataclass that inherits from a frozen dataclass with descriptors as attributes. mypy infer incorrect datatypes of the attributes from the base class. If the dataclasses are not frozen, then mypy infer correct datatypes in inherited class.

Below is the minimal code to reproduce the issue.
python=3.11
mypy=1.14.0

mypy-play.net

To Reproduce


from abc import ABCMeta, abstractmethod
from dataclasses import dataclass
from typing import Self, SupportsFloat, TypeVar, overload, Type, Optional, Generic, Any

T = TypeVar("T")
V = TypeVar("V")


class Base(Generic[T, V], metaclass=ABCMeta):
    def __set_name__(self, owner: type, name: str) -> None:
        self.public_name = name
        self.private_name = "_" + name

    @overload
    def __get__(self, instance: None, owner: Optional[Type[Any]] = None) -> Self:...

    @overload
    def __get__(self, instance: Any, owner: Optional[Type[Any]] = None) -> V | None:...

    def __get__(self, instance: Any, owner: Optional[Type[Any]] = None) ->  Self | V | None:
        if instance is None:
            return self
        return getattr(instance, self.private_name, None)

    def __set__(self, instance: Any, value: Optional[T]) -> None:
        if value is self or value is None:
            return
        converted = self._converter(value)
        object.__setattr__(instance, self.private_name, converted)

    @abstractmethod
    def _converter(self, value: T) -> V:
        """
        Hook to implement conversion logic
        """

class FloatParameter(Base[SupportsFloat, float]):
    def _converter(self, value: SupportsFloat) -> float:
        """Can have more logic here to check if value can be converted to float"""
        return float(value)
        

@dataclass(frozen=True, kw_only=True)
class BaseDataClass:
    float_param: FloatParameter = FloatParameter()


@dataclass(frozen=True, kw_only=True)
class DerivedDataClass(BaseDataClass):
    boolean: bool = True


reveal_type(BaseDataClass.float_param) # correct FloatParameter
reveal_type(DerivedDataClass.float_param) # Incorrect Union[typing.SupportsFloat, None]

reveal_type(BaseDataClass().float_param) # Correct "Union[builtins.float, None]"
reveal_type(DerivedDataClass().float_param) # Incorrect Union[typing.SupportsFloat, None]

NOTE: Pylance on the other hand on VSCode shows correct datatypes.

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 với bản tái hiện tối thiểu bằng Python 3.11 sử dụng mypy 1.14.0 và so sánh các kết quả reveal_type cho BaseDataClass và DerivedDataClass. Điều tra việc kế thừa dataclass đóng băng với các thuộc tính descriptor; được xem là hoàn thành khi lớp dẫn xuất báo cáo FloatParameter trên lớp và float | None trên các thực thể, khớp với lớp cơ sở.

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ó
4/5
Thời gian dự kiến
3-5 ngày
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
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.