Skip to content
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

Helpful note when union may not have been narrowed #17115

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
5 changes: 5 additions & 0 deletions mypy/messages.py
Original file line number Diff line number Diff line change
Expand Up @@ -529,6 +529,11 @@ def has_no_attr(
context,
code=codes.UNION_ATTR,
)
self.note(
'You can use "if <variable_name> is not None" to protect against a None value',
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 @@ -3482,7 +3482,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 <variable_name> is not None" to protect against a None value
[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 <variable_name> is not None" to protect against a None value

[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 @@ -813,7 +813,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 <variable_name> is not None" to protect against a None value

[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 @@ -2828,15 +2828,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 <variable_name> is not None" to protect against a None value

[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 <variable_name> is not None" to protect against a None value

-- Special case for assignment to '_'
-- ----------------------------------
Expand Down
9 changes: 6 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 <variable_name> is not None" to protect against a None value
[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 <variable_name> is not None" to protect against a None value
x = 'a'
[builtins fixtures/isinstancelist.pyi]

Expand Down Expand Up @@ -2104,7 +2106,8 @@ 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 <variable_name> is not None" to protect against a None value
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 <variable_name> is not None" to protect against a None value
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
6 changes: 4 additions & 2 deletions test-data/unit/check-optional.test
Original file line number Diff line number Diff line change
Expand Up @@ -564,7 +564,8 @@ if int():
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: You can use "if <variable_name> is not None" to protect against a None value
if x is not None:
x.x = 1 # OK here

Expand Down Expand Up @@ -617,7 +618,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 <variable_name> is not None" to protect against a None value

[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 @@ -5145,6 +5145,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 <variable_name> is not None" to protect against a None value \
# 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 <variable_name> is not None" to protect against a None value \
# 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 <variable_name> is not None" to protect against a None value \
# 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 <variable_name> is not None" to protect against a None value
zz = x.y # E: Item "C" of "Union[A, C]" has no attribute "y" \
# N: You can use "if <variable_name> is not None" to protect against a None value
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 <variable_name> is not None" to protect against a None value \
# 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 <variable_name> is not None" to protect against a None value
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 <variable_name> is not None" to protect against a None value
if x:
for s, t in x:
reveal_type(s) # N: Revealed type is "builtins.str"
Expand Down