astral-sh / ruff

An extremely fast Python linter and code formatter, written in Rust.
https://docs.astral.sh/ruff
MIT License
33.09k stars 1.11k forks source link

[red-knot] Audit handling of metaclasses in various contexts, add more tests #14200

Open AlexWaygood opened 2 weeks ago

AlexWaygood commented 2 weeks ago

Now that we support metaclasses, we should verify that all of the following work as expected. If they do, we should add tests that assert that they do; if they don't, we have some bugs to fix:

from __future__ import annotations
from typing import Literal

class IntIterator:
    def __next__(self) -> int:
        return 42

class Meta(type):
    def __add__(self, other: Meta) -> int:
        return 42

    def __lt__(self, other: Meta) -> Literal[True]:
        return True

    def __getitem__(self, key: int) -> str:
        return "foo"

    def __iter__(self) -> IntIterator:
        return IntIterator()

    def __enter__(self) -> bytes:
        return b"42"

    def __exit__(self, *args) -> None:
        pass

class A(metaclass=Meta): ...
class B(metaclass=Meta): ...

reveal_type(A + B)  # revealed: int
reveal_type(A < B)  # revealed: Literal[True]
reveal_type(A[42])  # revealed: str

for x in A:
    reveal_type(x)  # revealed: int

with A as var:
    reveal_type(var)  # revealed: bytes

Cc. @charliermarsh, if you're interested!

carljm commented 2 weeks ago

I'm torn here, because we definitely do want this eventually, and it makes a lot of sense for @charliermarsh to follow up on it while the metaclass stuff is still fresh, but on the other hand -- I don't think that understanding these aspects of metaclasses is blocking other type system features, nor do I think it has a lot of technical risk, nor do I think it's necessary to pass much of the conformance suite. So is it a priority to work on right now?

AlexWaygood commented 2 weeks ago

No, not a priority, agreed! There may well be more important things for Charlie to work on. It felt like it wasn't a huge task, though, and as you say, it felt like it make sense to work on it now while metaclass considerations were fresh in our minds.

No strong opinion at all as to whether we work on it now or just add this issue to the backlog to work on later!