forked from python/mypy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsubtypes.py
2057 lines (1854 loc) · 87.5 KB
/
subtypes.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from __future__ import annotations
from contextlib import contextmanager
from typing import Any, Callable, Final, Iterator, List, TypeVar, cast
from typing_extensions import TypeAlias as _TypeAlias
import mypy.applytype
import mypy.constraints
import mypy.typeops
from mypy.erasetype import erase_type
from mypy.expandtype import expand_self_type, expand_type, expand_type_by_instance
from mypy.maptype import map_instance_to_supertype
# Circular import; done in the function instead.
# import mypy.solve
from mypy.nodes import (
ARG_STAR,
ARG_STAR2,
CONTRAVARIANT,
COVARIANT,
INVARIANT,
VARIANCE_NOT_READY,
Decorator,
FuncBase,
OverloadedFuncDef,
TypeInfo,
Var,
)
from mypy.options import Options
from mypy.state import state
from mypy.types import (
MYPYC_NATIVE_INT_NAMES,
TUPLE_LIKE_INSTANCE_NAMES,
TYPED_NAMEDTUPLE_NAMES,
AnyType,
CallableType,
DeletedType,
ErasedType,
FormalArgument,
FunctionLike,
Instance,
LiteralType,
NoneType,
NormalizedCallableType,
Overloaded,
Parameters,
ParamSpecType,
PartialType,
ProperType,
TupleType,
Type,
TypeAliasType,
TypedDictType,
TypeOfAny,
TypeType,
TypeVarTupleType,
TypeVarType,
TypeVisitor,
UnboundType,
UninhabitedType,
UnionType,
UnpackType,
find_unpack_in_list,
get_proper_type,
is_named_instance,
split_with_prefix_and_suffix,
)
from mypy.types_utils import flatten_types
from mypy.typestate import SubtypeKind, type_state
from mypy.typevars import fill_typevars, fill_typevars_with_any
# Flags for detected protocol members
IS_SETTABLE: Final = 1
IS_CLASSVAR: Final = 2
IS_CLASS_OR_STATIC: Final = 3
IS_VAR: Final = 4
TypeParameterChecker: _TypeAlias = Callable[[Type, Type, int, bool, "SubtypeContext"], bool]
class SubtypeContext:
def __init__(
self,
*,
# Non-proper subtype flags
ignore_type_params: bool = False,
ignore_pos_arg_names: bool = False,
ignore_declared_variance: bool = False,
# Supported for both proper and non-proper
ignore_promotions: bool = False,
ignore_uninhabited: bool = False,
# Proper subtype flags
erase_instances: bool = False,
keep_erased_types: bool = False,
options: Options | None = None,
) -> None:
self.ignore_type_params = ignore_type_params
self.ignore_pos_arg_names = ignore_pos_arg_names
self.ignore_declared_variance = ignore_declared_variance
self.ignore_promotions = ignore_promotions
self.ignore_uninhabited = ignore_uninhabited
self.erase_instances = erase_instances
self.keep_erased_types = keep_erased_types
self.options = options
def check_context(self, proper_subtype: bool) -> None:
# Historically proper and non-proper subtypes were defined using different helpers
# and different visitors. Check if flag values are such that we definitely support.
if proper_subtype:
assert not self.ignore_pos_arg_names and not self.ignore_declared_variance
else:
assert not self.erase_instances and not self.keep_erased_types
def is_subtype(
left: Type,
right: Type,
*,
subtype_context: SubtypeContext | None = None,
ignore_type_params: bool = False,
ignore_pos_arg_names: bool = False,
ignore_declared_variance: bool = False,
ignore_promotions: bool = False,
ignore_uninhabited: bool = False,
options: Options | None = None,
) -> bool:
"""Is 'left' subtype of 'right'?
Also consider Any to be a subtype of any type, and vice versa. This
recursively applies to components of composite types (List[int] is subtype
of List[Any], for example).
type_parameter_checker is used to check the type parameters (for example,
A with B in is_subtype(C[A], C[B]). The default checks for subtype relation
between the type arguments (e.g., A and B), taking the variance of the
type var into account.
"""
if subtype_context is None:
subtype_context = SubtypeContext(
ignore_type_params=ignore_type_params,
ignore_pos_arg_names=ignore_pos_arg_names,
ignore_declared_variance=ignore_declared_variance,
ignore_promotions=ignore_promotions,
ignore_uninhabited=ignore_uninhabited,
options=options,
)
else:
assert not any(
{
ignore_type_params,
ignore_pos_arg_names,
ignore_declared_variance,
ignore_promotions,
ignore_uninhabited,
options,
}
), "Don't pass both context and individual flags"
if type_state.is_assumed_subtype(left, right):
return True
if mypy.typeops.is_recursive_pair(left, right):
# This case requires special care because it may cause infinite recursion.
# Our view on recursive types is known under a fancy name of iso-recursive mu-types.
# Roughly this means that a recursive type is defined as an alias where right hand side
# can refer to the type as a whole, for example:
# A = Union[int, Tuple[A, ...]]
# and an alias unrolled once represents the *same type*, in our case all these represent
# the same type:
# A
# Union[int, Tuple[A, ...]]
# Union[int, Tuple[Union[int, Tuple[A, ...]], ...]]
# The algorithm for subtyping is then essentially under the assumption that left <: right,
# check that get_proper_type(left) <: get_proper_type(right). On the example above,
# If we start with:
# A = Union[int, Tuple[A, ...]]
# B = Union[int, Tuple[B, ...]]
# When checking if A <: B we push pair (A, B) onto 'assuming' stack, then when after few
# steps we come back to initial call is_subtype(A, B) and immediately return True.
with pop_on_exit(type_state.get_assumptions(is_proper=False), left, right):
return _is_subtype(left, right, subtype_context, proper_subtype=False)
return _is_subtype(left, right, subtype_context, proper_subtype=False)
def is_proper_subtype(
left: Type,
right: Type,
*,
subtype_context: SubtypeContext | None = None,
ignore_promotions: bool = False,
ignore_uninhabited: bool = False,
erase_instances: bool = False,
keep_erased_types: bool = False,
) -> bool:
"""Is left a proper subtype of right?
For proper subtypes, there's no need to rely on compatibility due to
Any types. Every usable type is a proper subtype of itself.
If erase_instances is True, erase left instance *after* mapping it to supertype
(this is useful for runtime isinstance() checks). If keep_erased_types is True,
do not consider ErasedType a subtype of all types (used by type inference against unions).
"""
if subtype_context is None:
subtype_context = SubtypeContext(
ignore_promotions=ignore_promotions,
ignore_uninhabited=ignore_uninhabited,
erase_instances=erase_instances,
keep_erased_types=keep_erased_types,
)
else:
assert not any(
{
ignore_promotions,
ignore_uninhabited,
erase_instances,
keep_erased_types,
ignore_uninhabited,
}
), "Don't pass both context and individual flags"
if type_state.is_assumed_proper_subtype(left, right):
return True
if mypy.typeops.is_recursive_pair(left, right):
# Same as for non-proper subtype, see detailed comment there for explanation.
with pop_on_exit(type_state.get_assumptions(is_proper=True), left, right):
return _is_subtype(left, right, subtype_context, proper_subtype=True)
return _is_subtype(left, right, subtype_context, proper_subtype=True)
def is_equivalent(
a: Type,
b: Type,
*,
ignore_type_params: bool = False,
ignore_pos_arg_names: bool = False,
options: Options | None = None,
subtype_context: SubtypeContext | None = None,
) -> bool:
return is_subtype(
a,
b,
ignore_type_params=ignore_type_params,
ignore_pos_arg_names=ignore_pos_arg_names,
options=options,
subtype_context=subtype_context,
) and is_subtype(
b,
a,
ignore_type_params=ignore_type_params,
ignore_pos_arg_names=ignore_pos_arg_names,
options=options,
subtype_context=subtype_context,
)
def is_same_type(
a: Type, b: Type, ignore_promotions: bool = True, subtype_context: SubtypeContext | None = None
) -> bool:
"""Are these types proper subtypes of each other?
This means types may have different representation (e.g. an alias, or
a non-simplified union) but are semantically exchangeable in all contexts.
"""
# First, use fast path for some common types. This is performance-critical.
if (
type(a) is Instance
and type(b) is Instance
and a.type == b.type
and len(a.args) == len(b.args)
and a.last_known_value is b.last_known_value
):
return all(is_same_type(x, y) for x, y in zip(a.args, b.args))
elif isinstance(a, TypeVarType) and isinstance(b, TypeVarType) and a.id == b.id:
return True
# Note that using ignore_promotions=True (default) makes types like int and int64
# considered not the same type (which is the case at runtime).
# Also Union[bool, int] (if it wasn't simplified before) will be different
# from plain int, etc.
return is_proper_subtype(
a, b, ignore_promotions=ignore_promotions, subtype_context=subtype_context
) and is_proper_subtype(
b, a, ignore_promotions=ignore_promotions, subtype_context=subtype_context
)
# This is a common entry point for subtyping checks (both proper and non-proper).
# Never call this private function directly, use the public versions.
def _is_subtype(
left: Type, right: Type, subtype_context: SubtypeContext, proper_subtype: bool
) -> bool:
subtype_context.check_context(proper_subtype)
orig_right = right
orig_left = left
left = get_proper_type(left)
right = get_proper_type(right)
# Note: Unpack type should not be a subtype of Any, since it may represent
# multiple types. This should always go through the visitor, to check arity.
if (
not proper_subtype
and isinstance(right, (AnyType, UnboundType, ErasedType))
and not isinstance(left, UnpackType)
):
# TODO: should we consider all types proper subtypes of UnboundType and/or
# ErasedType as we do for non-proper subtyping.
return True
if isinstance(right, UnionType) and not isinstance(left, UnionType):
# Normally, when 'left' is not itself a union, the only way
# 'left' can be a subtype of the union 'right' is if it is a
# subtype of one of the items making up the union.
if proper_subtype:
is_subtype_of_item = any(
is_proper_subtype(orig_left, item, subtype_context=subtype_context)
for item in right.items
)
else:
is_subtype_of_item = any(
is_subtype(orig_left, item, subtype_context=subtype_context)
for item in right.items
)
# Recombine rhs literal types, to make an enum type a subtype
# of a union of all enum items as literal types. Only do it if
# the previous check didn't succeed, since recombining can be
# expensive.
# `bool` is a special case, because `bool` is `Literal[True, False]`.
if (
not is_subtype_of_item
and isinstance(left, Instance)
and (left.type.is_enum or left.type.fullname == "builtins.bool")
):
right = UnionType(mypy.typeops.try_contracting_literals_in_union(right.items))
if proper_subtype:
is_subtype_of_item = any(
is_proper_subtype(orig_left, item, subtype_context=subtype_context)
for item in right.items
)
else:
is_subtype_of_item = any(
is_subtype(orig_left, item, subtype_context=subtype_context)
for item in right.items
)
# However, if 'left' is a type variable T, T might also have
# an upper bound which is itself a union. This case will be
# handled below by the SubtypeVisitor. We have to check both
# possibilities, to handle both cases like T <: Union[T, U]
# and cases like T <: B where B is the upper bound of T and is
# a union. (See #2314.)
if not isinstance(left, TypeVarType):
return is_subtype_of_item
elif is_subtype_of_item:
return True
# otherwise, fall through
return left.accept(SubtypeVisitor(orig_right, subtype_context, proper_subtype))
def check_type_parameter(
left: Type, right: Type, variance: int, proper_subtype: bool, subtype_context: SubtypeContext
) -> bool:
# It is safe to consider empty collection literals and similar as covariant, since
# such type can't be stored in a variable, see checker.is_valid_inferred_type().
if variance == INVARIANT:
p_left = get_proper_type(left)
if isinstance(p_left, UninhabitedType) and p_left.ambiguous:
variance = COVARIANT
# If variance hasn't been inferred yet, we are lenient and default to
# covariance. This shouldn't happen often, but it's very difficult to
# avoid these cases altogether.
if variance == COVARIANT or variance == VARIANCE_NOT_READY:
if proper_subtype:
return is_proper_subtype(left, right, subtype_context=subtype_context)
else:
return is_subtype(left, right, subtype_context=subtype_context)
elif variance == CONTRAVARIANT:
if proper_subtype:
return is_proper_subtype(right, left, subtype_context=subtype_context)
else:
return is_subtype(right, left, subtype_context=subtype_context)
else:
if proper_subtype:
# We pass ignore_promotions=False because it is a default for subtype checks.
# The actual value will be taken from the subtype_context, and it is whatever
# the original caller passed.
return is_same_type(
left, right, ignore_promotions=False, subtype_context=subtype_context
)
else:
return is_equivalent(left, right, subtype_context=subtype_context)
class SubtypeVisitor(TypeVisitor[bool]):
def __init__(self, right: Type, subtype_context: SubtypeContext, proper_subtype: bool) -> None:
self.right = get_proper_type(right)
self.orig_right = right
self.proper_subtype = proper_subtype
self.subtype_context = subtype_context
self.options = subtype_context.options
self._subtype_kind = SubtypeVisitor.build_subtype_kind(subtype_context, proper_subtype)
@staticmethod
def build_subtype_kind(subtype_context: SubtypeContext, proper_subtype: bool) -> SubtypeKind:
return (
state.strict_optional,
proper_subtype,
subtype_context.ignore_type_params,
subtype_context.ignore_pos_arg_names,
subtype_context.ignore_declared_variance,
subtype_context.ignore_promotions,
subtype_context.erase_instances,
subtype_context.keep_erased_types,
)
def _is_subtype(self, left: Type, right: Type) -> bool:
if self.proper_subtype:
return is_proper_subtype(left, right, subtype_context=self.subtype_context)
return is_subtype(left, right, subtype_context=self.subtype_context)
# visit_x(left) means: is left (which is an instance of X) a subtype of right?
def visit_unbound_type(self, left: UnboundType) -> bool:
# This can be called if there is a bad type annotation. The result probably
# doesn't matter much but by returning True we simplify these bad types away
# from unions, which could filter out some bogus messages.
return True
def visit_any(self, left: AnyType) -> bool:
return isinstance(self.right, AnyType) if self.proper_subtype else True
def visit_none_type(self, left: NoneType) -> bool:
if state.strict_optional:
if isinstance(self.right, NoneType) or is_named_instance(
self.right, "builtins.object"
):
return True
if isinstance(self.right, Instance) and self.right.type.is_protocol:
members = self.right.type.protocol_members
# None is compatible with Hashable (and other similar protocols). This is
# slightly sloppy since we don't check the signature of "__hash__".
# None is also compatible with `SupportsStr` protocol.
return not members or all(member in ("__hash__", "__str__") for member in members)
return False
else:
return True
def visit_uninhabited_type(self, left: UninhabitedType) -> bool:
# We ignore this for unsafe overload checks, so that and empty list and
# a list of int will be considered non-overlapping.
if isinstance(self.right, UninhabitedType):
return True
return not self.subtype_context.ignore_uninhabited
def visit_erased_type(self, left: ErasedType) -> bool:
# This may be encountered during type inference. The result probably doesn't
# matter much.
# TODO: it actually does matter, figure out more principled logic about this.
return not self.subtype_context.keep_erased_types
def visit_deleted_type(self, left: DeletedType) -> bool:
return True
def visit_instance(self, left: Instance) -> bool:
if left.type.fallback_to_any and not self.proper_subtype:
# NOTE: `None` is a *non-subclassable* singleton, therefore no class
# can by a subtype of it, even with an `Any` fallback.
# This special case is needed to treat descriptors in classes with
# dynamic base classes correctly, see #5456.
return not isinstance(self.right, NoneType)
right = self.right
if isinstance(right, TupleType) and right.partial_fallback.type.is_enum:
return self._is_subtype(left, mypy.typeops.tuple_fallback(right))
if isinstance(right, TupleType):
if len(right.items) == 1:
# Non-normalized Tuple type (may be left after semantic analysis
# because semanal_typearg visitor is not a type translator).
item = right.items[0]
if isinstance(item, UnpackType):
unpacked = get_proper_type(item.type)
if isinstance(unpacked, Instance):
return self._is_subtype(left, unpacked)
if left.type.has_base(right.partial_fallback.type.fullname):
if not self.proper_subtype:
# Special case to consider Foo[*tuple[Any, ...]] (i.e. bare Foo) a
# subtype of Foo[<whatever>], when Foo is user defined variadic tuple type.
mapped = map_instance_to_supertype(left, right.partial_fallback.type)
for arg in map(get_proper_type, mapped.args):
if isinstance(arg, UnpackType):
unpacked = get_proper_type(arg.type)
if not isinstance(unpacked, Instance):
break
assert unpacked.type.fullname == "builtins.tuple"
if not isinstance(get_proper_type(unpacked.args[0]), AnyType):
break
elif not isinstance(arg, AnyType):
break
else:
return True
return False
if isinstance(right, TypeVarTupleType):
# tuple[Any, ...] is like Any in the world of tuples (see special case above).
if left.type.has_base("builtins.tuple"):
mapped = map_instance_to_supertype(left, right.tuple_fallback.type)
if isinstance(get_proper_type(mapped.args[0]), AnyType):
return not self.proper_subtype
if isinstance(right, Instance):
if type_state.is_cached_subtype_check(self._subtype_kind, left, right):
return True
if type_state.is_cached_negative_subtype_check(self._subtype_kind, left, right):
return False
if not self.subtype_context.ignore_promotions:
for base in left.type.mro:
if base._promote and any(
self._is_subtype(p, self.right) for p in base._promote
):
type_state.record_subtype_cache_entry(self._subtype_kind, left, right)
return True
# Special case: Low-level integer types are compatible with 'int'. We can't
# use promotions, since 'int' is already promoted to low-level integer types,
# and we can't have circular promotions.
if left.type.alt_promote and left.type.alt_promote.type is right.type:
return True
rname = right.type.fullname
# Always try a nominal check if possible,
# there might be errors that a user wants to silence *once*.
# NamedTuples are a special case, because `NamedTuple` is not listed
# in `TypeInfo.mro`, so when `(a: NamedTuple) -> None` is used,
# we need to check for `is_named_tuple` property
if (
left.type.has_base(rname)
or rname == "builtins.object"
or (
rname in TYPED_NAMEDTUPLE_NAMES
and any(l.is_named_tuple for l in left.type.mro)
)
) and not self.subtype_context.ignore_declared_variance:
# Map left type to corresponding right instances.
t = map_instance_to_supertype(left, right.type)
if self.subtype_context.erase_instances:
erased = erase_type(t)
assert isinstance(erased, Instance)
t = erased
nominal = True
if right.type.has_type_var_tuple_type:
# For variadic instances we simply find the correct type argument mappings,
# all the heavy lifting is done by the tuple subtyping.
assert right.type.type_var_tuple_prefix is not None
assert right.type.type_var_tuple_suffix is not None
prefix = right.type.type_var_tuple_prefix
suffix = right.type.type_var_tuple_suffix
tvt = right.type.defn.type_vars[prefix]
assert isinstance(tvt, TypeVarTupleType)
fallback = tvt.tuple_fallback
left_prefix, left_middle, left_suffix = split_with_prefix_and_suffix(
t.args, prefix, suffix
)
right_prefix, right_middle, right_suffix = split_with_prefix_and_suffix(
right.args, prefix, suffix
)
left_args = (
left_prefix + (TupleType(list(left_middle), fallback),) + left_suffix
)
right_args = (
right_prefix + (TupleType(list(right_middle), fallback),) + right_suffix
)
if not self.proper_subtype and t.args:
for arg in map(get_proper_type, t.args):
if isinstance(arg, UnpackType):
unpacked = get_proper_type(arg.type)
if not isinstance(unpacked, Instance):
break
assert unpacked.type.fullname == "builtins.tuple"
if not isinstance(get_proper_type(unpacked.args[0]), AnyType):
break
elif not isinstance(arg, AnyType):
break
else:
return True
if len(left_args) != len(right_args):
return False
type_params = zip(left_args, right_args, right.type.defn.type_vars)
else:
type_params = zip(t.args, right.args, right.type.defn.type_vars)
if not self.subtype_context.ignore_type_params:
tried_infer = False
for lefta, righta, tvar in type_params:
if isinstance(tvar, TypeVarType):
if tvar.variance == VARIANCE_NOT_READY and not tried_infer:
infer_class_variances(right.type)
tried_infer = True
if not check_type_parameter(
lefta,
righta,
tvar.variance,
self.proper_subtype,
self.subtype_context,
):
nominal = False
else:
# TODO: everywhere else ParamSpecs are handled as invariant.
if not check_type_parameter(
lefta, righta, COVARIANT, self.proper_subtype, self.subtype_context
):
nominal = False
if nominal:
type_state.record_subtype_cache_entry(self._subtype_kind, left, right)
else:
type_state.record_negative_subtype_cache_entry(self._subtype_kind, left, right)
return nominal
if right.type.is_protocol and is_protocol_implementation(
left, right, proper_subtype=self.proper_subtype, options=self.options
):
return True
# We record negative cache entry here, and not in the protocol check like we do for
# positive cache, to avoid accidentally adding a type that is not a structural
# subtype, but is a nominal subtype (involving type: ignore override).
type_state.record_negative_subtype_cache_entry(self._subtype_kind, left, right)
return False
if isinstance(right, TypeType):
item = right.item
if isinstance(item, TupleType):
item = mypy.typeops.tuple_fallback(item)
# TODO: this is a bit arbitrary, we should only skip Any-related cases.
if not self.proper_subtype:
if is_named_instance(left, "builtins.type"):
return self._is_subtype(TypeType(AnyType(TypeOfAny.special_form)), right)
if left.type.is_metaclass():
if isinstance(item, AnyType):
return True
if isinstance(item, Instance):
return is_named_instance(item, "builtins.object")
if isinstance(right, LiteralType) and left.last_known_value is not None:
return self._is_subtype(left.last_known_value, right)
if isinstance(right, CallableType):
# Special case: Instance can be a subtype of Callable.
call = find_member("__call__", left, left, is_operator=True)
if call:
return self._is_subtype(call, right)
return False
else:
return False
def visit_type_var(self, left: TypeVarType) -> bool:
right = self.right
if isinstance(right, TypeVarType) and left.id == right.id:
return True
if left.values and self._is_subtype(UnionType.make_union(left.values), right):
return True
return self._is_subtype(left.upper_bound, self.right)
def visit_param_spec(self, left: ParamSpecType) -> bool:
right = self.right
if (
isinstance(right, ParamSpecType)
and right.id == left.id
and right.flavor == left.flavor
):
return self._is_subtype(left.prefix, right.prefix)
if isinstance(right, Parameters) and are_trivial_parameters(right):
return True
return self._is_subtype(left.upper_bound, self.right)
def visit_type_var_tuple(self, left: TypeVarTupleType) -> bool:
right = self.right
if isinstance(right, TypeVarTupleType) and right.id == left.id:
return left.min_len >= right.min_len
return self._is_subtype(left.upper_bound, self.right)
def visit_unpack_type(self, left: UnpackType) -> bool:
# TODO: Ideally we should not need this (since it is not a real type).
# Instead callers (upper level types) should handle it when it appears in type list.
if isinstance(self.right, UnpackType):
return self._is_subtype(left.type, self.right.type)
if isinstance(self.right, Instance) and self.right.type.fullname == "builtins.object":
return True
return False
def visit_parameters(self, left: Parameters) -> bool:
if isinstance(self.right, Parameters):
return are_parameters_compatible(
left,
self.right,
is_compat=self._is_subtype,
# TODO: this should pass the current value, but then couple tests fail.
is_proper_subtype=False,
ignore_pos_arg_names=self.subtype_context.ignore_pos_arg_names,
)
else:
return False
def visit_callable_type(self, left: CallableType) -> bool:
right = self.right
if isinstance(right, CallableType):
if left.type_guard is not None and right.type_guard is not None:
if not self._is_subtype(left.type_guard, right.type_guard):
return False
elif left.type_is is not None and right.type_is is not None:
# For TypeIs we have to check both ways; it is unsafe to pass
# a TypeIs[Child] when a TypeIs[Parent] is expected, because
# if the narrower returns False, we assume that the narrowed value is
# *not* a Parent.
if not self._is_subtype(left.type_is, right.type_is) or not self._is_subtype(
right.type_is, left.type_is
):
return False
elif right.type_guard is not None and left.type_guard is None:
# This means that one function has `TypeGuard` and other does not.
# They are not compatible. See https://github.com/python/mypy/issues/11307
return False
elif right.type_is is not None and left.type_is is None:
# Similarly, if one function has `TypeIs` and the other does not,
# they are not compatible.
return False
return is_callable_compatible(
left,
right,
is_compat=self._is_subtype,
is_proper_subtype=self.proper_subtype,
ignore_pos_arg_names=self.subtype_context.ignore_pos_arg_names,
strict_concatenate=(
(self.options.extra_checks or self.options.strict_concatenate)
if self.options
else False
),
)
elif isinstance(right, Overloaded):
return all(self._is_subtype(left, item) for item in right.items)
elif isinstance(right, Instance):
if right.type.is_protocol and "__call__" in right.type.protocol_members:
# OK, a callable can implement a protocol with a `__call__` member.
# TODO: we should probably explicitly exclude self-types in this case.
call = find_member("__call__", right, left, is_operator=True)
assert call is not None
if self._is_subtype(left, call):
if len(right.type.protocol_members) == 1:
return True
if is_protocol_implementation(left.fallback, right, skip=["__call__"]):
return True
if right.type.is_protocol and left.is_type_obj():
ret_type = get_proper_type(left.ret_type)
if isinstance(ret_type, TupleType):
ret_type = mypy.typeops.tuple_fallback(ret_type)
if isinstance(ret_type, Instance) and is_protocol_implementation(
ret_type, right, proper_subtype=self.proper_subtype, class_obj=True
):
return True
return self._is_subtype(left.fallback, right)
elif isinstance(right, TypeType):
# This is unsound, we don't check the __init__ signature.
return left.is_type_obj() and self._is_subtype(left.ret_type, right.item)
else:
return False
def visit_tuple_type(self, left: TupleType) -> bool:
right = self.right
if isinstance(right, Instance):
if is_named_instance(right, "typing.Sized"):
return True
elif is_named_instance(right, TUPLE_LIKE_INSTANCE_NAMES):
if right.args:
iter_type = right.args[0]
else:
if self.proper_subtype:
return False
iter_type = AnyType(TypeOfAny.special_form)
if is_named_instance(right, "builtins.tuple") and isinstance(
get_proper_type(iter_type), AnyType
):
# TODO: We shouldn't need this special case. This is currently needed
# for isinstance(x, tuple), though it's unclear why.
return True
for li in left.items:
if isinstance(li, UnpackType):
unpack = get_proper_type(li.type)
if isinstance(unpack, TypeVarTupleType):
unpack = get_proper_type(unpack.upper_bound)
assert (
isinstance(unpack, Instance)
and unpack.type.fullname == "builtins.tuple"
)
li = unpack.args[0]
if not self._is_subtype(li, iter_type):
return False
return True
elif self._is_subtype(left.partial_fallback, right) and self._is_subtype(
mypy.typeops.tuple_fallback(left), right
):
return True
return False
elif isinstance(right, TupleType):
# If right has a variadic unpack this needs special handling. If there is a TypeVarTuple
# unpack, item count must coincide. If the left has variadic unpack but right
# doesn't have one, we will fall through to False down the line.
if self.variadic_tuple_subtype(left, right):
return True
if len(left.items) != len(right.items):
return False
if any(not self._is_subtype(l, r) for l, r in zip(left.items, right.items)):
return False
rfallback = mypy.typeops.tuple_fallback(right)
if is_named_instance(rfallback, "builtins.tuple"):
# No need to verify fallback. This is useful since the calculated fallback
# may be inconsistent due to how we calculate joins between unions vs.
# non-unions. For example, join(int, str) == object, whereas
# join(Union[int, C], Union[str, C]) == Union[int, str, C].
return True
lfallback = mypy.typeops.tuple_fallback(left)
return self._is_subtype(lfallback, rfallback)
else:
return False
def variadic_tuple_subtype(self, left: TupleType, right: TupleType) -> bool:
"""Check subtyping between two potentially variadic tuples.
Most non-trivial cases here are due to variadic unpacks like *tuple[X, ...],
we handle such unpacks as infinite unions Tuple[()] | Tuple[X] | Tuple[X, X] | ...
Note: the cases where right is fixed or has *Ts unpack should be handled
by the caller.
"""
right_unpack_index = find_unpack_in_list(right.items)
if right_unpack_index is None:
# This case should be handled by the caller.
return False
right_unpack = right.items[right_unpack_index]
assert isinstance(right_unpack, UnpackType)
right_unpacked = get_proper_type(right_unpack.type)
if not isinstance(right_unpacked, Instance):
# This case should be handled by the caller.
return False
assert right_unpacked.type.fullname == "builtins.tuple"
right_item = right_unpacked.args[0]
right_prefix = right_unpack_index
right_suffix = len(right.items) - right_prefix - 1
left_unpack_index = find_unpack_in_list(left.items)
if left_unpack_index is None:
# Simple case: left is fixed, simply find correct mapping to the right
# (effectively selecting item with matching length from an infinite union).
if len(left.items) < right_prefix + right_suffix:
return False
prefix, middle, suffix = split_with_prefix_and_suffix(
tuple(left.items), right_prefix, right_suffix
)
if not all(
self._is_subtype(li, ri) for li, ri in zip(prefix, right.items[:right_prefix])
):
return False
if right_suffix and not all(
self._is_subtype(li, ri) for li, ri in zip(suffix, right.items[-right_suffix:])
):
return False
return all(self._is_subtype(li, right_item) for li in middle)
else:
if len(left.items) < len(right.items):
# There are some items on the left that will never have a matching length
# on the right.
return False
left_unpack = left.items[left_unpack_index]
assert isinstance(left_unpack, UnpackType)
left_unpacked = get_proper_type(left_unpack.type)
if not isinstance(left_unpacked, Instance):
# *Ts unpacks can't be split.
return False
assert left_unpacked.type.fullname == "builtins.tuple"
left_item = left_unpacked.args[0]
# The most tricky case with two variadic unpacks we handle similar to union
# subtyping: *each* item on the left, must be a subtype of *some* item on the right.
# For this we first check the "asymptotic case", i.e. that both unpacks a subtypes,
# and then check subtyping for all finite overlaps.
if not self._is_subtype(left_item, right_item):
return False
left_prefix = left_unpack_index
left_suffix = len(left.items) - left_prefix - 1
max_overlap = max(0, right_prefix - left_prefix, right_suffix - left_suffix)
for overlap in range(max_overlap + 1):
repr_items = left.items[:left_prefix] + [left_item] * overlap
if left_suffix:
repr_items += left.items[-left_suffix:]
left_repr = left.copy_modified(items=repr_items)
if not self._is_subtype(left_repr, right):
return False
return True
def visit_typeddict_type(self, left: TypedDictType) -> bool:
right = self.right
if isinstance(right, Instance):
return self._is_subtype(left.fallback, right)
elif isinstance(right, TypedDictType):
if not left.names_are_wider_than(right):
return False
for name, l, r in left.zip(right):
# TODO: should we pass on the full subtype_context here and below?
if self.proper_subtype:
check = is_same_type(l, r)
else:
check = is_equivalent(
l,
r,
ignore_type_params=self.subtype_context.ignore_type_params,
options=self.options,
)
if not check:
return False
# Non-required key is not compatible with a required key since
# indexing may fail unexpectedly if a required key is missing.
# Required key is not compatible with a non-required key since
# the prior doesn't support 'del' but the latter should support
# it.
#
# NOTE: 'del' support is currently not implemented (#3550). We
# don't want to have to change subtyping after 'del' support
# lands so here we are anticipating that change.
if (name in left.required_keys) != (name in right.required_keys):
return False
# (NOTE: Fallbacks don't matter.)
return True
else:
return False
def visit_literal_type(self, left: LiteralType) -> bool:
if isinstance(self.right, LiteralType):
return left == self.right
else:
return self._is_subtype(left.fallback, self.right)
def visit_overloaded(self, left: Overloaded) -> bool:
right = self.right
if isinstance(right, Instance):
if right.type.is_protocol and "__call__" in right.type.protocol_members:
# same as for CallableType
call = find_member("__call__", right, left, is_operator=True)
assert call is not None
if self._is_subtype(left, call):
if len(right.type.protocol_members) == 1:
return True
if is_protocol_implementation(left.fallback, right, skip=["__call__"]):
return True
return self._is_subtype(left.fallback, right)
elif isinstance(right, CallableType):
for item in left.items:
if self._is_subtype(item, right):
return True
return False
elif isinstance(right, Overloaded):
if left == self.right:
# When it is the same overload, then the types are equal.
return True
# Ensure each overload in the right side (the supertype) is accounted for.
previous_match_left_index = -1
matched_overloads = set()
for right_item in right.items:
found_match = False
for left_index, left_item in enumerate(left.items):
subtype_match = self._is_subtype(left_item, right_item)
# Order matters: we need to make sure that the index of
# this item is at least the index of the previous one.
if subtype_match and previous_match_left_index <= left_index:
previous_match_left_index = left_index
found_match = True
matched_overloads.add(left_index)
break
else:
# If this one overlaps with the supertype in any way, but it wasn't
# an exact match, then it's a potential error.
strict_concat = (
(self.options.extra_checks or self.options.strict_concatenate)
if self.options
else False
)
if left_index not in matched_overloads and (
is_callable_compatible(
left_item,
right_item,
is_compat=self._is_subtype,
is_proper_subtype=self.proper_subtype,
ignore_return=True,
ignore_pos_arg_names=self.subtype_context.ignore_pos_arg_names,
strict_concatenate=strict_concat,
)
or is_callable_compatible(
right_item,
left_item,
is_compat=self._is_subtype,
is_proper_subtype=self.proper_subtype,
ignore_return=True,
ignore_pos_arg_names=self.subtype_context.ignore_pos_arg_names,
strict_concatenate=strict_concat,
)
):
return False
if not found_match:
return False
return True
elif isinstance(right, UnboundType):
return True
elif isinstance(right, TypeType):
# All the items must have the same type object status, so