Skip to content

Regression: Type Confusion from Inline Class Naming #10418

@robert-bn

Description

@robert-bn

The following code produces two errors with pyright 1.1.400

from typing import Any, Generic, Protocol, TypeVar

Row = TypeVar("Row", covariant=True)


class Cursor(Generic[Row]):
    def fetchone(self) -> Row: ...


class RowMaker(Protocol[Row]): ...


class BaseRowFactory(Protocol[Row]):
    def __call__(self, cursor: Cursor[Any]) -> RowMaker[Row]: ...


class RowFactory(Protocol[Row]):
    def __call__(self, cursor: Cursor[Any]) -> RowMaker[Row]: ...


class Connection:
    def cursor(self, row_factory: RowFactory[Row]) -> Cursor[Row]: ...


_T = TypeVar("_T")


def class_row(cls: type[_T]) -> BaseRowFactory[_T]: ...


def example_1(connection: Connection) -> None:
    class Row:
        foo: bool

    cursor = connection.cursor(row_factory=class_row(Row))
    res = cursor.fetchone()
    assert isinstance(res.foo, bool)


def example_2(connection: Connection) -> None:
    class Row:
        bar: str

    cursor = connection.cursor(row_factory=class_row(Row))
    res = cursor.fetchone()
    assert isinstance(res.bar, str)
    assert isinstance(res.foo, bool)

the errors are

example.py:46:23 - error: Type of "bar" is unknown (reportUnknownMemberType)
examplepy:46:27 - error: Cannot access attribute "bar" for class "Row"
    Attribute "bar" is unknown (reportAttributeAccessIssue)

In fact, res.bar should be available, and res.foo unavailable. If the class Row defined inline in example_2 is renamed so its name doesn't conflict with the name defined inline in example_1, the error disappears.

This appears to be due to a regression that appears in pyright 1.1.386, as 1.1.385 is the most recent version that correctly identifies foo as the undefined attribute, not bar.

Metadata

Metadata

Assignees

No one assigned

    Labels

    addressed in next versionIssue is fixed and will appear in next published versionbugSomething isn't workingregression

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions