Skip to content

Conversation

@ayushdoesdev
Copy link

This PR fixes how mypy handles generic classes with default type parameters when they refer to themselves inside the class body. It Fixes #20336

Before this change, if you wrote something like:

class Foo[X, Y, Z = object]:
    def test(self, swapped: Foo[Y, X]) -> None:
        reveal_type(swapped)

mypy would show:

Revealed type is "Foo[X, Y, builtins.object]"

It ignored the fact that Foo[Y, X] swaps the type variables.

With this change, mypy now keeps the order that the user wrote:

Revealed type is "Foo[Y, X, builtins.object]"

The fix is in fix_instance in mypy/typeanal.py.
It checks for cases where all the type arguments are the class’s own type variables (like Foo[Y, X]) and skips the extra expansion step that was reordering them.

Copy link
Collaborator

@sterliakov sterliakov left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Was this generated by some kind of LLM?

Please add a few testcases (at least from the original issue and from comments there).

@ayushdoesdev
Copy link
Author

Hi @sterliakov , no I took help but did code on my own because they were not able to help
and yes did code formatting with them

Ok I will add the test case

@github-actions
Copy link
Contributor

github-actions bot commented Dec 1, 2025

According to mypy_primer, this change doesn't affect type check results on a corpus of open source code. ✅

@ayushdoesdev
Copy link
Author

@sterliakov something up with .mypy_cache? does it show previous output even after changes?

@sterliakov
Copy link
Collaborator

Mhm, you can run mypy ... --cache-dir=/dev/null to rule that out, or remove .mypy_cache dir manually. Not applicable to tests, everything is cleaned up after a test run.

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.

Swapping some type variables gives incorrect results

2 participants