Apparent false positive when using reduce with dictionaries

Open
#4,150 3 comments 2 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Assessment

Difficulty
3/5
Estimated time
1-2 days
Newbie friendliness
45/100
Issue type
Bug
Clarity
Mostly clear
Activity status
Stale
Tech stack
python
Domain
devtools

Research direction

Reproduce the report from the test.py example using the stated Python 3.6.3 and mypy 0.521 versions, then trace how functools.reduce is typed for Iterable[dict]. Add regression coverage for the shown reduce_func call; done means the valid dictionary reduction no longer produces the incompatible Callable error.

Written by the indexing model from the issue text.

Description

bug false-positive priority-1-normal

Python 3.6.3, mypy 0.521.

When using reduce on an Iterable/List of dictionaries, mypy seems to be confused about the signature of the function and seems to be unpacking the dictionary into an iterable of tuples. The following example appears to conform to the reduce function's parameters, so no errors should be appearing.

https://docs.python.org/3.6/library/functools.html#functools.reduce

test.py:14: error: Argument 1 to "reduce" has incompatible type Callable[[Dict[Any, Any], Dict[Any, Any]], Dict[Any, Any]]; expected Callable[[Iterable[Tuple[Any, Any]], Dict[Any, Any]], Iterable[Tuple[Any, Any]]]
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

from functools import reduce

from typing import Iterable

def update(ccc: dict, meta: dict) -> dict:
    foo = dict(ccc)
    foo.update(meta)
    return foo

def reduce_func(configs: Iterable[dict]) -> dict:
    output = dict(reduce(update, configs, {})) # type: dict
    return output

print(reduce_func([{"a": 1}, {"b": 2}]))

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.