Skip to content

Improve the signature of type.__subclasses__ - #16299

Merged
JelleZijlstra merged 2 commits into
mainfrom
alex/dunder-subclasses
Aug 25, 2026
Merged

Improve the signature of type.__subclasses__#16299
JelleZijlstra merged 2 commits into
mainfrom
alex/dunder-subclasses

Conversation

@AlexWaygood

Copy link
Copy Markdown
Member

ty currently infers the types of object.__subclasses__() as list[<class 'object'>], AKA, "a list in which all contents of the list are the class object". This is obviously suboptimal: object clearly has more subclasses than just itself.

All other type checkers infer the type of object.__subclasses__() as either list[type[object]] (pyright, pyrefly) or list[Callable[[], object]] (mypy), because no other type checker has the concept of "class-literal types" the same way that ty does. (A "class-literal" type like <class 'object'> means "exactly the class object, not including subclasses", unlike type[object] which means "the class object, or any subclass".) But ty's behaviour arguably isn't incorrect here: it's a valid solution to the type variable in typeshed's signature as it is right now.

With the changes made in this PR, mypy, ty, pyright and pyrefly all infer the type of int.__subclasses__() as list[type[int]].

Fixes astral-sh/ty#4386. Credit to @sharkdp for the idea of how to fix this.

@github-actions

This comment has been minimized.

@AlexWaygood
AlexWaygood marked this pull request as ready for review August 25, 2026 10:43
@srittau

srittau commented Aug 25, 2026

Copy link
Copy Markdown
Collaborator

Could we add a brief test here that this infers correctly for the type checkers supported by our tests?

@AlexWaygood
AlexWaygood requested a review from srittau August 25, 2026 11:36
@github-actions

Copy link
Copy Markdown
Contributor

According to mypy_primer, this change has no effect on the checked open source code. 🤖🎉

@JelleZijlstra
JelleZijlstra merged commit 6b7f7b9 into main Aug 25, 2026
88 checks passed
@JelleZijlstra
JelleZijlstra deleted the alex/dunder-subclasses branch August 25, 2026 12:43
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

X.__subclasses__() is inferred as list[<class 'X'>]

3 participants