Skip to content

Add note for union types with missing attribute #17575

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
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
16 changes: 16 additions & 0 deletions mypy/messages.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@
Expression,
FuncDef,
IndexExpr,
MemberExpr,
MypyFile,
NameExpr,
ReturnStmt,
Expand All @@ -48,6 +49,7 @@
SymbolTable,
TypeInfo,
Var,
get_member_expr_fullname,
reverse_builtin_aliases,
)
from mypy.operators import op_methods, op_methods_to_symbols
Expand Down Expand Up @@ -534,6 +536,20 @@ def has_no_attr(
context,
code=codes.UNION_ATTR,
)
if isinstance(context, NameExpr):
var_name = f" {context.name}"
elif isinstance(context, MemberExpr) and isinstance(context.expr, NameExpr):
var_name = f" {context.expr.name}"
elif isinstance(context, MemberExpr) and isinstance(context.expr, MemberExpr):
var_name = f" {get_member_expr_fullname(context.expr)}"
else:
var_name = " <variable name>"
self.note(
f"You can use 'if hasattr({var_name}, '{member}'):' to guard against missing attribute error",
context,
code=codes.UNION_ATTR,
)

return codes.UNION_ATTR
elif isinstance(original_type, TypeVarType):
bound = get_proper_type(original_type.upper_bound)
Expand Down
3 changes: 2 additions & 1 deletion test-data/unit/check-classes.test
Original file line number Diff line number Diff line change
Expand Up @@ -3515,7 +3515,8 @@ def process(cls: Type[Union[BasicUser, ProUser]]):
obj = cls()
cls.bar(obj)
cls.mro() # Defined in class type
cls.error # E: Item "type" of "Union[Type[BasicUser], Type[ProUser]]" has no attribute "error"
cls.error # E: Item "type" of "Union[Type[BasicUser], Type[ProUser]]" has no attribute "error" \
# N: You can use 'if hasattr( cls, 'error'):' to guard against missing attribute error
[builtins fixtures/classmethod.pyi]
[out]

Expand Down
3 changes: 2 additions & 1 deletion test-data/unit/check-errorcodes.test
Original file line number Diff line number Diff line change
Expand Up @@ -344,7 +344,8 @@ class A:
class B:
y: str
a: Union[A, B]
a.x # E: Item "B" of "Union[A, B]" has no attribute "x" [union-attr]
a.x # E: Item "B" of "Union[A, B]" has no attribute "x" [union-attr] \
# N: You can use 'if hasattr( a, 'x'):' to guard against missing attribute error

[case testErrorCodeFunctionHasNoAnnotation]
# flags: --disallow-untyped-defs
Expand Down
3 changes: 2 additions & 1 deletion test-data/unit/check-generics.test
Original file line number Diff line number Diff line change
Expand Up @@ -817,7 +817,8 @@ if not isinstance(s, str):

z = None # type: TNode # Same as TNode[Any]
z.x
z.foo() # E: Item "Node[int]" of "Union[Any, Node[int]]" has no attribute "foo"
z.foo() # E: Item "Node[int]" of "Union[Any, Node[int]]" has no attribute "foo" \
# N: You can use 'if hasattr( z, 'foo'):' to guard against missing attribute error

[builtins fixtures/isinstance.pyi]

Expand Down
6 changes: 4 additions & 2 deletions test-data/unit/check-inference.test
Original file line number Diff line number Diff line change
Expand Up @@ -2832,15 +2832,17 @@ class C:
a = None # E: Need type annotation for "a" (hint: "a: Optional[<type>] = ...")

def f(self, x) -> None:
C.a.y # E: Item "None" of "Optional[Any]" has no attribute "y"
C.a.y # E: Item "None" of "Optional[Any]" has no attribute "y" \
# N: You can use 'if hasattr( C.a, 'y'):' to guard against missing attribute error

[case testLocalPartialTypesAccessPartialNoneAttribute2]
# flags: --local-partial-types
class C:
a = None # E: Need type annotation for "a" (hint: "a: Optional[<type>] = ...")

def f(self, x) -> None:
self.a.y # E: Item "None" of "Optional[Any]" has no attribute "y"
self.a.y # E: Item "None" of "Optional[Any]" has no attribute "y" \
# N: You can use 'if hasattr( self.a, 'y'):' to guard against missing attribute error

-- Special case for assignment to '_'
-- ----------------------------------
Expand Down
10 changes: 7 additions & 3 deletions test-data/unit/check-isinstance.test
Original file line number Diff line number Diff line change
Expand Up @@ -578,7 +578,8 @@ v = A() # type: Union[A, B, C]

if isinstance(v, (B, C)):
v.method2(123)
v.method3('xyz') # E: Item "B" of "Union[B, C]" has no attribute "method3"
v.method3('xyz') # E: Item "B" of "Union[B, C]" has no attribute "method3" \
# N: You can use 'if hasattr( v, 'method3'):' to guard against missing attribute error
[builtins fixtures/isinstance.pyi]

[case testIsinstanceNeverWidens]
Expand Down Expand Up @@ -1007,7 +1008,8 @@ def bar() -> None:
if isinstance(x, int):
x + 1
else:
x.a # E: Item "str" of "Union[str, A]" has no attribute "a"
x.a # E: Item "str" of "Union[str, A]" has no attribute "a" \
# N: You can use 'if hasattr( x, 'a'):' to guard against missing attribute error
x = 'a'
[builtins fixtures/isinstancelist.pyi]

Expand Down Expand Up @@ -2104,7 +2106,9 @@ reveal_type(x) # N: Revealed type is "Any"
from typing import Union
from foo import A # type: ignore
def f(x: Union[A, str]) -> None:
x.method_only_in_a() # E: Item "str" of "Union[Any, str]" has no attribute "method_only_in_a"
x.method_only_in_a() # E: Item "str" of "Union[Any, str]" has no attribute "method_only_in_a" \
# N: You can use 'if hasattr( x, 'method_only_in_a'):' to guard against missing attribute \
error
if isinstance(x, A):
x.method_only_in_a()
[builtins fixtures/isinstance.pyi]
Expand Down
3 changes: 2 additions & 1 deletion test-data/unit/check-narrowing.test
Original file line number Diff line number Diff line change
Expand Up @@ -420,7 +420,8 @@ else:
reveal_type(ok_mixture) # N: Revealed type is "Tuple[Literal[__main__.Key.C], fallback=__main__.KeyedNamedTuple]"

impossible_mixture: Union[KeyedObject, KeyedTypedDict]
if impossible_mixture.key is Key.A: # E: Item "KeyedTypedDict" of "Union[KeyedObject, KeyedTypedDict]" has no attribute "key"
if impossible_mixture.key is Key.A: # E: Item "KeyedTypedDict" of "Union[KeyedObject, KeyedTypedDict]" has no attribute "key" \
# N: You can use 'if hasattr( impossible_mixture, 'key'):' to guard against missing attribute error
reveal_type(impossible_mixture) # N: Revealed type is "Union[__main__.KeyedObject, TypedDict('__main__.KeyedTypedDict', {'key': Literal[__main__.Key.B]})]"
else:
reveal_type(impossible_mixture) # N: Revealed type is "Union[__main__.KeyedObject, TypedDict('__main__.KeyedTypedDict', {'key': Literal[__main__.Key.B]})]"
Expand Down
7 changes: 4 additions & 3 deletions test-data/unit/check-optional.test
Original file line number Diff line number Diff line change
Expand Up @@ -563,8 +563,8 @@ if int():
x = f(1)
if int():
x = f('x') # E: Argument 1 to "f" has incompatible type "str"; expected "int"

x.x = 1 # E: Item "None" of "Optional[Node[int]]" has no attribute "x"
x.x = 1 # E: Item "None" of "Optional[Node[int]]" has no attribute "x" \
# N: # N: You can use 'if hasattr( x, 'x'):' to guard against missing attribute error
if x is not None:
x.x = 1 # OK here

Expand Down Expand Up @@ -617,7 +617,8 @@ A = None # type: Any
class C(A):
pass
x = None # type: Optional[C]
x.foo() # E: Item "None" of "Optional[C]" has no attribute "foo"
x.foo() # E: Item "None" of "Optional[C]" has no attribute "foo" \
# N: You can use 'if hasattr( x, 'foo'):' to guard against missing attribute error

[case testIsinstanceAndOptionalAndAnyBase]
from typing import Any, Optional
Expand Down
1 change: 1 addition & 0 deletions test-data/unit/check-overloading.test
Original file line number Diff line number Diff line change
Expand Up @@ -5167,6 +5167,7 @@ def foo(iterable: Iterable[_T]) -> None: ...
def foo(iterable = None) -> None: pass

foo(bar('lol').foo()) # E: Item "int" of "Union[A, int]" has no attribute "foo" \
# N: You can use 'if hasattr( <variable name>, 'foo'):' to guard against missing attribute error \
# E: Argument 1 to "bar" has incompatible type "str"; expected "int"


Expand Down
15 changes: 11 additions & 4 deletions test-data/unit/check-unions.test
Original file line number Diff line number Diff line change
Expand Up @@ -65,15 +65,19 @@ z: str
if int():
y = w.y
v.y # E: Item "C" of "Union[C, D]" has no attribute "y" \
# N: You can use 'if hasattr( v, 'y'):' to guard against missing attribute error \
# E: Item "D" of "Union[C, D]" has no attribute "y"
u.y # E: Item "C" of "Union[A, C, D]" has no attribute "y" \
# N: You can use 'if hasattr( u, 'y'):' to guard against missing attribute error \
# E: Item "D" of "Union[A, C, D]" has no attribute "y"
if int():
z = w.y # E: Incompatible types in assignment (expression has type "int", variable has type "str")
w.y = 'a' # E: Incompatible types in assignment (expression has type "str", variable has type "int")
if int():
y = x.y # E: Item "C" of "Union[A, C]" has no attribute "y"
zz = x.y # E: Item "C" of "Union[A, C]" has no attribute "y"
y = x.y # E: Item "C" of "Union[A, C]" has no attribute "y" \
# N: You can use 'if hasattr( x, 'y'):' to guard against missing attribute error
zz = x.y # E: Item "C" of "Union[A, C]" has no attribute "y" \
# N: You can use 'if hasattr( x, 'y'):' to guard against missing attribute error
if int():
z = zz # E: Incompatible types in assignment (expression has type "Union[int, Any]", variable has type "str")

Expand Down Expand Up @@ -350,6 +354,7 @@ def foo(a: Union[A, B, C]):
reveal_type(a) # N: Revealed type is "Union[Tuple[builtins.int, fallback=__main__.B], Tuple[builtins.int, fallback=__main__.C]]"
a.x
a.y # E: Item "B" of "Union[B, C]" has no attribute "y" \
# N: You can use 'if hasattr( a, 'y'):' to guard against missing attribute error \
# E: Item "C" of "Union[B, C]" has no attribute "y"
b = a # type: Union[B, C]
[builtins fixtures/isinstance.pyi]
Expand Down Expand Up @@ -935,7 +940,8 @@ a: Any
d: Dict[str, Tuple[List[Tuple[str, str]], str]]
x, _ = d.get(a, (None, None))

for y in x: pass # E: Item "None" of "Optional[List[Tuple[str, str]]]" has no attribute "__iter__" (not iterable)
for y in x: pass # E: Item "None" of "Optional[List[Tuple[str, str]]]" has no attribute "__iter__" (not iterable) \
# N: You can use 'if hasattr( x, '__iter__'):' to guard against missing attribute error
if x:
for s, t in x:
reveal_type(s) # N: Revealed type is "builtins.str"
Expand All @@ -950,7 +956,8 @@ x = None
d: Dict[str, Tuple[List[Tuple[str, str]], str]]
x, _ = d.get(a, (None, None))

for y in x: pass # E: Item "None" of "Optional[List[Tuple[str, str]]]" has no attribute "__iter__" (not iterable)
for y in x: pass # E: Item "None" of "Optional[List[Tuple[str, str]]]" has no attribute "__iter__" (not iterable) \
# N: You can use 'if hasattr( x, '__iter__'):' to guard against missing attribute error
if x:
for s, t in x:
reveal_type(s) # N: Revealed type is "builtins.str"
Expand Down
Loading