Skip to content

Commit

Permalink
Report attribute access errors for TypeVar bound to Union (#11140)
Browse files Browse the repository at this point in the history
  • Loading branch information
tyralla authored Sep 19, 2021
1 parent 75d417f commit b94b04c
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 0 deletions.
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"

0 comments on commit b94b04c

Please sign in to comment.