-
-
Notifications
You must be signed in to change notification settings - Fork 2.9k
Fix class method type variables #7862
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
Merged
ilevkivskyi
merged 9 commits into
python:master
from
ilevkivskyi:fix-class-method-type-vars
Nov 12, 2019
Merged
Changes from all commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
47cb240
Start fixing
ilevkivskyi 534976e
Some fixes
ilevkivskyi 0a79576
Tweak also direct cls call
ilevkivskyi 2866429
Update tests
ilevkivskyi b7efd22
Fix lint
ilevkivskyi f938d1a
Merge remote-tracking branch 'upstream/master' into fix-class-method-…
ilevkivskyi a59cecf
Fix self-check
ilevkivskyi 5921ef9
Address CR
3bbf7de
Put back an empty line
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,6 +1,6 @@ | ||
"""Type checking of attribute access""" | ||
|
||
from typing import cast, Callable, Optional, Union | ||
from typing import cast, Callable, Optional, Union, List | ||
from typing_extensions import TYPE_CHECKING | ||
|
||
from mypy.types import ( | ||
|
@@ -240,7 +240,9 @@ def analyze_type_callable_member_access(name: str, | |
# This check makes sure that when we encounter an operator, we skip looking up | ||
# the corresponding method in the current instance to avoid this edge case. | ||
# See https://github.com/python/mypy/pull/1787 for more info. | ||
result = analyze_class_attribute_access(ret_type, name, mx) | ||
# TODO: do not rely on same type variables being present in all constructor overloads. | ||
result = analyze_class_attribute_access(ret_type, name, mx, | ||
original_vars=typ.items()[0].variables) | ||
if result: | ||
return result | ||
# Look up from the 'type' type. | ||
|
@@ -649,8 +651,15 @@ def f(self: S) -> T: ... | |
def analyze_class_attribute_access(itype: Instance, | ||
name: str, | ||
mx: MemberContext, | ||
override_info: Optional[TypeInfo] = None) -> Optional[Type]: | ||
"""original_type is the type of E in the expression E.var""" | ||
override_info: Optional[TypeInfo] = None, | ||
original_vars: Optional[List[TypeVarDef]] = None | ||
) -> Optional[Type]: | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Document the new argument. |
||
"""Analyze access to an attribute on a class object. | ||
|
||
itype is the return type of the class object callable, original_type is the type | ||
of E in the expression E.var, original_vars are type variables of the class callable | ||
(for generic classes). | ||
""" | ||
info = itype.type | ||
if override_info: | ||
info = override_info | ||
|
@@ -718,7 +727,7 @@ def analyze_class_attribute_access(itype: Instance, | |
# C[int].x # Also an error, since C[int] is same as C at runtime | ||
if isinstance(t, TypeVarType) or has_type_vars(t): | ||
# Exception: access on Type[...], including first argument of class methods is OK. | ||
if not isinstance(get_proper_type(mx.original_type), TypeType): | ||
if not isinstance(get_proper_type(mx.original_type), TypeType) or node.implicit: | ||
if node.node.is_classvar: | ||
message = message_registry.GENERIC_CLASS_VAR_ACCESS | ||
else: | ||
|
@@ -737,7 +746,7 @@ def analyze_class_attribute_access(itype: Instance, | |
if isinstance(t, FunctionLike) and is_classmethod: | ||
t = check_self_arg(t, mx.self_type, False, mx.context, name, mx.msg) | ||
result = add_class_tvars(t, itype, isuper, is_classmethod, | ||
mx.builtin_type, mx.self_type) | ||
mx.builtin_type, mx.self_type, original_vars=original_vars) | ||
if not mx.is_lvalue: | ||
result = analyze_descriptor_access(mx.original_type, result, mx.builtin_type, | ||
mx.msg, mx.context, chk=mx.chk) | ||
|
@@ -783,7 +792,8 @@ def analyze_class_attribute_access(itype: Instance, | |
def add_class_tvars(t: ProperType, itype: Instance, isuper: Optional[Instance], | ||
is_classmethod: bool, | ||
builtin_type: Callable[[str], Instance], | ||
original_type: Type) -> Type: | ||
original_type: Type, | ||
original_vars: Optional[List[TypeVarDef]] = None) -> Type: | ||
"""Instantiate type variables during analyze_class_attribute_access, | ||
e.g T and Q in the following: | ||
|
||
|
@@ -796,10 +806,10 @@ class B(A[str]): pass | |
B.foo() | ||
|
||
original_type is the value of the type B in the expression B.foo() or the corresponding | ||
component in case if a union (this is used to bind the self-types). | ||
component in case if a union (this is used to bind the self-types); original_vars are type | ||
variables of the class callable on which the method was accessed. | ||
""" | ||
# TODO: verify consistency between Q and T | ||
info = itype.type # type: TypeInfo | ||
if is_classmethod: | ||
assert isuper is not None | ||
t = get_proper_type(expand_type_by_instance(t, isuper)) | ||
|
@@ -815,22 +825,15 @@ class B(A[str]): pass | |
# This behaviour is useful for defining alternative constructors for generic classes. | ||
# To achieve such behaviour, we add the class type variables that are still free | ||
# (i.e. appear in the return type of the class object on which the method was accessed). | ||
free_ids = {t.id for t in itype.args if isinstance(t, TypeVarType)} | ||
|
||
if isinstance(t, CallableType): | ||
# NOTE: in practice either all or none of the variables are free, since | ||
# visit_type_application() will detect any type argument count mismatch and apply | ||
# a correct number of Anys. | ||
tvars = [TypeVarDef(n, n, i + 1, [], builtin_type('builtins.object'), tv.variance) | ||
for (i, n), tv in zip(enumerate(info.type_vars), info.defn.type_vars) | ||
# use 'is' to avoid id clashes with unrelated variables | ||
if any(tv.id is id for id in free_ids)] | ||
tvars = original_vars if original_vars is not None else [] | ||
if is_classmethod: | ||
t = bind_self(t, original_type, is_classmethod=True) | ||
return t.copy_modified(variables=tvars + t.variables) | ||
elif isinstance(t, Overloaded): | ||
return Overloaded([cast(CallableType, add_class_tvars(item, itype, isuper, is_classmethod, | ||
builtin_type, original_type)) | ||
builtin_type, original_type, | ||
original_vars=original_vars)) | ||
for item in t.items()]) | ||
return t | ||
|
||
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I wonder if picking the first item may cause problems with overloaded methods. If so, it would be good to add a comment and maybe create a follow-up issue (unless the fix is trivial).
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I think I use thus because I noticed overloaded constructors have "uniform" type variables, but maybe it is not guaranteed, I will add a test case and a TODO here.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Funny enough, when adding a test for this (that seem to work well as I said) I discovered a bug because dozen lines above we use
ret_type = typ.items()[0].ret_type
and now this is clearly wrong.