python / python/mypy

Specialize empty collections to Any as a fallback

Open
#15,433 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

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

Description

Context

I have a pending PR for typeshed which fixes overparameterized dict.get and dict.pop methods: python/typeshed#10294. The PR causes a lot of failures in various GitHub projects due to how mypy treats empty collections. Specifically, if dict.get is annotated as

class dict(Generic[KT, VT]):
    def get(self, key: KT, default: T) -> T | VT: ...

mypy infers the type of v in

def test(d: dict[str, Any]):
    v = d.get("foo", {})

to be Any | dict[<unknown>, <unknown>], instead of Any | dict[Any, Any].

Feature

Specialize empty collections to Any if no other information is available to recover type arguments.

Pitch

Using <unknown> instead of Any requires users to cast or add type annotations where they otherwise will not be necessary. See comments in the PR for a few examples from real projects.

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 shown dict.get example in mypy and inspect how empty collection expressions are inferred when no type arguments can be recovered. Done means empty collections in this situation are specialized to Any rather than unknown, while the behavior remains covered by relevant type-checking tests.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
compilers
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.