Skip to content

Commit b94b04c

Browse files
authored
Report attribute access errors for TypeVar bound to Union (#11140)
1 parent 75d417f commit b94b04c

File tree

2 files changed

+34
-0
lines changed

2 files changed

+34
-0
lines changed

mypy/messages.py

+10
Original file line numberDiff line numberDiff line change
@@ -345,6 +345,16 @@ def has_no_attr(self,
345345
self.fail('Item {} of {} has no attribute "{}"{}'.format(
346346
typ_format, orig_type_format, member, extra), context,
347347
code=codes.UNION_ATTR)
348+
elif isinstance(original_type, TypeVarType):
349+
bound = get_proper_type(original_type.upper_bound)
350+
if isinstance(bound, UnionType):
351+
typ_fmt, bound_fmt = format_type_distinctly(typ, bound)
352+
original_type_fmt = format_type(original_type)
353+
self.fail(
354+
'Item {} of the upper bound {} of type variable {} has no '
355+
'attribute "{}"{}'.format(
356+
typ_fmt, bound_fmt, original_type_fmt, member, extra),
357+
context, code=codes.UNION_ATTR)
348358
return AnyType(TypeOfAny.from_error)
349359

350360
def unsupported_operand_types(self,

test-data/unit/check-generic-subtyping.test

+24
Original file line numberDiff line numberDiff line change
@@ -817,4 +817,28 @@ class Y(Generic[T]):
817817
def f(self) -> T:
818818
return U() # E: Incompatible return value type (got "U", expected "T")
819819

820+
821+
[case testTypeVarBoundToUnionAttributeAccess]
822+
from typing import Union, TypeVar
823+
824+
class U:
825+
a: float
826+
class V:
827+
b: float
828+
class W:
829+
c: float
830+
831+
T = TypeVar("T", bound=Union[U, V, W])
832+
833+
def f(x: T) -> None:
834+
x.a # E
835+
x.b = 1.0 # E
836+
del x.c # E
837+
820838
[out]
839+
main:13: error: Item "V" of the upper bound "Union[U, V, W]" of type variable "T" has no attribute "a"
840+
main:13: error: Item "W" of the upper bound "Union[U, V, W]" of type variable "T" has no attribute "a"
841+
main:14: error: Item "U" of the upper bound "Union[U, V, W]" of type variable "T" has no attribute "b"
842+
main:14: error: Item "W" of the upper bound "Union[U, V, W]" of type variable "T" has no attribute "b"
843+
main:15: error: Item "U" of the upper bound "Union[U, V, W]" of type variable "T" has no attribute "c"
844+
main:15: error: Item "V" of the upper bound "Union[U, V, W]" of type variable "T" has no attribute "c"

0 commit comments

Comments
 (0)