mypy icon indicating copy to clipboard operation
mypy copied to clipboard

Fix incorrect TypeVar default expansion order (Fixes #20336)

Open ayushdoesdev opened this issue 3 weeks ago • 4 comments

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.

ayushdoesdev avatar Dec 01 '25 14:12 ayushdoesdev

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

ayushdoesdev avatar Dec 01 '25 14:12 ayushdoesdev

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

github-actions[bot] avatar Dec 01 '25 14:12 github-actions[bot]

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

ayushdoesdev avatar Dec 01 '25 15:12 ayushdoesdev

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.

sterliakov avatar Dec 01 '25 16:12 sterliakov