Skip to content

Allow errors for unsound Self definitions on non-final classes#2221

Open
davidhalter wants to merge 5 commits intopython:mainfrom
davidhalter:allow-unsound-error-self-classvar
Open

Allow errors for unsound Self definitions on non-final classes#2221
davidhalter wants to merge 5 commits intopython:mainfrom
davidhalter:allow-unsound-error-self-classvar

Conversation

@davidhalter
Copy link
Copy Markdown
Contributor

This comes after #2148 which wants to make this a mandatory error.

But for now it should be totally fine to allow type checkers to error here, since it can clearly be shown to be unsound, see also:

https://discuss.python.org/t/disallow-access-to-class-variables-with-self/105434

I'm happy to revisit the original pull request, but for now I hope this should suffice. I will rerun the automated tests if and once no changes are required.

@srittau srittau added the topic: conformance tests Issues with the conformance test suite label Mar 17, 2026
@davidhalter
Copy link
Copy Markdown
Contributor Author

@JelleZijlstra Would you mind reviewing this? IMO it's a very uncontroversial change.

The problem is (quoting from discuss):

from typing import Self, assert_type

class ParentB:
    a: list[Self]
    @classmethod
    def method4(cls) -> None:
        cls.a = [cls()]

class ChildB(ParentB):
    @classmethod
    def method3(cls) -> None:
        assert_type(cls, type[Self])
        assert_type(cls.a, list[Self]) # This can be a different type, but is not in conformance tests
        assert_type(cls.a[0], Self)  # Same
        print(cls.a)

ParentB.method4()
ChildB.method3()  # Prints [<__main__.ParentB object>]

There is currently no part of the spec that describes this.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

topic: conformance tests Issues with the conformance test suite

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants