GeezerVison is showing github.com — Support protocol checks for self-types in tuple types (#21535) · python/mypy@21e2859
File treeExpand file treeCollapse file tree Open diff view settings Expand file treeCollapse file tree Open diff view settings Collapse file Copy file name to clipboardExpand all lines: mypy/constraints.py +19-2Lines changed: 19 additions & 2 deletions | Original file line number | Diff line number | Diff line change |
|---|
@@ -797,7 +797,7 @@ def visit_instance(self, template: Instance) -> list[Constraint]: | 797 | 797 | if isinstance(actual, Instance): | 798 | 798 | instance = actual | 799 | 799 | erased = erase_typevars(template) | 800 | | - assert isinstance(erased, Instance) # type: ignore[misc] | | 800 | + assert isinstance(erased, ProperType) and isinstance(erased, Instance) | 801 | 801 | # We always try nominal inference if possible, | 802 | 802 | # it is much faster than the structural one. | 803 | 803 | if self.direction == SUBTYPE_OF and template.type.has_base(instance.type.fullname): | @@ -996,7 +996,24 @@ def visit_instance(self, template: Instance) -> list[Constraint]: | 996 | 996 | res.extend(cb) | 997 | 997 | return res | 998 | 998 | elif isinstance(actual, TupleType) and self.direction == SUPERTYPE_OF: | 999 | | - return infer_constraints(template, mypy.typeops.tuple_fallback(actual), self.direction) | | 999 | + instance = mypy.typeops.tuple_fallback(actual) | | 1000 | + erased = erase_typevars(template) | | 1001 | + assert isinstance(erased, ProperType) and isinstance(erased, Instance) | | 1002 | + # Special-case protocols before using fallback to get more precise constraints | | 1003 | + # for custom tuple types like NamedTuples. | | 1004 | + if ( | | 1005 | + template.type.is_protocol | | 1006 | + and self.direction == SUPERTYPE_OF | | 1007 | + and not any(template == t for t in reversed(template.type.inferring)) | | 1008 | + and mypy.subtypes.is_protocol_implementation(instance, erased, skip=["__call__"]) | | 1009 | + ): | | 1010 | + template.type.inferring.append(template) | | 1011 | + res = self.infer_constraints_from_protocol_members( | | 1012 | + instance, template, original_actual, template | | 1013 | + ) | | 1014 | + template.type.inferring.pop() | | 1015 | + return res | | 1016 | + return infer_constraints(template, instance, self.direction) | 1000 | 1017 | elif isinstance(actual, TypeVarType): | 1001 | 1018 | if not actual.values and not actual.id.is_meta_var(): | 1002 | 1019 | return infer_constraints(template, actual.upper_bound, self.direction) | |
Collapse file Copy file name to clipboardExpand all lines: mypy/messages.py +17-6Lines changed: 17 additions & 6 deletions | Original file line number | Diff line number | Diff line change |
|---|
@@ -2220,8 +2220,9 @@ def report_protocol_problems( | 2220 | 2220 | class_obj = False | 2221 | 2221 | is_module = False | 2222 | 2222 | skip = [] | | 2223 | + original_subtype = subtype | 2223 | 2224 | if isinstance(subtype, TupleType): | 2224 | | - subtype = subtype.partial_fallback | | 2225 | + subtype = mypy.typeops.tuple_fallback(subtype) | 2225 | 2226 | elif isinstance(subtype, TypedDictType): | 2226 | 2227 | subtype = subtype.fallback | 2227 | 2228 | elif isinstance(subtype, TypeType): | @@ -2233,7 +2234,7 @@ def report_protocol_problems( | 2233 | 2234 | if subtype.is_type_obj(): | 2234 | 2235 | ret_type = get_proper_type(subtype.ret_type) | 2235 | 2236 | if isinstance(ret_type, TupleType): | 2236 | | - ret_type = ret_type.partial_fallback | | 2237 | + ret_type = mypy.typeops.tuple_fallback(ret_type) | 2237 | 2238 | if not isinstance(ret_type, Instance): | 2238 | 2239 | return | 2239 | 2240 | class_obj = True | @@ -2243,6 +2244,10 @@ def report_protocol_problems( | 2243 | 2244 | skip = ["__call__"] | 2244 | 2245 | if subtype.extra_attrs and subtype.extra_attrs.mod_name: | 2245 | 2246 | is_module = True | | 2247 | + if not isinstance(original_subtype, TupleType): | | 2248 | + # Apart from instances, only tuples are supported by | | 2249 | + # is_protocol_implementation() for now. | | 2250 | + original_subtype = subtype | 2246 | 2251 |
| 2247 | 2252 | # Report missing members | 2248 | 2253 | missing = get_missing_protocol_members(subtype, supertype, skip=skip) | @@ -2274,7 +2279,7 @@ def report_protocol_problems( | 2274 | 2279 |
| 2275 | 2280 | # Report member type conflicts | 2276 | 2281 | conflict_types = get_conflict_protocol_types( | 2277 | | - subtype, supertype, class_obj=class_obj, options=self.options | | 2282 | + subtype, original_subtype, supertype, class_obj=class_obj, options=self.options | 2278 | 2283 | ) | 2279 | 2284 | if conflict_types and ( | 2280 | 2285 | not is_subtype(subtype, erase_type(supertype), options=self.options) | @@ -3191,7 +3196,11 @@ def get_missing_protocol_members(left: Instance, right: Instance, skip: list[str | 3191 | 3196 |
| 3192 | 3197 |
| 3193 | 3198 | def get_conflict_protocol_types( | 3194 | | - left: Instance, right: Instance, class_obj: bool = False, options: Options | None = None | | 3199 | + left: Instance, | | 3200 | + original_left: Type, | | 3201 | + right: Instance, | | 3202 | + class_obj: bool = False, | | 3203 | + options: Options | None = None, | 3195 | 3204 | ) -> list[tuple[str, Type, Type, bool]]: | 3196 | 3205 | """Find members that are defined in 'left' but have incompatible types. | 3197 | 3206 | Return them as a list of ('member', 'got', 'expected', 'is_lvalue'). | @@ -3203,7 +3212,7 @@ def get_conflict_protocol_types( | 3203 | 3212 | continue | 3204 | 3213 | supertype = find_member(member, right, left) | 3205 | 3214 | assert supertype is not None | 3206 | | - subtype = get_protocol_member(left, member, class_obj) | | 3215 | + subtype = get_protocol_member(left, original_left, member, class_obj) | 3207 | 3216 | if not subtype: | 3208 | 3217 | continue | 3209 | 3218 | is_compat = is_subtype(subtype, supertype, ignore_pos_arg_names=True, options=options) | @@ -3219,7 +3228,9 @@ def get_conflict_protocol_types( | 3219 | 3228 | different_setter = True | 3220 | 3229 | supertype = set_supertype | 3221 | 3230 | if IS_EXPLICIT_SETTER in get_member_flags(member, left): | 3222 | | - set_subtype = get_protocol_member(left, member, class_obj, is_lvalue=True) | | 3231 | + set_subtype = get_protocol_member( | | 3232 | + left, original_left, member, class_obj, is_lvalue=True | | 3233 | + ) | 3223 | 3234 | if set_subtype and not is_same_type(set_subtype, subtype): | 3224 | 3235 | different_setter = True | 3225 | 3236 | subtype = set_subtype | |
Collapse file Copy file name to clipboardExpand all lines: mypy/subtypes.py +20-7Lines changed: 20 additions & 7 deletions | Original file line number | Diff line number | Diff line change |
|---|
@@ -811,6 +811,12 @@ def visit_tuple_type(self, left: TupleType) -> bool: | 811 | 811 | mypy.typeops.tuple_fallback(left), right | 812 | 812 | ): | 813 | 813 | return True | | 814 | + elif right.type.is_protocol and is_protocol_implementation( | | 815 | + left, right, proper_subtype=self.proper_subtype | | 816 | + ): | | 817 | + # Special-case protocols to get precise binding of self type for | | 818 | + # custom tuple types like NamedTuples. | | 819 | + return True | 814 | 820 | return False | 815 | 821 | elif isinstance(right, TupleType): | 816 | 822 | # If right has a variadic unpack this needs special handling. If there is a TypeVarTuple | @@ -1185,7 +1191,7 @@ def pop_on_exit(stack: list[tuple[T, T]], left: T, right: T) -> Iterator[None]: | 1185 | 1191 |
| 1186 | 1192 |
| 1187 | 1193 | def is_protocol_implementation( | 1188 | | - left: Instance, | | 1194 | + left: Instance | TupleType, | 1189 | 1195 | right: Instance, | 1190 | 1196 | proper_subtype: bool = False, | 1191 | 1197 | class_obj: bool = False, | @@ -1212,6 +1218,11 @@ def f(self) -> A: ... | 1212 | 1218 | assert right.type.is_protocol | 1213 | 1219 | if skip is None: | 1214 | 1220 | skip = [] | | 1221 | + # Preserve original left type for precise self-type binding. Only tuple types are | | 1222 | + # supported for now. | | 1223 | + original_left = left | | 1224 | + if isinstance(left, TupleType): | | 1225 | + left = mypy.typeops.tuple_fallback(left) | 1215 | 1226 | # We need to record this check to generate protocol fine-grained dependencies. | 1216 | 1227 | type_state.record_protocol_subtype_check(left.type, right.type) | 1217 | 1228 | # nominal subtyping currently ignores '__init__' and '__new__' signatures | @@ -1234,10 +1245,10 @@ def f(self) -> A: ... | 1234 | 1245 | ignore_names = member != "__call__" # __call__ can be passed kwargs | 1235 | 1246 | # The third argument below indicates to what self type is bound. | 1236 | 1247 | # We always bind self to the subtype. (Similarly to nominal types). | 1237 | | - supertype = find_member(member, right, left) | | 1248 | + supertype = find_member(member, right, original_left) | 1238 | 1249 | assert supertype is not None | 1239 | 1250 |
| 1240 | | - subtype = get_protocol_member(left, member, class_obj) | | 1251 | + subtype = get_protocol_member(left, original_left, member, class_obj) | 1241 | 1252 | # Useful for debugging: | 1242 | 1253 | # print(member, 'of', left, 'has type', subtype) | 1243 | 1254 | # print(member, 'of', right, 'has type', supertype) | @@ -1264,9 +1275,11 @@ def f(self) -> A: ... | 1264 | 1275 | if IS_SETTABLE in superflags: | 1265 | 1276 | # Check opposite direction for settable attributes. | 1266 | 1277 | if IS_EXPLICIT_SETTER in superflags: | 1267 | | - supertype = find_member(member, right, left, is_lvalue=True) | | 1278 | + supertype = find_member(member, right, original_left, is_lvalue=True) | 1268 | 1279 | if IS_EXPLICIT_SETTER in subflags: | 1269 | | - subtype = get_protocol_member(left, member, class_obj, is_lvalue=True) | | 1280 | + subtype = get_protocol_member( | | 1281 | + left, original_left, member, class_obj, is_lvalue=True | | 1282 | + ) | 1270 | 1283 | # At this point we know attribute is present on subtype, otherwise we | 1271 | 1284 | # would return False above. | 1272 | 1285 | assert supertype is not None and subtype is not None | @@ -1305,7 +1318,7 @@ def f(self) -> A: ... | 1305 | 1318 |
| 1306 | 1319 |
| 1307 | 1320 | def get_protocol_member( | 1308 | | - left: Instance, member: str, class_obj: bool, is_lvalue: bool = False | | 1321 | + left: Instance, original_left: Type, member: str, class_obj: bool, is_lvalue: bool = False | 1309 | 1322 | ) -> Type | None: | 1310 | 1323 | if member == "__call__" and class_obj: | 1311 | 1324 | # Special case: class objects always have __call__ that is just the constructor. | @@ -1316,7 +1329,7 @@ def get_protocol_member( | 1316 | 1329 | # if constructor signature didn't match, this can cause many false negatives. | 1317 | 1330 | return None | 1318 | 1331 |
| 1319 | | - subtype = find_member(member, left, left, class_obj=class_obj, is_lvalue=is_lvalue) | | 1332 | + subtype = find_member(member, left, original_left, class_obj=class_obj, is_lvalue=is_lvalue) | 1320 | 1333 | if isinstance(subtype, PartialType): | 1321 | 1334 | subtype = ( | 1322 | 1335 | NoneType() | |
Collapse file Copy file name to clipboardExpand all lines: test-data/unit/check-protocols.test +30Lines changed: 30 additions & 0 deletions | Original file line number | Diff line number | Diff line change |
|---|
@@ -4779,3 +4779,33 @@ class A(Protocol): | 4779 | 4779 | pass | 4780 | 4780 |
| 4781 | 4781 | [builtins fixtures/tuple.pyi] | | 4782 | + | | 4783 | +[case testTupleTypeSelfTypeProto] | | 4784 | +from typing import Protocol, TypeVar | | 4785 | + | | 4786 | +R = TypeVar("R", covariant=True) | | 4787 | + | | 4788 | +class P(Protocol[R]): | | 4789 | + def rep(self) -> R: ... | | 4790 | + | | 4791 | +T = TypeVar("T") | | 4792 | +def rep(x: P[T]) -> T: ... | | 4793 | + | | 4794 | +class C(tuple[int, str]): | | 4795 | + def rep(self: T) -> T: ... | | 4796 | + | | 4797 | +t: C | | 4798 | +reveal_type(t) # N: Revealed type is "tuple[builtins.int, builtins.str, fallback=__main__.C]" | | 4799 | +reveal_type(rep(t)) # N: Revealed type is "tuple[builtins.int, builtins.str, fallback=__main__.C]" | | 4800 | + | | 4801 | +def ok_rep(x: P[tuple[int, str]]) -> None: ... | | 4802 | +ok_rep(t) | | 4803 | + | | 4804 | +def bad_rep(x: P[tuple[str, int]]) -> None: ... | | 4805 | +bad_rep(t) # E: Argument 1 to "bad_rep" has incompatible type "C"; expected "P[tuple[str, int]]" \ | | 4806 | + # N: Following member(s) of "C" have conflicts: \ | | 4807 | + # N: Expected: \ | | 4808 | + # N: def rep(self) -> tuple[str, int] \ | | 4809 | + # N: Got: \ | | 4810 | + # N: def rep(self) -> C | | 4811 | +[builtins fixtures/tuple.pyi] |
|