Skip to content

Validation of attribute assignments does not handle unions/intersections correctly #1163

@Glyphack

Description

@Glyphack

Summary

This example is extracted from mdtests after adding explicit self annotation (related astral-sh/ruff#18007)

After adding self annotation the following example fails:

from typing import Literal, Any

class DataDescriptor:
    def __get__(self: "DataDescriptor", instance: object, owner: type | None = None) -> Literal["data"]:
        return "data"

    def __set__(self: "DataDescriptor", instance: object, value: int) -> None:
        pass

def _(flag: bool):
    class Meta7(type):
        if flag:
            attr: DataDescriptor = DataDescriptor()
        else:
            attr: Literal[2] = 2

    class C7(metaclass=Meta7):
        pass

    # Invalid assignment to data descriptor attribute `attr` on type `<class 'C7'>` with custom `__set__` method (invalid-assignment)
    C7.attr = 2 if flag else 100

https://play.ty.dev/d25588da-713f-44d3-b35e-937808f43c06

I expected the error to be related to DataDescriptor, since we added the self annotation and it failed.
I could not find why adding self annotation causes the issue so I tried to change the other annotation.

This example has no diagnostics:

from typing import Literal, Any

class DataDescriptor:
    def __get__(self: "DataDescriptor", instance: object, owner: type | None = None) -> Literal["data"]:
        return "data"

    def __set__(self: "DataDescriptor", instance: object, value: int) -> None:
        pass

def _(flag: bool):
    class Meta7(type):
        attr: DataDescriptor = DataDescriptor()

    class C7(metaclass=Meta7):
        pass

    C7.attr = 2 if flag else 100

Version

fd7eb1e22

Metadata

Metadata

Assignees

No one assigned

    Labels

    attribute accessInstance attributes, class attributes, etc.bugSomething isn't working

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions