python / python/mypy

unpacking dict in function call with optional arguments fails

Aperta
#10,008 1 commento 16 reazioni 0 assegnatari Vedi su GitHub

Nessuno ha ancora preso questa issue.

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

Descrizione

Bug Report

Unpacking a dict when calling a function with **kwargs should not fail. This seems to be related to #4771 and #9676, but slightly different since the function definition is wider than those reports.

To Reproduce

from __future__ import annotations

from collections.abc import Mapping
from typing import Any, cast, TYPE_CHECKING


def test(one: int | None = None, **kwargs: Any) -> int | None:
    print(repr(kwargs))
    return one


if TYPE_CHECKING:
    reveal_type(test)
    reveal_type(test())
    reveal_type(test(test='one'))
    reveal_type(test(**{'test': 'one'}))

which outputs:

test.py:13: note: Revealed type is 'def (one: Union[builtins.int, None] =, **kwargs: Any) -> Union[builtins.int, None]'
test.py:14: note: Revealed type is 'Union[builtins.int, None]'
test.py:15: note: Revealed type is 'Union[builtins.int, None]'
test.py:16: error: Argument 1 to "test" has incompatible type "**Dict[str, str]"; expected "Optional[int]"  [arg-type]

Expected Behavior

There is no issue passing kwargs via a dict and you shouldn't need to cast to a Mapping type.

Actual Behavior

There is an error message, but reveal_type(test(**cast(Mapping[str, str], {'test': 'one'}))) (or saving as a temporary variable with Mapping as its type) will allow the code to succeed.

Your Environment

  • Mypy version used: 0.800
  • Mypy command-line flags: --show-error-codes
  • Mypy configuration options from mypy.ini (and other config files):
  • Python version used: 3.8

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

Esegui il reproducer Python 3.8 fornito con mypy e --show-error-codes, confrontando gli argomenti con parole chiave diretti con il caso dell'unpacking di un dizionario. Traccia l'unpacking degli argomenti insieme ai parametri opzionali e a **kwargs; il lavoro è terminato quando la chiamata con unpacking del dizionario viene accettata senza richiedere un cast a Mapping e mantiene il tipo restituito previsto.

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.