python / python/mypy

--disallow-any-generics is allowing defaultdict[Any, ...]

Open
#9,785 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

bug topic-disallow-any
Dominant language
Python
Stars
20.6k
Forks
3.3k
PR merge metrics
PR metrics pending

Description

Bug Report

(A clear and concise description of what the bug is.)

To Reproduce

this python file (I was working on advent of code, this is about as minimal as I could reproduce)

import collections
import re

PATTERN = re.compile('^([^ ]+ [^ ]+) bags contain (.*)$')
BAG_RE = re.compile(r'(\d+) ([^ ]+ [^ ]+)')


def compute(s: str) -> int:
    parents = collections.defaultdict(list)
    for line in s.splitlines():
        match = PATTERN.match(line)
        assert match
        k = match[1]
        targets = [(int(n), tp) for n, tp in BAG_RE.findall(match[2])]
        for _, color in targets:
            parents[color].append(k)

    total_colors = set()
    todo = parents['shiny gold']
    while todo:
        color = todo.pop()
        if color not in total_colors:
            total_colors.add(color)
            todo.extend(parents[color])

    reveal_type(parents)

    return len(total_colors)

Run with mypy --disallow-any-generics t.py

Expected Behavior

I expect an error requiring me to annotate parents = collections.defaultdict(list) because mypy has not inferred the key type (though, I think it should be able to infer that it is str from the code)

Actual Behavior

$ mypy t.py --disallow-any-generics
t.py:26: note: Revealed type is 'collections.defaultdict[Any, builtins.list[builtins.str*]]'

Your Environment

  • Mypy version used: 0.790
  • Mypy command-line flags: --disallow-any-generics
  • Mypy configuration options from mypy.ini (and other config files): N/A
  • Python version used: 3.8.5
  • Operating system and version: ubuntu 20.04

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 running mypy 0.790 with --disallow-any-generics on the reproducer in t.py and inspect the revealed defaultdict type. Trace the handling of collections.defaultdict(list) and generic type inference; done means the command reports the intended diagnostic or infers the key type consistently with the issue's expected behavior.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
devtools
Issue type
Bug
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.