Skip to content

Report attribute access errors for TypeVar bound to Union. #11140

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
merged 3 commits into from
Sep 19, 2021
Merged
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
10 changes: 10 additions & 0 deletions mypy/messages.py
Original file line number Diff line number Diff line change
Expand Up @@ -345,6 +345,16 @@ def has_no_attr(self,
self.fail('Item {} of {} has no attribute "{}"{}'.format(
typ_format, orig_type_format, member, extra), context,
code=codes.UNION_ATTR)
elif isinstance(original_type, TypeVarType):
bound = get_proper_type(original_type.upper_bound)
if isinstance(bound, UnionType):
typ_fmt, bound_fmt = format_type_distinctly(typ, bound)
original_type_fmt = format_type(original_type)
self.fail(
'Item {} of the upper bound {} of type variable {} has no '
'attribute "{}"{}'.format(
typ_fmt, bound_fmt, original_type_fmt, member, extra),
context, code=codes.UNION_ATTR)
return AnyType(TypeOfAny.from_error)

def unsupported_operand_types(self,
Expand Down
24 changes: 24 additions & 0 deletions test-data/unit/check-generic-subtyping.test
Original file line number Diff line number Diff line change
Expand Up @@ -817,4 +817,28 @@ class Y(Generic[T]):
def f(self) -> T:
return U() # E: Incompatible return value type (got "U", expected "T")


[case testTypeVarBoundToUnionAttributeAccess]
from typing import Union, TypeVar

class U:
a: float
class V:
b: float
class W:
c: float

T = TypeVar("T", bound=Union[U, V, W])

def f(x: T) -> None:
x.a # E
x.b = 1.0 # E
del x.c # E

[out]
main:13: error: Item "V" of the upper bound "Union[U, V, W]" of type variable "T" has no attribute "a"
main:13: error: Item "W" of the upper bound "Union[U, V, W]" of type variable "T" has no attribute "a"
main:14: error: Item "U" of the upper bound "Union[U, V, W]" of type variable "T" has no attribute "b"
main:14: error: Item "W" of the upper bound "Union[U, V, W]" of type variable "T" has no attribute "b"
main:15: error: Item "U" of the upper bound "Union[U, V, W]" of type variable "T" has no attribute "c"
main:15: error: Item "V" of the upper bound "Union[U, V, W]" of type variable "T" has no attribute "c"