Commit 4ccf216
authored
Fix cross-variable type-narrowing example (#17488)
From [<i>Type narrowing</i> §
<i>Limitations</i>](https://github.com/python/mypy/blob/606971807fad1de26ebc575d327d4c1c33f71c0e/docs/source/type_narrowing.rst#limitations):
```python
def f(a: str | None, b: str | None) -> str:
if a is not None or b is not None:
return a or b # Incompatible return value type (got "str | None", expected "str")
return 'spam'
```
A trivial counter-example is `f('', None)`, which returns `None`.
Ironically, this somewhat makes Mypy's diagnostic "correct".
I propose that `str` be replaced with a custom class `C` whose
`__bool__()` is not defined (does it have to be `@final` too?):
```python
class C:
pass
def f(a: C | None, b: C | None) -> C:
if a is not None or b is not None:
return a or b # Incompatible return value type (got "C | None", expected "C")
return C()
```1 parent 1ea8676 commit 4ccf216
1 file changed
+10
-6
lines changed| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
368 | 368 | | |
369 | 369 | | |
370 | 370 | | |
371 | | - | |
| 371 | + | |
| 372 | + | |
372 | 373 | | |
373 | 374 | | |
374 | 375 | | |
375 | | - | |
| 376 | + | |
| 377 | + | |
| 378 | + | |
| 379 | + | |
376 | 380 | | |
377 | | - | |
378 | | - | |
| 381 | + | |
| 382 | + | |
379 | 383 | | |
380 | 384 | | |
381 | 385 | | |
| |||
385 | 389 | | |
386 | 390 | | |
387 | 391 | | |
388 | | - | |
| 392 | + | |
389 | 393 | | |
390 | 394 | | |
391 | 395 | | |
392 | 396 | | |
393 | | - | |
| 397 | + | |
0 commit comments