Skip to content

Confusing type of local __class__ #10451

@Enegg

Description

@Enegg

Describe the bug
Pyright reports the type of the local variable __class__ as type[Self@Foo].
This led me to believe the error at return __class__() is spurious; a runtime test has shown me the error is valid, as __class__ seems to remain concretely type[Foo] even in a subclass.

With that in mind, I think pyright should not report __class__ as type[Self@Foo], but rather type[Foo], and consequently __class__() should not be assignable to Self.

The error at the return statement could be improved as well, as Type "Self@Foo" is not assignable to return type "Self@Foo" is quite confusing.

Code or Screenshots

from typing import Self, reveal_type


class Foo:
    def from_self(self) -> Self:
        reveal_type(self.__class__)    # type[Self@Foo]
        reveal_type(self.__class__())  # Self@Foo
        _: Self = self.__class__()     # ok
        return self.__class__()        # ok

    def implicit(self) -> Self:
        reveal_type(__class__)    # type[Self@Foo]
        reveal_type(__class__())  # Self@Foo
        _: Self = __class__()     # ok
        return __class__()        # Type "Self@Foo" is not assignable to return type "Self@Foo"


class Bar(Foo): ...

foo = Foo()
bar = Bar()
print(foo.from_self(), foo.implicit())
print(bar.from_self(), bar.implicit())

Output:

Runtime type is 'type'
Runtime type is 'Foo'
Runtime type is 'type'
Runtime type is 'Foo'
<__main__.Foo object at 0x1> <__main__.Foo object at 0x2>
Runtime type is 'type'
Runtime type is 'Bar'
Runtime type is 'type'
Runtime type is 'Foo'
<__main__.Bar object at 0x1> <__main__.Foo object at 0x3>

VS Code extension or command-line
Pylance 2025.5.100, pre-release

Metadata

Metadata

Assignees

No one assigned

    Labels

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

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions