-
-
Notifications
You must be signed in to change notification settings - Fork 3k
Description
Not sure if this should be considered a bug, or an enhancement proposal...
I had some code looking like this:
CallbackResult = TypeVar("CallbackResult")
VisitCallback = Callable[[str], Optional[CallbackResult]]
def visititems(self, func: VisitCallback) -> CallbackResult:
return func("test")
Actual Behavior
mypy says about this code:
error: A function returning TypeVar should receive at least one argument containing the same TypeVar [type-var]
Expected Behavior
First, I was confused, and thought that mypy is not able to infer that CallbackResult
is hidden in the function input as the return value of VisitCallback
. Actually I was initially going to open an issue because of that.
Then I noticed that in a sense, mypy is correct - because I spotted that VisitCallback
returns Optional[CallbackResult]
, while the visititems
function returns a CallbackResult
.
Once I fixed that, the error went away. But in this case, mypy did not really "pinpoint" the problem as well as I feel it could.
Not sure how deeply mypy plays out the type algebra to figure out what types are constructible in a context, but I feel like this specific case could be a rather "common" one (forgetting the Optional
), so maybe this can be catched with a better error message.
Maybe something of the form "the function returns typevar value X, but based on its inputs can only construct Y[X, ...]" could be possible? So that it would cover Optional, Union
and other simple cases like List
, etc.
Your Environment
- Mypy version used: 1.1.1