Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix inference for overloaded __call__ with generic self #16053

Merged
merged 15 commits into from Sep 19, 2023

Conversation

hauntsaninja
Copy link
Collaborator

@hauntsaninja hauntsaninja commented Sep 5, 2023

Fixes #8283

Co-authored-by: ilevkivskyi

@github-actions

This comment has been minimized.

@hauntsaninja hauntsaninja marked this pull request as ready for review September 5, 2023 22:24
@@ -898,7 +897,7 @@ def f(self: S) -> T: ...
selfarg = get_proper_type(item.arg_types[0])
if subtypes.is_subtype(dispatched_arg_type, erase_typevars(erase_to_bound(selfarg))):
new_items.append(item)
elif isinstance(selfarg, ParamSpecType):
elif isinstance(selfarg, (ParamSpecType, TupleType)):
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Bit of a lazy hack to keep testTypeTupleCall and testTypeNamedTupleCall green

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This looks suspicious. ParamSpecType doesn't really make sense here (and it is unlikely it can get there without previously emitting an error), but TupleType is relatively common self-type for various user defined tuple types. Is it needed because type erasure touches some unhandled/incorectly handled corner case in is_subtype()? If yes, then that should be fixed instead.

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah, needs a change in is_subtype: #16073

@hauntsaninja hauntsaninja marked this pull request as draft September 9, 2023 06:12
@hauntsaninja
Copy link
Collaborator Author

Converting to draft since this needs #16073 and a regression test

@hauntsaninja
Copy link
Collaborator Author

hauntsaninja commented Sep 15, 2023

@ilevkivskyi lol, looks like this PR gives me the test case I wanted in #16108 (comment). We create these kind of types in mypy.typevars.fill_typevars (at least).

I changed subtyping logic again to fix the case I care about by checking if all args are subtype of Any (for non-generic classes there are no args). But this isn't enough, since it doesn't work for callable generic tuple subclasses. So I added new clause, which works slightly more, but is a little sketchy

@hauntsaninja hauntsaninja marked this pull request as ready for review September 15, 2023 07:28
@github-actions

This comment has been minimized.

@github-actions

This comment has been minimized.

mypy/subtypes.py Outdated
return not self.proper_subtype
if mapped.type.tuple_type:
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This additional branch looks like a hack. We shouldn't need this. I think the real bug is that we are passing incomplete information when accessing __call__ on a tuple type. This diff I think is a (much) more cleaner fix:

--- a/mypy/checkexpr.py
+++ b/mypy/checkexpr.py
@@ -1476,6 +1476,7 @@ class ExpressionChecker(ExpressionVisitor[Type]):
         callable_node: Expression | None = None,
         callable_name: str | None = None,
         object_type: Type | None = None,
+        original_type: Type | None = None,
     ) -> tuple[Type, Type]:
         """Type check a call.
 
@@ -1538,7 +1539,7 @@ class ExpressionChecker(ExpressionVisitor[Type]):
                 is_super=False,
                 is_operator=True,
                 msg=self.msg,
-                original_type=callee,
+                original_type=original_type or callee,
                 chk=self.chk,
                 in_literal_context=self.is_literal_context(),
             )
@@ -1579,6 +1580,7 @@ class ExpressionChecker(ExpressionVisitor[Type]):
                 callable_node,
                 callable_name,
                 object_type,
+                original_type=callee,
             )
         else:
             return self.msg.not_callable(callee, context), AnyType(TypeOfAny.from_error)

mypy/subtypes.py Outdated
if mapped.type.fullname == "builtins.tuple" and isinstance(
get_proper_type(mapped.args[0]), AnyType
):
if all(isinstance(get_proper_type(a), AnyType) for a in mapped.args):
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think this should actually be combined with the if just above. I just realised that the if I added is incomplete, in fact if all type argument are either Any or *tuple[Any, ...] we are still good. But currently we are only considering only plain *tuple[Any, ...] or e.g. Any, Any, Any, while missing Any, *tuple[Any, ...], Any, which should be equally fine (note you don't need to check number of unpacks, it is already validated during semantic analyzis).

Note this also equally applies to the equivalent special case for plain instances I added around line 538. You may fix that as well if you want while you are at it.

@ilevkivskyi
Copy link
Member

@hauntsaninja Looks better, but I think there is even cleaner solution. I left couple comments.

@hauntsaninja
Copy link
Collaborator Author

Thanks for the review!

@github-actions

This comment has been minimized.

Copy link
Member

@ilevkivskyi ilevkivskyi left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks, LG! I have one last style comment.

mypy/subtypes.py Outdated
@@ -454,19 +454,22 @@ def visit_instance(self, left: Instance) -> bool:
if isinstance(unpacked, Instance):
return self._is_subtype(left, unpacked)
if left.type.has_base(right.partial_fallback.type.fullname):
if self.proper_subtype:
return False
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

return False (here an in few places below) is now correct, but may be error prone if we will add another if after this case in the (distant) future. I like how you use if not self.proper_subtype + breaks + else: return True. I think it would be better to do the same here (and maybe move the comment below to between if left.type.has_base() and if not self.proper_subtype).

@github-actions
Copy link
Contributor

Diff from mypy_primer, showing the effect of this PR on open source code:

prefect (https://github.com/PrefectHQ/prefect)
- src/prefect/server/utilities/database.py:631: error: Invalid self argument "URL" to attribute function "get_dialect" with type "Callable[[URL, bool], type[Dialect]]"  [misc]

@hauntsaninja hauntsaninja merged commit 249f3f8 into python:master Sep 19, 2023
18 checks passed
@hauntsaninja hauntsaninja deleted the generic-call branch September 19, 2023 06:53
@hauntsaninja
Copy link
Collaborator Author

Thanks for all the reviews!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Invalid type inferred when overloading __call__ with generic self-type
2 participants