Fix incorrect TypeVar default expansion order (Fixes #20336)
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.
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
According to mypy_primer, this change doesn't affect type check results on a corpus of open source code. ✅
@sterliakov something up with .mypy_cache? does it show previous output even after changes?
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.