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
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):
thesketh
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
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.
Uh oh!
There was an error while loading. Please reload this page.
Bug Report
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 withis None
e.g.:https://mypy-play.net/?mypy=latest&python=3.12&gist=470d29ce79af159a1950e5f47aac2798
and
https://mypy-play.net/?mypy=latest&python=3.12&gist=16f08fc7cc619fa2797d12d6c50e2103
Expected Behavior
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.ini
(and other config files):The text was updated successfully, but these errors were encountered: