Skip to content

Fix generic type expansion for attribute acces on class #2879

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

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion mypy/checkmember.py
Original file line number Diff line number Diff line change
Expand Up @@ -383,7 +383,8 @@ def analyze_class_attribute_access(itype: Instance,
if isinstance(t, PartialType):
return handle_partial_attribute_type(t, is_lvalue, msg, node.node)
is_classmethod = is_decorated and cast(Decorator, node.node).func.is_class
return add_class_tvars(t, itype, is_classmethod, builtin_type, original_type)
res = add_class_tvars(t, itype, is_classmethod, builtin_type, original_type)
return expand_type_by_instance(res, itype)
elif isinstance(node.node, Var):
not_ready_callback(name, context)
return AnyType()
Expand Down
33 changes: 33 additions & 0 deletions test-data/unit/check-generics.test
Original file line number Diff line number Diff line change
Expand Up @@ -1534,6 +1534,39 @@ class A:
def f(cls) -> None: pass
[builtins fixtures/classmethod.pyi]

[case testGenericTypeExpansionOnClassAccess]
from typing import TypeVar, Generic
from typing import Generic, TypeVar

T = TypeVar('T')
class A(Generic[T]):
def f(self, x: T) -> None:
pass
class B(Generic[T]):
x = None # type: A[T]

B[int].x.f(0)
B[int].x.f('hi') # E: Argument 1 to "f" of "A" has incompatible type "str"; expected "int"
[builtins fixtures/classmethod.pyi]

[case testGenericClassVariableTypeExpansion]
from typing import TypeVar, Generic, List, Tuple, Union
T = TypeVar('T')
S = TypeVar('S')
class A(Generic[T]):
x = None # type: List[T]

A[int].x.append(42)
A[int].x.append('hi') # E: Argument 1 to "append" of "list" has incompatible type "str"; expected "int"

class B(Generic[T, S]):
x = None # type: Tuple[T, S]
y = None # type: Union[T, A[S]]

reveal_type(B[int, str].x) # E: Revealed type is 'Tuple[builtins.int*, builtins.str*]'
reveal_type(B[int, str].y) # E: Revealed type is 'Union[builtins.int*, __main__.A[builtins.str*]]'
[builtins fixtures/list.pyi]

[case testGenericOperatorMethodOverlapping]
from typing import TypeVar, Generic, Tuple
T = TypeVar('T')
Expand Down