Skip to content

[red-knot] Improve not-iterable diagnostic #13989

@MichaReiser

Description

@MichaReiser

It's hard to debug why a type isn't considered iterable by red knot:

For example:

from typing import reveal_type


class TestIter:
    def __next__(self) -> str: ...


class Test:
    def __iter__(self) -> TestIter: ...


def bool_instance() -> bool:
    return True


flag = bool_instance()

if flag:
    a = "123"
else:
    a = Test()

for x in a:
    ...
reveal_type(x)

Reports

ERROR /home/micha/astral/test/src/test.py:23:10: Object of type `Literal["123"] | Test` is not iterable
ERROR /home/micha/astral/test/src/test.py:25:13: Name `x` used when possibly not defined
ERROR /home/micha/astral/test/src/test.py:25:1: Revealed type is `Unbound | Unknown`

And it's not clear to me why Test the type isn't iterable (pyright is fine with it).

Changing __next__ on TestIter to a non-callable gives the exact same error message (expect) but the error message isn't helpful because it isn't telling you what's off.

class TestIter:
    __next__ = 10

I'm not sure if it's worth investing time into improving the diagnostics know or if we should wait for proper Protocols support but I thought it worth noting it down because I just had a very bad time debugging the error message myself

Metadata

Metadata

Assignees

No one assigned

    Labels

    tyMulti-file analysis & type inference

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions