Require an annotation if inferred list or dict item type is object

Open
#3,816 12 comments 1 reaction 0 assignees View on GitHub

Nobody has claimed this yet.

Assessment

Difficulty
5/5
Estimated time
Over a week
Newbie friendliness
28/100
Issue type
Feature
Clarity
Mostly clear
Activity status
Stale
Tech stack
python
Domain
tooling

Research direction

The reproducer is x = [1, 'a'], with the proposed behavior compared to mypy's handling of empty collections. Start by tracing inference for list and dictionary literals and the existing empty-collection annotation diagnostic. Done requires a decided scope for object-valued containers, an appropriate diagnostic, and coverage for the agreed cases.

Written by the indexing model from the issue text.

Description

topic-join-v-union topic-usability

Mypy infers the type List[object] for x in this example:

x = [1, 'a']

This is often not what the user expects and can be confusing, as there tends to be an error when the program tries to do something with the list. Often the user would prefer the type to be List[Any] or List[Union[int, str]], but generally the desired item type could be something else, such as an ABC or protocol (once protocols are supported).

It's perhaps impractical to unambiguously infer the desired type, but it would be easy enough to detect cases like these and require an explicit annotation. For the above example, mypy would require an annotation for x (and potentially suggest List[Any] or List[Union[int, str]] as the potential type), similar to how mypy deals with x = [].

For user-defined generic types object might be a reasonable value for a type parameter, so we should probably restrict this to things where the object type is likely a problem. For example, we could generate the message for the types List[object] and Dict[<anything>, object] only. It's less clear if we should do this for dictionaries withobject keys or for sets.

Dominant language
Python
Stars
20.6k
Forks
3.3k
Avg merge
1d 18h
Merged PRs (30d)
54

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.

More from python/mypy

All issues in python/mypy

Similar issues

More Python issues

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.