You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Inconsistent behavior when narrowing bounded generics. #13426
fromtypingimportGeneric, TypeVarT=TypeVar('T')
G=TypeVar('G', bound='Y')
classX(Generic[T]): passclassY: pass# Consider this function:deff(a: X[T] |G) ->X[T] |G:
ifisinstance(a, X):
reveal_type(a) # X[T`-1]returnaifisinstance(a, Y):
reveal_type(a) # G`-2returnaprint() # error: unreachable. It is ok, because all possibilities checked.# The same function, but if's swappeddefg(a: X[T] |G) ->X[T] |G: # error: Missing return statementifisinstance(a, Y):
reveal_type(a) # Yreturna# error: Incompatible return value type (got "Y", expected "Union[X[T], G]")ifisinstance(a, X):
reveal_type(a) # X[T`-1]returnaprint() # no "error: unreachable", because it is reachable and mypy complains about "missing return"# I expect to get no errors here, because it isnt reachable
Expected Behavior
First function is fine. I expect to get no errors in second function. Also first reveal_type in second function is IMO invalid, it should be G.
Your Environment
Mypy version used: mypy 0.971 (compiled: yes)
Mypy command-line flags: none
Mypy configuration options from mypy.ini (and other config files):
Activity
denballakh commentedon Aug 15, 2022
May be related: #9023 #7913 #7362
brianschubert commentedon Dec 7, 2024
This incorrect reachability analysis in the second function was fixed in #14923.
The narrowing issue in the
isinstance(a, Y)branch is still present in mypy v1.13.0. Here's a simplified reproducer:Narrow type variable bounds in binder (python#19183)