python / python/mypy

mypy shows a somewhat confusing error message for functions returning a TypeVar value

Open
#15,724 7 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

bug
Dominant language
Python
Stars
20.6k
Forks
3.3k
PR merge metrics
PR metrics pending

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

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by reproducing the issue's TypeVar example and examining how mypy reports the type-var error when Optional[CallbackResult] is returned as CallbackResult. Done means producing a clearer diagnostic that explains the mismatch and covers simple wrappers such as Optional, Union, or List.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
compilers, devtools
Issue type
Feature
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.