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
mypy too strict in enforcing generic return types when they are unions #19239
mypy is overly strict in enforcing union return types from generic functions.
If a function both takes and returns a value of type T, which is a union of two types, and does any guarding to check which of the possible types the value is before returning it, mypy emits an "Incompatible return type" error.
To Reproduce
This happens with checks using isinstance or with is None e.g.:
mypy should not emit an error, because the input and output types are still correct, the guard just leads to an early return.
I suppose more specifically I would expect that guards on the input type for a generic which takes and returns the same type should also be guards on the output type.
Actual Behavior
error: Incompatible return value type (got "int", expected "T") [return-value]
and error: Incompatible return value type (got "None", expected "T") [return-value]
Your Environment
Mypy version used: 1.16.0
Mypy command-line flags:
Mypy configuration options from mypy.ini (and other config files):
changed the title [-][1.16 regression] mypy too strict in enforcing generic return types when they are unions[/-][+]mypy too strict in enforcing generic return types when they are unions[/+]on Jun 5, 2025
I've changed the title - the None case is a 1.16 regression and has been fixed on master, but the int/isinstance case still emits an error and I don't think it should.
Activity
[-][1.16 regression] mypy too strict in enforcing generic return types when they are unions[/-][+]mypy too strict in enforcing generic return types when they are unions[/+]thesketh commentedon Jun 5, 2025
I've changed the title - the
Nonecase is a 1.16 regression and has been fixed onmaster, but theint/isinstancecase still emits an error and I don't think it should.A5rocks commentedon Jun 5, 2025
I assume this is fixed by #19183
thesketh commentedon Jun 5, 2025
Looks like it has been - I must have accidentally clicked "mypy latest" when I tried the
isinstance(value, int)case, whoops. Nice spot @A5rocks