1
1
from __future__ import annotations
2
2
3
- from collections .abc import Iterable , Mapping , Sequence
3
+ from collections .abc import Iterable , Mapping
4
4
from typing import Final , TypeVar , cast , overload
5
5
6
6
from mypy .nodes import ARG_STAR , FakeInfo , Var
@@ -209,7 +209,11 @@ def visit_erased_type(self, t: ErasedType) -> Type:
209
209
return t
210
210
211
211
def visit_instance (self , t : Instance ) -> Type :
212
- args = self .expand_types_with_unpack (list (t .args ))
212
+ if len (t .args ) == 0 :
213
+ # TODO: Why do we need to create a copy here?
214
+ return t .copy_modified ()
215
+
216
+ args = self .expand_type_tuple_with_unpack (t .args )
213
217
214
218
if isinstance (t .type , FakeInfo ):
215
219
# The type checker expands function definitions and bodies
@@ -431,7 +435,7 @@ def visit_overloaded(self, t: Overloaded) -> Type:
431
435
items .append (new_item )
432
436
return Overloaded (items )
433
437
434
- def expand_types_with_unpack (self , typs : Sequence [Type ]) -> list [Type ]:
438
+ def expand_type_list_with_unpack (self , typs : list [Type ]) -> list [Type ]:
435
439
"""Expands a list of types that has an unpack."""
436
440
items : list [Type ] = []
437
441
for item in typs :
@@ -441,8 +445,19 @@ def expand_types_with_unpack(self, typs: Sequence[Type]) -> list[Type]:
441
445
items .append (item .accept (self ))
442
446
return items
443
447
448
+ def expand_type_tuple_with_unpack (self , typs : tuple [Type , ...]) -> list [Type ]:
449
+ """Expands a tuple of types that has an unpack."""
450
+ # Micro-optimization: Specialized variant of expand_type_list_with_unpack
451
+ items : list [Type ] = []
452
+ for item in typs :
453
+ if isinstance (item , UnpackType ) and isinstance (item .type , TypeVarTupleType ):
454
+ items .extend (self .expand_unpack (item ))
455
+ else :
456
+ items .append (item .accept (self ))
457
+ return items
458
+
444
459
def visit_tuple_type (self , t : TupleType ) -> Type :
445
- items = self .expand_types_with_unpack (t .items )
460
+ items = self .expand_type_list_with_unpack (t .items )
446
461
if len (items ) == 1 :
447
462
# Normalize Tuple[*Tuple[X, ...]] -> Tuple[X, ...]
448
463
item = items [0 ]
@@ -510,7 +525,7 @@ def visit_type_type(self, t: TypeType) -> Type:
510
525
def visit_type_alias_type (self , t : TypeAliasType ) -> Type :
511
526
# Target of the type alias cannot contain type variables (not bound by the type
512
527
# alias itself), so we just expand the arguments.
513
- args = self .expand_types_with_unpack (t .args )
528
+ args = self .expand_type_list_with_unpack (t .args )
514
529
# TODO: normalize if target is Tuple, and args are [*tuple[X, ...]]?
515
530
return t .copy_modified (args = args )
516
531
0 commit comments