python / python/mypy

Improve error message when using `TypeVar` in functions

Open
#12,012 4 comments 1 reaction 0 assignees View on GitHub

Nobody has claimed this yet.

bug topic-error-reporting
Dominant language
Python
Stars
20.6k
Forks
3.3k
PR merge metrics
PR metrics pending

Description

We're trying to add static typing support to the Application object in aiohttp. Currently the latest proposal is to define a custom key which can be used something like:

k = AppKey("k", int)
app[k] = "foo"

The method definition looks like:

def __setitem__(self, key: AppKey[_T], value: _T) -> None:

The problem is, that example produces a rather uninformative error:

Cannot infer type argument 1 of "__setitem__" of "Application"  [misc]

I'd really like to see something along the lines of "str" is not compatible with "int" so the user can easily understand the issue.

Related PR: https://github.com/aio-libs/aiohttp/pull/6498

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

Reproduce the example using Application.setitem, AppKey, and TypeVar, then trace mypy's generic function type-inference and diagnostic handling for the reported [misc] error. Done means the same mismatch produces an actionable message such as "str" is not compatible with "int", with the relevant behavior covered by mypy tests.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
tooling
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
30/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.