python / python/mypy

Variadic tuple unpacking requires a star target -- why?

Offen
#17,282 3 Kommentare 2 Reaktionen 0 zugewiesene Personen Auf GitHub ansehen

Dieses Issue hat noch niemand übernommen.

bug
Vorherrschende Sprache
Python
Sterne
20.6k
Forks
3.3k
PR-Merge-Kennzahlen
PR-Kennzahlen ausstehend

Beschreibung

Bug Report

When attempting to unpack a tuple that uses Unpack, if you don't use a star target to capture the variadic tuple as a list, you get the error Variadic tuple unpacking requires a star target.

This is overly strict and prescriptivist and is not even applied consistently between similar type concepts within mypy.

  1. You definitely can do this if the lengths check out.
  2. pyright doesn't raise an error like this. You are simply on your own for length checking the unpacking of indeterminate length tuples, just like you are for list, another indeterminate length unpackable sequence.
  3. In fact, this is also how mypy treats unpacking list. It doesn't raise an error if you don't use a star target.
  4. I have a real use case where I want to do exactly this. I lay out my use case in this bug report to pyright: https://github.com/microsoft/pyright/issues/7987

To Reproduce

from typing import Tuple

from typing_extensions import Unpack


def foo() -> Tuple[int, Unpack[Tuple[str, ...]]]:
    return 1, "bar", "baz"

a, b, c = foo()  # error: Variadic tuple unpacking requires a star target  [misc]

d, e, f = [1, "bar", "baz"]  # OK

Gist URL: https://gist.github.com/mypy-play/4014976ca069e54b5c1fe86a45353f58
Playground URL: https://mypy-play.net/?mypy=master&python=3.12&gist=4014976ca069e54b5c1fe86a45353f58

Expected Behavior

No errors in the above example. a's type should be revealed to be int, and b and c's types should be revealed to be str.

Actual Behavior

An error, and a, b, and c are all revealed to be Any.

Beitragsleitfaden

Beitragsleitfaden öffnen

Erste Schritte

  1. Lies das ganze Issue und danach den Beitragsleitfaden des Projekts.
  2. Schreib ins Issue, dass du es übernimmst — das erspart doppelte Arbeit.
  3. Forke das Repository und arbeite in einem Branch.
  4. Öffne einen Pull Request, der die Issue-Nummer nennt.

Rechercherichtung

Beginne mit der minimalen Reproduktion im Report oder dessen mypy-play-URL und vergleiche die Diagnose und die angezeigten Typen für das Entpacken von Tupeln und Listen. Erledigt ist es, wenn die Tupelzuweisung keinen Fehler erzeugt, a als int sowie b und c als str anzeigt und im Listenfall keine Regression verursacht.

Vom Indexierungsmodell aus dem Issue-Text verfasst.

Bewertung

Tech-Stack
python
Bereich
compilers
Issue-Typ
Bug
Schwierigkeit
4/5
Geschätzter Aufwand
3-5 Tage
Aktivitätsstatus
Veraltet
Klarheit
Größtenteils klar
Anfängerfreundlichkeit
42/100

Neue Issues direkt in Ihr Postfach

Eine kurze Übersicht über anfängerfreundliche GitHub-Issues.