Debian Codegraph @

test-data/unit/check-optional.test

raw
1 -- Tests for strict Optional behavior
2
3 [case testImplicitNoneType]
4 x = None
5 x() # E: "None" not callable
6
7 [case testImplicitNoneTypeInNestedFunction]
8 def f() -> None:
9 def g() -> None:
10 x = None
11 x() # E: "None" not callable
12
13 [case testExplicitNoneType]
14 x = None # type: None
15 x() # E: "None" not callable
16
17 [case testNoneMemberOfOptional]
18 from typing import Optional
19 x = None # type: Optional[int]
20
21 [case testTypeMemberOfOptional]
22 from typing import Optional
23 x = 0 # type: Optional[int]
24
25 [case testNoneNotMemberOfType]
26 x = None # type: int
27 [out]
28 main:1: error: Incompatible types in assignment (expression has type "None", variable has type "int")
29
30 [case testTypeNotMemberOfNone]
31 x = 0 # type: None
32 [out]
33 main:1: error: Incompatible types in assignment (expression has type "int", variable has type "None")
34
35 [case testOptionalNotMemberOfType]
36 from typing import Optional
37 def f(a: int) -> None: pass
38 x = None # type: Optional[int]
39 f(x) # E: Argument 1 to "f" has incompatible type "int | None"; expected "int"
40
41 [case testIsinstanceCases]
42 from typing import Optional
43 x = None # type: Optional[int]
44 if isinstance(x, int):
45 reveal_type(x) # N: Revealed type is "builtins.int"
46 else:
47 reveal_type(x) # N: Revealed type is "None"
48 [builtins fixtures/isinstance.pyi]
49
50 [case testIfCases]
51 from typing import Optional
52 x = None # type: Optional[int]
53 if x:
54 reveal_type(x) # N: Revealed type is "builtins.int"
55 else:
56 reveal_type(x) # N: Revealed type is "Literal[0] | None"
57 [builtins fixtures/bool.pyi]
58
59 [case testIfNotCases]
60 from typing import Optional
61 x = None # type: Optional[int]
62 if not x:
63 reveal_type(x) # N: Revealed type is "Literal[0] | None"
64 else:
65 reveal_type(x) # N: Revealed type is "builtins.int"
66 [builtins fixtures/bool.pyi]
67
68 [case testIsNotNoneCases]
69 from typing import Optional
70 x = None # type: Optional[int]
71 if x is not None:
72 reveal_type(x) # N: Revealed type is "builtins.int"
73 else:
74 reveal_type(x) # N: Revealed type is "None"
75 [builtins fixtures/bool.pyi]
76
77 [case testIsNoneCases]
78 from typing import Optional
79 x = None # type: Optional[int]
80 if x is None:
81 reveal_type(x) # N: Revealed type is "None"
82 else:
83 reveal_type(x) # N: Revealed type is "builtins.int"
84 reveal_type(x) # N: Revealed type is "builtins.int | None"
85 [builtins fixtures/bool.pyi]
86
87 [case testAnyCanBeNone]
88 from typing import Optional, Any
89 x = None # type: Any
90 if x is None:
91 reveal_type(x) # N: Revealed type is "None"
92 else:
93 reveal_type(x) # N: Revealed type is "Any"
94 [builtins fixtures/bool.pyi]
95
96 [case testOrCases]
97 from typing import Optional
98 x = None # type: Optional[str]
99 y1 = x or 'a'
100 reveal_type(y1) # N: Revealed type is "builtins.str"
101 y2 = x or 1
102 reveal_type(y2) # N: Revealed type is "builtins.str | builtins.int"
103 z1 = 'a' or x
104 reveal_type(z1) # N: Revealed type is "builtins.str | None"
105 z2 = int() or x
106 reveal_type(z2) # N: Revealed type is "builtins.int | builtins.str | None"
107
108 [case testAndCases]
109 from typing import Optional
110 x = None # type: Optional[str]
111 y1 = x and 'b'
112 reveal_type(y1) # N: Revealed type is "Literal[''] | None | builtins.str"
113 y2 = x and 1 # x could be '', so...
114 reveal_type(y2) # N: Revealed type is "Literal[''] | None | builtins.int"
115 z1 = 'b' and x
116 reveal_type(z1) # N: Revealed type is "builtins.str | None"
117 z2 = int() and x
118 reveal_type(z2) # N: Revealed type is "Literal[0] | builtins.str | None"
119
120 [case testLambdaReturningNone]
121 f = lambda: None
122 x = f()
123 reveal_type(x) # N: Revealed type is "None"
124
125 [case testNoneArgumentType]
126 def f(x: None) -> None: pass
127 f(None)
128
129 [case testInferOptionalFromDefaultNone]
130 # flags: --implicit-optional
131 def f(x: int = None) -> None:
132 x + 1 # E: Unsupported left operand type for + ("None") \
133 # N: Left operand is of type "int | None"
134 f(None)
135 [out]
136
137 [case testNoInferOptionalFromDefaultNone]
138 # flags: --no-implicit-optional
139 def f(x: int = None) -> None: # E: Incompatible default for parameter "x" (default has type "None", parameter has type "int") \
140 # N: PEP 484 prohibits implicit Optional. Accordingly, mypy has changed its default to no_implicit_optional=True \
141 # N: Use https://github.com/hauntsaninja/no_implicit_optional to automatically upgrade your codebase
142 pass
143 [out]
144
145 [case testInferOptionalFromDefaultNoneComment]
146 # flags: --implicit-optional
147 def f(x=None):
148 # type: (int) -> None
149 x + 1 # E: Unsupported left operand type for + ("None") \
150 # N: Left operand is of type "int | None"
151 f(None)
152 [out]
153
154 [case testNoInferOptionalFromDefaultNoneComment]
155 # flags: --no-implicit-optional
156 def f(x=None): # E: Incompatible default for parameter "x" (default has type "None", parameter has type "int") \
157 # N: PEP 484 prohibits implicit Optional. Accordingly, mypy has changed its default to no_implicit_optional=True \
158 # N: Use https://github.com/hauntsaninja/no_implicit_optional to automatically upgrade your codebase
159 # type: (int) -> None
160 pass
161 [out]
162
163 [case testInferOptionalType]
164 x = None
165 if bool():
166 # scope limit assignment
167 x = 1
168 # in scope of the assignment, x is an int
169 reveal_type(x) # N: Revealed type is "builtins.int"
170 # out of scope of the assignment, it's an Optional[int]
171 reveal_type(x) # N: Revealed type is "builtins.int | None"
172 [builtins fixtures/bool.pyi]
173
174 [case testInferOptionalTypeLocallyBound]
175 x = None
176 x = 1
177 reveal_type(x) # N: Revealed type is "builtins.int"
178
179 [case testInferOptionalAnyType]
180 from typing import Any
181 x = None
182 a = None # type: Any
183 if bool():
184 x = a
185 reveal_type(x) # N: Revealed type is "Any"
186 reveal_type(x) # N: Revealed type is "Any | None"
187 [builtins fixtures/bool.pyi]
188
189 [case testInferOptionalTypeFromOptional]
190 from typing import Optional
191 y = None # type: Optional[int]
192 x = None
193 x = y
194 reveal_type(x) # N: Revealed type is "builtins.int | None"
195
196 [case testInferOptionalListType]
197 x = [None]
198 x.append(1) # E: Argument 1 to "append" of "list" has incompatible type "int"; expected "None"
199 [builtins fixtures/list.pyi]
200
201 [case testInferNonOptionalListType]
202 x = []
203 x.append(1)
204 x() # E: "list[int]" not callable
205 [builtins fixtures/list.pyi]
206
207 [case testInferOptionalDictKeyValueTypes]
208 x = {None: None}
209 x["bar"] = 1
210 [builtins fixtures/dict.pyi]
211 [out]
212 main:2: error: Invalid index type "str" for "dict[None, None]"; expected type "None"
213 main:2: error: Incompatible types in assignment (expression has type "int", target has type "None")
214
215 [case testInferNonOptionalDictType]
216 x = {}
217 x["bar"] = 1
218 x() # E: "dict[str, int]" not callable
219 [builtins fixtures/dict.pyi]
220
221 [case testNoneClassVariable]
222 from typing import Optional
223 class C:
224 x: int
225 def __init__(self) -> None:
226 self.x = 0
227
228 [case testNoneClassVariableInInit]
229 from typing import Optional
230 class C:
231 x: int
232 def __init__(self) -> None:
233 self.x = None # E: Incompatible types in assignment (expression has type "None", variable has type "int")
234 [out]
235
236 [case testMultipleAssignmentNoneClassVariableInInit]
237 from typing import Optional
238 class C:
239 x, y = None, None # type: int, str # E: Incompatible types in assignment (expression has type "None", variable has type "int") \
240 # E: Incompatible types in assignment (expression has type "None", variable has type "str")
241 def __init__(self) -> None:
242 self.x = None # E: Incompatible types in assignment (expression has type "None", variable has type "int")
243 self.y = None # E: Incompatible types in assignment (expression has type "None", variable has type "str")
244
245 [builtins fixtures/tuple.pyi]
246
247 [case testOverloadWithNone]
248 from foo import *
249 [file foo.pyi]
250 from typing import overload
251 @overload
252 def f(x: None) -> str: pass
253 @overload
254 def f(x: int) -> int: pass
255 reveal_type(f(None)) # N: Revealed type is "builtins.str"
256 reveal_type(f(0)) # N: Revealed type is "builtins.int"
257
258 [case testOptionalTypeOrTypePlain]
259 from typing import Optional
260 def f(a: Optional[int]) -> int:
261 return a or 0
262 [out]
263
264 [case testOptionalTypeOrTypeTypeVar]
265 from typing import Optional, TypeVar
266 T = TypeVar('T')
267 def f(a: Optional[T], b: T) -> T:
268 return a or b
269 [out]
270
271 [case testOptionalTypeOrTypeBothOptional]
272 from typing import Optional
273 def f(a: Optional[int], b: Optional[int]) -> None:
274 reveal_type(a or b)
275 def g(a: int, b: Optional[int]) -> None:
276 reveal_type(a or b)
277 [out]
278 main:3: note: Revealed type is "builtins.int | None"
279 main:5: note: Revealed type is "builtins.int | None"
280
281 [case testOptionalTypeOrTypeComplexUnion]
282 from typing import Union
283 def f(a: Union[int, str, None]) -> None:
284 reveal_type(a or 'default')
285 [out]
286 main:3: note: Revealed type is "builtins.int | builtins.str"
287
288 [case testOptionalTypeOrTypeNoTriggerPlain]
289 from typing import Optional
290 def f(a: Optional[int], b: int) -> int:
291 return b or a
292 [out]
293 main:3: error: Incompatible return value type (got "int | None", expected "int")
294
295 [case testOptionalTypeOrTypeNoTriggerTypeVar]
296 from typing import Optional, TypeVar
297 T = TypeVar('T')
298 def f(a: Optional[T], b: T) -> T:
299 return b or a
300 [out]
301 main:4: error: Incompatible return value type (got "T | None", expected "T")
302
303 [case testNoneOrStringIsString]
304 def f() -> str:
305 a = None
306 b = ''
307 return a or b
308 [out]
309
310 [case testNoneOrTypeVarIsTypeVar]
311 from typing import TypeVar
312 T = TypeVar('T')
313 def f(b: T) -> T:
314 a = None
315 return a or b
316 [out]
317
318 [case testYieldNothingInFunctionReturningGenerator]
319 from typing import Generator
320 def f() -> Generator[None, None, None]:
321 yield
322 [out]
323
324 [case testNoneAndStringIsNone]
325 a: None = None
326 b = "foo"
327 reveal_type(a and b) # N: Revealed type is "None"
328
329 c = None
330 reveal_type(c and b) # N: Revealed type is "None"
331
332 [case testNoneMatchesObjectInOverload]
333 import a
334 a.f(None)
335
336 [file a.pyi]
337 from typing import overload
338 @overload
339 def f() -> None: ...
340 @overload
341 def f(o: object) -> None: ...
342
343 [case testGenericSubclassReturningNone]
344 from typing import Generic, TypeVar
345
346 T = TypeVar('T')
347
348 class Base(Generic[T]):
349 def f(self) -> T:
350 pass
351
352 class SubNone(Base[None]):
353 def f(self) -> None:
354 pass
355
356 class SubInt(Base[int]):
357 def f(self) -> int:
358 return 1
359
360 [case testUseOfNoneReturningFunction]
361 from typing import Optional
362 def f() -> None:
363 pass
364
365 def g(x: Optional[int]) -> int:
366 pass
367
368 x = f() # E: "f" does not return a value (it only ever returns None)
369 f() + 1 # E: "f" does not return a value (it only ever returns None) \
370 # E: Unsupported left operand type for + ("None")
371 g(f()) # E: "f" does not return a value (it only ever returns None)
372
373 [case testEmptyReturn]
374 def f() -> None:
375 return
376
377 [case testReturnNone]
378 def f() -> None:
379 return None
380
381 [case testNoneCallable]
382 from typing import Callable
383 def f() -> None: pass
384 x = f # type: Callable[[], None]
385
386 [case testOptionalCallable]
387 from typing import Callable, Optional
388 T = Optional[Callable[..., None]]
389
390 [case testAnyTypeInPartialTypeList]
391 # flags: --check-untyped-defs
392 def f(): ...
393
394 def lookup_field(name, obj):
395 try:
396 pass
397 except:
398 attr = f()
399 else:
400 attr = None
401
402 [case testTernaryWithNone]
403 reveal_type(None if bool() else 0) # N: Revealed type is "None | Literal[0]?"
404 [builtins fixtures/bool.pyi]
405
406 [case testListWithNone]
407 reveal_type([0, None, 0]) # N: Revealed type is "builtins.list[builtins.int | None]"
408 [builtins fixtures/list.pyi]
409
410 [case testNoneContextInference]
411 from typing import Dict, List
412 def f() -> List[None]:
413 return []
414 def g() -> Dict[None, None]:
415 return {}
416 [builtins fixtures/dict.pyi]
417
418 [case testRaiseFromNone]
419 raise BaseException from None
420 [builtins fixtures/exception.pyi]
421
422 [case testOptionalNonPartialTypeWithNone]
423 from typing import Generator
424 def f() -> Generator[str, None, None]: pass
425 x = f()
426 reveal_type(x) # N: Revealed type is "typing.Generator[builtins.str, None, None]"
427 l = [f()]
428 reveal_type(l) # N: Revealed type is "builtins.list[typing.Generator[builtins.str, None, None]]"
429 [builtins fixtures/list.pyi]
430
431 [case testNoneListTernary]
432 # https://github.com/python/mypy/issues/19534
433 x = [None] if "" else [1]
434 reveal_type(x) # N: Revealed type is "builtins.list[None] | builtins.list[builtins.int]"
435 [builtins fixtures/list.pyi]
436
437 [case testListIncompatibleErrorMessage]
438 from typing import List, Callable
439
440 def foo(l: List[Callable[[], str]]) -> None: pass
441 def f() -> int:
442 return 42
443
444 foo([f]) # E: List item 0 has incompatible type "Callable[[], int]"; expected "Callable[[], str]"
445 [builtins fixtures/list.pyi]
446
447 [case testInferEqualsNotOptional]
448 from typing import Optional
449
450 def main(x: Optional[str]):
451 if x == '<string>':
452 reveal_type(x) # N: Revealed type is "builtins.str"
453 else:
454 reveal_type(x) # N: Revealed type is "builtins.str | None"
455 if x is '<string>':
456 reveal_type(x) # N: Revealed type is "Literal['<string>']"
457 else:
458 reveal_type(x) # N: Revealed type is "builtins.str | None"
459 [builtins fixtures/ops.pyi]
460
461 [case testInferEqualsNotOptionalWithUnion]
462 from typing import Union
463 def main(x: Union[str, int, None]):
464 if x == '<string>':
465 reveal_type(x) # N: Revealed type is "builtins.str"
466 else:
467 reveal_type(x) # N: Revealed type is "builtins.str | builtins.int | None"
468 if x is '<string>':
469 reveal_type(x) # N: Revealed type is "Literal['<string>']"
470 else:
471 reveal_type(x) # N: Revealed type is "builtins.str | builtins.int | None"
472 [builtins fixtures/ops.pyi]
473
474 [case testInferEqualsNotOptionalWithOverlap]
475 from typing import Union
476
477 def make_random_object() -> object:
478 return None
479
480 def main(x: Union[str, int, None]):
481 if x == make_random_object():
482 reveal_type(x) # N: Revealed type is "builtins.str | builtins.int | None"
483 else:
484 reveal_type(x) # N: Revealed type is "builtins.str | builtins.int | None"
485 if x is make_random_object():
486 reveal_type(x) # N: Revealed type is "builtins.str | builtins.int | None"
487 else:
488 reveal_type(x) # N: Revealed type is "builtins.str | builtins.int | None"
489 [builtins fixtures/ops.pyi]
490
491 [case testInferEqualsStillOptionalWithNoOverlap]
492 # flags: --warn-unreachable
493 from typing import Optional
494
495 def main(x: Optional[str]):
496 if x == 0:
497 reveal_type(x) # E: Statement is unreachable
498 else:
499 reveal_type(x) # N: Revealed type is "builtins.str | None"
500 if x is 0:
501 reveal_type(x) # E: Statement is unreachable
502 else:
503 reveal_type(x) # N: Revealed type is "builtins.str | None"
504 [builtins fixtures/ops.pyi]
505
506 [case testInferEqualsStillOptionalWithBothOptional]
507 from typing import Union
508 x = '' # type: Union[str, int, None]
509 y = '' # type: Union[str, None]
510 if x == y:
511 reveal_type(x) # N: Revealed type is "builtins.str | None"
512 else:
513 reveal_type(x) # N: Revealed type is "builtins.str | builtins.int | None"
514 if x is y:
515 reveal_type(x) # N: Revealed type is "builtins.str | None"
516 else:
517 reveal_type(x) # N: Revealed type is "builtins.str | builtins.int | None"
518 [builtins fixtures/ops.pyi]
519
520 [case testInferEqualsNotOptionalWithMultipleArgs]
521 from typing import Optional
522
523 def main(x: Optional[int], y: Optional[int]):
524 if x == y == 1:
525 reveal_type(x) # N: Revealed type is "builtins.int"
526 reveal_type(y) # N: Revealed type is "builtins.int"
527 else:
528 reveal_type(x) # N: Revealed type is "builtins.int | None"
529 reveal_type(y) # N: Revealed type is "builtins.int | None"
530
531 class A: pass
532
533 def returns_random_object() -> object:
534 return None
535
536 def main2(a: Optional[A], b: Optional[A]):
537 if a == b == returns_random_object():
538 reveal_type(a) # N: Revealed type is "__main__.A | None"
539 reveal_type(b) # N: Revealed type is "__main__.A | None"
540 else:
541 reveal_type(a) # N: Revealed type is "__main__.A | None"
542 reveal_type(b) # N: Revealed type is "__main__.A | None"
543 [builtins fixtures/ops.pyi]
544
545 [case testInferInWithErasedTypes]
546 from typing import TypeVar, Callable
547
548 T = TypeVar('T')
549 def foo(f: Callable[[T], bool], it: T) -> None: ...
550
551 foo(lambda x: x in [1, 2] and bool(), 3)
552 [builtins fixtures/list.pyi]
553
554 [case testWarnNoReturnWorksWithStrictOptional]
555 # flags: --warn-no-return
556 def f() -> None:
557 1 + 1 # no error
558
559 def g() -> int:
560 1 + 1 #
561 [out]
562 main:5: error: Missing return statement
563
564 [case testGenericTypeAliasesOptional]
565 from typing import TypeVar, Generic, Optional
566 T = TypeVar('T')
567 class Node(Generic[T]):
568 def __init__(self, x: T) -> None:
569 self.x = x
570
571 ONode = Optional[Node[T]]
572 def f(x: T) -> ONode[T]:
573 if 1 > 0:
574 return Node(x)
575 else:
576 return None
577
578 x = None # type: ONode[int]
579 if int():
580 x = f(1)
581 if int():
582 x = f('x') # E: Argument 1 to "f" has incompatible type "str"; expected "int"
583
584 x.x = 1 # E: Item "None" of "Node[int] | None" has no attribute "x"
585 if x is not None:
586 x.x = 1 # OK here
587
588 [builtins fixtures/ops.pyi]
589
590 [case testOptionalTypeNarrowedInBooleanStatement]
591 from typing import Optional
592
593 x: Optional[int] = None
594 x is not None and x + 42
595 x is not None and x + '42' # E: Unsupported operand types for + ("int" and "str")
596 [builtins fixtures/isinstance.pyi]
597
598 [case testInvalidBooleanBranchIgnored]
599 from typing import Optional
600
601 x: None = None
602 x is not None and x + 42
603 [builtins fixtures/isinstance.pyi]
604
605 [case testOptionalLambdaInference]
606 from typing import Optional, Callable
607 f = None # type: Optional[Callable[[int], None]]
608 f = lambda x: None
609 f(0)
610 [builtins fixtures/function.pyi]
611
612 [case testDontSimplifyNoneUnionsWithStrictOptional]
613 from typing import Any, TypeVar, Union
614 A = None # type: Any
615 class C(A): pass
616 T = TypeVar('T')
617 S = TypeVar('S')
618 def u(x: T, y: S) -> Union[S, T]: pass
619 a = None # type: Any
620
621 # Test both orders
622 reveal_type(u(C(), None)) # N: Revealed type is "None | __main__.C"
623 reveal_type(u(None, C())) # N: Revealed type is "__main__.C | None"
624
625 reveal_type(u(a, None)) # N: Revealed type is "None | Any"
626 reveal_type(u(None, a)) # N: Revealed type is "Any | None"
627
628 reveal_type(u(1, None)) # N: Revealed type is "None | builtins.int"
629 reveal_type(u(None, 1)) # N: Revealed type is "builtins.int | None"
630
631 [case testOptionalAndAnyBaseClass]
632 from typing import Any, Optional
633 A = None # type: Any
634 class C(A):
635 pass
636 x = None # type: Optional[C]
637 x.foo() # E: Item "None" of "C | None" has no attribute "foo"
638
639 [case testIsinstanceAndOptionalAndAnyBase]
640 from typing import Any, Optional
641
642 B = None # type: Any
643 class A(B): pass
644
645 def f(a: Optional[A]):
646 reveal_type(a) # N: Revealed type is "__main__.A | None"
647 if a is not None:
648 reveal_type(a) # N: Revealed type is "__main__.A"
649 else:
650 reveal_type(a) # N: Revealed type is "None"
651 reveal_type(a) # N: Revealed type is "__main__.A | None"
652 [builtins fixtures/isinstance.pyi]
653
654 [case testFlattenOptionalUnion]
655 from typing import Optional, Union
656
657 x: Optional[Union[int, str]]
658 reveal_type(x) # N: Revealed type is "builtins.int | builtins.str | None"
659 y: Optional[Union[int, None]]
660 reveal_type(y) # N: Revealed type is "builtins.int | None"
661
662 [case testOverloadWithNoneAndOptional]
663 from typing import overload, Optional
664
665 @overload
666 def f(x: int) -> str: ...
667 @overload
668 def f(x: Optional[int]) -> Optional[str]: ...
669 def f(x): return x
670
671 reveal_type(f(1)) # N: Revealed type is "builtins.str"
672 reveal_type(f(None)) # N: Revealed type is "builtins.str | None"
673 x: Optional[int]
674 reveal_type(f(x)) # N: Revealed type is "builtins.str | None"
675
676 [case testUnionTruthinessTracking]
677 from typing import Optional, Any
678 def test_or_shortcut(value: Optional[Any]) -> None:
679 if not value:
680 pass
681 if not value or value.get('foo') == 'hello':
682 pass
683 [builtins fixtures/bool.pyi]
684
685 [case testNarrowingFromObjectToOptional]
686 from typing import Optional
687 x: object
688 y: Optional[int]
689 x = y
690 reveal_type(x) # N: Revealed type is "builtins.int | None"
691 [out]
692
693 [case testNarrowOptionalOutsideLambda]
694 from typing import Optional
695
696 class A:
697 a: int
698
699 def f(x: Optional[A]) -> None:
700 assert x
701 lambda: x.a
702 [builtins fixtures/isinstancelist.pyi]
703
704 [case testNarrowOptionalOutsideLambdaWithDeferred]
705 from typing import Optional
706
707 class A:
708 a: int
709
710 def f(self, x: Optional['A']) -> None:
711 assert x
712 lambda: (self.y, x.a) # E: Cannot determine type of "y"
713 self.y = int()
714 [builtins fixtures/isinstancelist.pyi]
715
716 [case testDeferredAndOptionalInferenceSpecialCase]
717 def f() -> str:
718 y
719 x = None
720 if int():
721 x = ''
722 if x is None:
723 x = ''
724 g(x)
725 return x
726
727 def g(x: str) -> None: pass
728
729 y = int()
730 [builtins fixtures/bool.pyi]
731
732 [case testOptionalAssignAny1]
733 from typing import Optional
734 def f():
735 return 0
736
737 def g(x: Optional[int]) -> int:
738 if x is None:
739 reveal_type(x) # N: Revealed type is "None"
740 # As a special case for Unions containing None, during
741 x = f()
742 reveal_type(x) # N: Revealed type is "builtins.int | Any"
743 reveal_type(x) # N: Revealed type is "builtins.int | Any"
744 return x
745 [builtins fixtures/bool.pyi]
746
747 [case testOptionalAssignAny2]
748 from typing import Optional
749 def f():
750 return 0
751
752 def g(x: Optional[int]) -> int:
753 if x is None:
754 reveal_type(x) # N: Revealed type is "None"
755 x = 1
756 reveal_type(x) # N: Revealed type is "builtins.int"
757 # Same as above, even after we've assigned to x
758 x = f()
759 reveal_type(x) # N: Revealed type is "builtins.int | Any"
760 reveal_type(x) # N: Revealed type is "builtins.int | Any"
761 return x
762 [builtins fixtures/bool.pyi]
763
764 [case testOptionalAssignAny3]
765 from typing import Optional
766 def f():
767 return 0
768
769 def g(x: Optional[int]) -> int:
770 if x is not None:
771 return x
772 reveal_type(x) # N: Revealed type is "None"
773 x = f()
774 reveal_type(x) # N: Revealed type is "builtins.int | Any"
775 return x
776 [builtins fixtures/bool.pyi]
777
778 [case testStrictOptionalCovarianceCrossModule]
779 # flags: --config-file tmp/mypy.ini
780 from a import asdf
781 x = ["lol"]
782 asdf(x)
783
784 [file a.py]
785 from typing import List, Optional
786
787 def asdf(x: List[Optional[str]]) -> None:
788 pass
789
790 x = ["lol"]
791 asdf(x)
792
793 [file mypy.ini]
794 \[mypy]
795 \[mypy-a]
796 strict_optional = False
797 [out]
798 main:4: error: Argument 1 to "asdf" has incompatible type "list[str]"; expected "list[str | None]"
799 main:4: note: "list" is invariant -- see https://mypy.readthedocs.io/en/stable/common_issues.html#variance
800 main:4: note: Consider using "Sequence" instead, which is covariant
801 [builtins fixtures/list.pyi]
802
803 [case testOptionalBackwards1]
804 from typing import Any, Optional
805
806 def f1(b: bool) -> Optional[int]:
807 if b:
808 z = 10
809 reveal_type(z) # N: Revealed type is "builtins.int"
810 else:
811 z = None
812 reveal_type(z) # N: Revealed type is "None"
813 reveal_type(z) # N: Revealed type is "builtins.int | None"
814 return z
815
816 def f2(b: bool) -> int:
817 if b:
818 z = 10
819 else:
820 z = None
821 return z # E: Incompatible return value type (got "int | None", expected "int")
822
823 def f3(b: bool) -> int:
824 # XXX: This one is a little questionable! Maybe we *do* want to allow this?
825 z = 10
826 if b:
827 z = None # E: Incompatible types in assignment (expression has type "None", variable has type "int")
828 return z
829
830 def f4() -> Optional[int]:
831 z = 10
832 z = None # E: Incompatible types in assignment (expression has type "None", variable has type "int")
833
834 return z
835
836 def f5() -> None:
837 z = 10
838
839 def f() -> None:
840 nonlocal z
841 z = None # E: Incompatible types in assignment (expression has type "None", variable has type "int")
842
843 def f6(b: bool) -> None:
844 if b:
845 z = 10
846 else:
847 z = 11
848
849 def f() -> None:
850 nonlocal z
851 z = None # E: Incompatible types in assignment (expression has type "None", variable has type "int")
852
853 def f7(b: bool) -> None:
854 if b:
855 z = 10
856 else:
857 z = 11
858
859 z = None # E: Incompatible types in assignment (expression has type "None", variable has type "int")
860
861 def f8(b: bool, c: bool) -> Optional[int]:
862 if b:
863 if c:
864 z = 10
865 else:
866 z = 11
867 else:
868 z = None
869 return z
870
871 def f9(b: bool) -> None:
872 if b:
873 z: int = 10
874 else:
875 z = None # E: Incompatible types in assignment (expression has type "None", variable has type "int")
876
877 def f10(b: bool) -> None:
878 z: int
879 if b:
880 z = 10
881 else:
882 z = None # E: Incompatible types in assignment (expression has type "None", variable has type "int")
883
884 def f11(b: bool, c: bool) -> None:
885 if b:
886 z = 10
887 elif c:
888 z = 30
889 else:
890 z = None
891
892 def f12(b: bool, a: Any) -> None:
893 if b:
894 z = a
895 else:
896 z = None
897 reveal_type(z) # N: Revealed type is "Any"
898
899 def f13(b: bool, a: Any) -> None:
900 if b:
901 try:
902 z = f2(True)
903 except Exception:
904 raise RuntimeError
905 else:
906 z = None
907
908 def f14(b: bool, a: Any) -> None:
909 if b:
910 with a:
911 z = 10
912 else:
913 z = None
914
915 def f15() -> None:
916 try:
917 z = f2(True)
918 except Exception:
919 z = None
920 reveal_type(z) # N: Revealed type is "builtins.int | None"
921
922 def f16(z: Any) -> None:
923 for x in z:
924 if x == 0:
925 y = 50
926 break
927 else:
928 y = None
929 reveal_type(y) # N: Revealed type is "builtins.int | None"
930
931 def f17(b: bool, c: bool, d: bool) -> None:
932 if b:
933 z = 2
934 elif c:
935 z = None
936 elif d:
937 z = 3
938 reveal_type(z) # N: Revealed type is "builtins.int | None"
939
940 def f18(b: bool, c: bool, d: bool) -> None:
941 if b:
942 z = 4
943 else:
944 if c:
945 z = 5
946 else:
947 z = None
948 reveal_type(z) # N: Revealed type is "builtins.int | None"
949
950 def f19(b: bool, c: bool, d: bool) -> None:
951 if b:
952 z = 5
953 else:
954 z = None
955 if c:
956 z = 6
957 reveal_type(z) # N: Revealed type is "builtins.int | None"
958
959 def f20(b: bool) -> None:
960 if b:
961 x: Any = 5
962 else:
963 x = None
964 reveal_type(x) # N: Revealed type is "Any"
965
966 def f_unannot(): pass
967
968 def f21(b: bool) -> None:
969 if b:
970 x = f_unannot()
971 else:
972 x = None
973 reveal_type(x) # N: Revealed type is "Any"
974
975 def f22(b: bool) -> None:
976 if b:
977 z = 10
978 if not b:
979 z = None # E: Incompatible types in assignment (expression has type "None", variable has type "int")
980
981 def f23(b: bool) -> None:
982 if b:
983 z = 10
984 if b:
985 z = 11
986 else:
987 z = None # E: Incompatible types in assignment (expression has type "None", variable has type "int")
988
989 [builtins fixtures/exception.pyi]
990
991 [case testOptionalBackwards2]
992
993 def f1(b: bool) -> None:
994 if b:
995 x = [] # E: Need type annotation for "x" (hint: "x: list[<type>] = ...")
996 else:
997 x = None
998
999 def f2(b: bool) -> None:
1000 if b:
1001 x = []
1002 x.append(1)
1003 else:
1004 x = None
1005 reveal_type(x) # N: Revealed type is "builtins.list[builtins.int] | None"
1006
1007
1008 [builtins fixtures/list.pyi]
1009
1010 [case testOptionalBackwards3]
1011
1012 # We don't allow this sort of updating for globals or attributes currently.
1013 gb: bool
1014 if gb:
1015 Z = 10
1016 else:
1017 Z = None # E: Incompatible types in assignment (expression has type "None", variable has type "int")
1018
1019 class Foo:
1020 def __init__(self, b: bool) -> None:
1021 if b:
1022 self.x = 5
1023 else:
1024 self.x = None # E: Incompatible types in assignment (expression has type "None", variable has type "int")
1025
1026 def foo(self) -> None:
1027 reveal_type(self.x) # N: Revealed type is "builtins.int"
1028
1029 [case testOptionalBackwards4]
1030 from typing import Any, Optional
1031
1032 def f1(b: bool) -> Optional[int]:
1033 if b:
1034 z = 10
1035 reveal_type(z) # N: Revealed type is "builtins.int"
1036 else:
1037 # Force the node to get deferred between the two assignments
1038 Defer().defer
1039 z = None
1040 reveal_type(z) # N: Revealed type is "None"
1041 reveal_type(z) # N: Revealed type is "builtins.int | None"
1042 return z
1043
1044 class Defer:
1045 def __init__(self) -> None:
1046 self.defer = 10
1047
1048 [case testOptionalIterator]
1049 # mypy: no-strict-optional
1050 from typing import Optional, List
1051
1052 x: Optional[List[int]]
1053 if 3 in x:
1054 pass
1055
1056 [case testNarrowedVariableInNestedFunctionBasic]
1057 from typing import Optional
1058
1059 def can_narrow(x: Optional[str]) -> None:
1060 if x is None:
1061 x = "a"
1062 def nested() -> str:
1063 return reveal_type(x) # N: Revealed type is "builtins.str"
1064 nested()
1065
1066 def foo(a): pass
1067
1068 class C:
1069 def can_narrow_in_method(self, x: Optional[str]) -> None:
1070 if x is None:
1071 x = "a"
1072 def nested() -> str:
1073 return reveal_type(x) # N: Revealed type is "builtins.str"
1074 # Reading the variable is fine
1075 y = x
1076 with foo(x):
1077 foo(x)
1078 for a in foo(x):
1079 foo(x)
1080 nested()
1081
1082 def can_narrow_lambda(x: Optional[str]) -> None:
1083 if x is None:
1084 x = "a"
1085 nested = lambda: x
1086 reveal_type(nested()) # N: Revealed type is "builtins.str"
1087
1088 def cannot_narrow_if_reassigned(x: Optional[str]) -> None:
1089 if x is None:
1090 x = "a"
1091 def nested() -> str:
1092 return x # E: Incompatible return value type (got "str | None", expected "str")
1093 if int():
1094 x = None
1095 nested()
1096
1097 x: Optional[str] = "x"
1098
1099 def narrow_global_in_func() -> None:
1100 global x
1101 if x is None:
1102 x = "a"
1103 def nested() -> str:
1104 # This should perhaps not be narrowed, since the nested function could outlive
1105 # the outer function, and since other functions could also assign to x, but
1106 # this seems like a minor issue.
1107 return x
1108 nested()
1109
1110 x = "y"
1111
1112 def narrowing_global_at_top_level_not_propagated() -> str:
1113 def nested() -> str:
1114 return x # E: Incompatible return value type (got "str | None", expected "str")
1115 return x # E: Incompatible return value type (got "str | None", expected "str")
1116
1117 [case testNarrowedVariableInNestedFunctionMore1]
1118 from typing import Optional, overload
1119
1120 class C:
1121 a: Optional[str]
1122
1123 def attribute_narrowing(c: C) -> None:
1124 # This case is not supported, since we can't keep track of assignments to attributes.
1125 c.a = "x"
1126 def nested() -> str:
1127 return c.a # E: Incompatible return value type (got "str | None", expected "str")
1128 nested()
1129
1130 def assignment_in_for(x: Optional[str]) -> None:
1131 if x is None:
1132 x = "e"
1133 def nested() -> str:
1134 return x # E: Incompatible return value type (got "str | None", expected "str")
1135 for x in ["x"]:
1136 pass
1137
1138 def foo(): pass
1139
1140 def assignment_in_with(x: Optional[str]) -> None:
1141 if x is None:
1142 x = "e"
1143 def nested() -> str:
1144 return x # E: Incompatible return value type (got "str | None", expected "str")
1145 with foo() as x:
1146 pass
1147
1148 g: Optional[str]
1149
1150 def assign_to_global() -> None:
1151 global g
1152 g = "x"
1153 # This is unsafe, but we don't generate an error, for convenience. Besides,
1154 # this is probably a very rare case.
1155 def nested() -> str:
1156 return g
1157
1158 def assign_to_nonlocal(x: Optional[str]) -> None:
1159 def nested() -> str:
1160 nonlocal x
1161
1162 if x is None:
1163 x = "a"
1164
1165 def nested2() -> str:
1166 return x # E: Incompatible return value type (got "str | None", expected "str")
1167
1168 return nested2()
1169 nested()
1170 x = None
1171
1172 def dec(f):
1173 return f
1174
1175 @dec
1176 def decorated_outer(x: Optional[str]) -> None:
1177 if x is None:
1178 x = "a"
1179 def nested() -> str:
1180 return x
1181 nested()
1182
1183 @dec
1184 def decorated_outer_bad(x: Optional[str]) -> None:
1185 if x is None:
1186 x = "a"
1187 def nested() -> str:
1188 return x # E: Incompatible return value type (got "str | None", expected "str")
1189 x = None
1190 nested()
1191
1192 def decorated_inner(x: Optional[str]) -> None:
1193 if x is None:
1194 x = "a"
1195 @dec
1196 def nested() -> str:
1197 return x
1198 nested()
1199
1200 def decorated_inner_bad(x: Optional[str]) -> None:
1201 if x is None:
1202 x = "a"
1203 @dec
1204 def nested() -> str:
1205 return x # E: Incompatible return value type (got "str | None", expected "str")
1206 x = None
1207 nested()
1208
1209 @overload
1210 def overloaded_outer(x: None) -> None: ...
1211 @overload
1212 def overloaded_outer(x: str) -> None: ...
1213 def overloaded_outer(x: Optional[str]) -> None:
1214 if x is None:
1215 x = "a"
1216 def nested() -> str:
1217 return x
1218 nested()
1219
1220 @overload
1221 def overloaded_outer_bad(x: None) -> None: ...
1222 @overload
1223 def overloaded_outer_bad(x: str) -> None: ...
1224 def overloaded_outer_bad(x: Optional[str]) -> None:
1225 if x is None:
1226 x = "a"
1227 def nested() -> str:
1228 return x # E: Incompatible return value type (got "str | None", expected "str")
1229 x = None
1230 nested()
1231
1232 [case testNarrowedVariableInNestedFunctionMore2]
1233 from typing import Optional
1234
1235 def narrow_multiple(x: Optional[str], y: Optional[int]) -> None:
1236 z: Optional[str] = x
1237 if x is None:
1238 x = ""
1239 if y is None:
1240 y = 1
1241 if int():
1242 if z is None:
1243 z = ""
1244 def nested() -> None:
1245 a: str = x
1246 b: int = y
1247 c: str = z
1248 nested()
1249
1250 def narrow_multiple_partial(x: Optional[str], y: Optional[int]) -> None:
1251 z: Optional[str] = x
1252 if x is None:
1253 x = ""
1254 if isinstance(y, int):
1255 if z is None:
1256 z = ""
1257 def nested() -> None:
1258 a: str = x
1259 b: int = y
1260 c: str = z # E: Incompatible types in assignment (expression has type "str | None", variable has type "str")
1261 z = None
1262 nested()
1263
1264 def multiple_nested_functions(x: Optional[str], y: Optional[str]) -> None:
1265 if x is None:
1266 x = ""
1267 def nested1() -> str:
1268 return x
1269 if y is None:
1270 y = ""
1271 def nested2() -> str:
1272 a: str = y
1273 return x
1274
1275 class C:
1276 a: str
1277 def __setitem__(self, key, value): pass
1278
1279 def narrowed_variable_used_in_lvalue_but_not_assigned(c: Optional[C]) -> None:
1280 if c is None:
1281 c = C()
1282 def nested() -> C:
1283 return c
1284 c.a = "x"
1285 c[1] = 2
1286 cc = C()
1287 cc[c] = 3
1288 nested()
1289
1290 def narrow_with_multi_lvalues_1(x: Optional[str]) -> None:
1291 if x is None:
1292 x = ""
1293
1294 def nested() -> str:
1295 return x
1296
1297 y = z = None
1298
1299 def narrow_with_multi_lvalue_2(x: Optional[str]) -> None:
1300 if x is None:
1301 x = ""
1302
1303 def nested() -> str:
1304 return x # E: Incompatible return value type (got "str | None", expected "str")
1305
1306 x = y = None
1307
1308 def narrow_with_multi_lvalue_3(x: Optional[str]) -> None:
1309 if x is None:
1310 x = ""
1311
1312 def nested() -> str:
1313 return x # E: Incompatible return value type (got "str | None", expected "str")
1314
1315 y = x = None
1316
1317 def narrow_with_multi_assign_1(x: Optional[str]) -> None:
1318 if x is None:
1319 x = ""
1320
1321 def nested() -> str:
1322 return x
1323
1324 y, z = None, None
1325
1326 def narrow_with_multi_assign_2(x: Optional[str]) -> None:
1327 if x is None:
1328 x = ""
1329
1330 def nested() -> str:
1331 return x # E: Incompatible return value type (got "str | None", expected "str")
1332
1333 x, y = None, None
1334
1335 def narrow_with_multi_assign_3(x: Optional[str]) -> None:
1336 if x is None:
1337 x = ""
1338
1339 def nested() -> str:
1340 return x # E: Incompatible return value type (got "str | None", expected "str")
1341
1342 y, x = None, None
1343
1344 [builtins fixtures/isinstance.pyi]
1345
1346 [case testNestedFunctionSpecialCase]
1347 class C:
1348 def __enter__(self, *args): ...
1349 def __exit__(self, *args) -> bool: ...
1350
1351 def f(x: object) -> None:
1352 if x is not None:
1353 pass
1354
1355 def nested() -> None:
1356 with C():
1357 pass
1358 [builtins fixtures/tuple.pyi]
1359
1360 [case testInferOptionalFromDefaultNoneInlineConfig]
1361 # mypy: implicit-optional
1362 def f(x: int = None) -> None:
1363 reveal_type(x) # N: Revealed type is "builtins.int | None"
1364 f(None)