Commit 7dc23fe
authored
Enable negative narrowing of Union TypeVar upper bounds (#17850)
Fixes #15235
### Before
```python
from typing import TypeVar
class A:
pass
class B:
b: int
T = TypeVar("T", bound=A | B)
def foo(x: T) -> T:
if isinstance(x, A):
reveal_type(x) # N: Revealed type is "__main__.A"
else:
reveal_type(x) # N: Revealed type is "T`-1"
x.b # E: Item "A" of the upper bound "A | B" of type variable "T" has no attribute "b"
return x
```
### After
```python
from typing import TypeVar
class A:
pass
class B:
b: int
T = TypeVar("T", bound=A | B)
def foo(x: T) -> T:
if isinstance(x, A):
reveal_type(x) # N: Revealed type is "__main__.A"
else:
reveal_type(x) # N: Revealed type is "T`-1"
x.b # ok! Upper bound of T narrowed to B
return x
```1 parent 6726d77 commit 7dc23fe
2 files changed
+26
-0
lines changed| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
1941 | 1941 | | |
1942 | 1942 | | |
1943 | 1943 | | |
| 1944 | + | |
| 1945 | + | |
1944 | 1946 | | |
1945 | 1947 | | |
1946 | 1948 | | |
| |||
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
1833 | 1833 | | |
1834 | 1834 | | |
1835 | 1835 | | |
| 1836 | + | |
| 1837 | + | |
| 1838 | + | |
| 1839 | + | |
| 1840 | + | |
| 1841 | + | |
| 1842 | + | |
| 1843 | + | |
| 1844 | + | |
| 1845 | + | |
| 1846 | + | |
| 1847 | + | |
| 1848 | + | |
| 1849 | + | |
| 1850 | + | |
| 1851 | + | |
| 1852 | + | |
| 1853 | + | |
| 1854 | + | |
| 1855 | + | |
| 1856 | + | |
| 1857 | + | |
| 1858 | + | |
| 1859 | + | |
1836 | 1860 | | |
1837 | 1861 | | |
1838 | 1862 | | |
| |||
0 commit comments