Skip to content

Dict created by dict.fromkeys with None as default value is not checked properly #5512

@miguelsanchez-eb

Description

@miguelsanchez-eb

Bug Report

A method that is annotated to return a dict is not raising an error when the return value is generated with dict.fromkeys using no default value (i.e. having None as the value of the dict).

From Python documentation:

classmethod fromkeys(iterable[, value])
Create a new dictionary with keys from iterable and values set to value.

fromkeys() is a class method that returns a new dictionary. value defaults to None. All of the values refer to just a single instance, so it generally doesn’t make sense for value to be a mutable object such as an empty list. To get distinct values, use a dict comprehension instead.

To Reproduce

  1. Create a method like the following one:
from typing import Dict

def my_method() -> Dict[str, int]:
    return dict.fromkeys("foo")
  1. Run mypy over the file.
  2. See Success: no issues found in 1 source file

Expected Behavior

The expected behavior should be the same as running the following steps:

  1. Create a method like the following one:
from typing import Dict

def my_method() -> Dict[str, int]:
    return dict.fromkeys("foo", None)
  1. Run mypy over the file.
  2. See error: Argument 2 to "fromkeys" of "dict" has incompatible type "None"; expected "int" Found 1 error in 1 file (checked 1 source file)

Your Environment

  • Mypy version used: mypy==0.812
  • Mypy command-line flags: "mypy myfile.py"
  • Mypy configuration options from mypy.ini (and other config files): N/A
  • Python version used: Python 3.8.0
  • Operating system and version: macOS Catalina 10.15.7

Thanks.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions