KEMBAR78
Require an annotation if inferred list or dict item type is object · Issue #3816 · python/mypy · GitHub
Skip to content

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

@JukkaL

Description

@JukkaL

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.

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions