python / python/mypy

Error on dict construction from iterable items

Aperta
#9,938 2 commenti 0 reazioni 0 assegnatari Vedi su GitHub

Nessuno ha ancora preso questa issue.

bug
Lingua principale
Python
Stelle
20.6k
Fork
3.3k
Metriche di merge delle PR
Metriche PR in attesa

Descrizione

Bug Report

Attempting to construct a mapping from objects that are designed to be constructed into dict items results in an error.

To Reproduce

Run mypy on this file:

from typing import Dict


class MyObject(str):
    """
    >>> tuple(MyObject('G'))
    ('G', 71)
    """
    def __iter__(self):
        return iter((self, ord(self)))


def get_mapping() -> Dict[str, int]:
    """
    >>> get_mapping()
    {'a': 97, 'b': 98}
    """
    items = MyObject('a'), MyObject('b')
    return dict(items)

In this file, MyObject implements __iter__ to return a key/value pair such that a dict can be constructed from an iterable of MyObjects.

Note that python -m doctest dictable.py passes.

Expected Behavior

Mypy should honor dict's behavior to produce pairs from objects if they're iterable and accept any iterable of objects that when iterated on produce pairs of compatible types.

Actual Behavior

dictable.py:18: error: Argument 1 to "dict" has incompatible type "Tuple[MyObject, MyObject]"; expected "Iterable[Tuple[str, int]]"
Found 1 error in 1 file (checked 1 source file)

Your Environment

  • Mypy version used: 0.790
  • Mypy command-line flags: none
  • Mypy configuration options from mypy.ini (and other config files): none
  • Python version used: 3.9.0
  • Operating system and version: macOS 11.0

Guida per i contributori

Apri la guida per i contributori

Come iniziare

  1. Leggi tutta la issue e poi la guida ai contributi del progetto.
  2. Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
  3. Fai un fork del repository e lavora su un branch.
  4. Apri una pull request che faccia riferimento al numero della issue.

Direzione di ricerca

Inizia eseguendo mypy sull’esempio riprodotto in dictable.py e confrontalo con il comportamento corretto del doctest. Traccia come viene tipizzata la costruzione del dict, quindi verifica che vengano accettati oggetti elemento iterabili compatibili, mantenendo invariato il comportamento esistente del controllo dei tipi.

Scritto dal modello di indicizzazione a partire dal testo della issue.

Valutazione

Stack tecnologico
python
Ambito
devtools
Tipo di issue
Bug
Difficoltà
4/5
Tempo stimato
3-5 giorni
Stato di attività
Ferma
Chiarezza
Abbastanza chiara
Idoneità per principianti
45/100

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.