python / python/typeshed

type annotated arguments in zip function lead to wrong return types when using the star operator

Offen
#9,143 4 Kommentare 1 Reaktion 0 zugewiesene Personen Auf GitHub ansehen

Dieses Issue hat noch niemand übernommen.

Vorherrschende Sprache
Python
Sterne
5.1k
Forks
2.1k
Ø Merge
1 T. 19 Std.
Gemergte PRs (30 T.)
82

Beschreibung

This issue is a followup to the following issue:
https://github.com/microsoft/pylance-release/issues/3598

Here's the code that is wrongly annotated:

test_list: list[tuple[int, str]] = [(1, 'testa'), (2, 'testb')]

a: tuple[int]
b: tuple[str]

a, b = zip(*test_list)

Pylance warns about an assignment of typle[int | str] to the tuples a and b.
The tuple annotation is being converted to an Iterator annotation, which does not support a sequence of types (see Eric's reply to the previous issue for details). Therefore, the resulting tuples after the unpacking operation are not as precisely typed as they could be.

And here is the typeshed code that leads to the 'wrong' type annotations:

https://github.com/python/typeshed/blob/7b3fff714a48f0413141ba10344f9473e3ec4a18/stdlib/builtins.pyi#L1673-L1715

I'm not sure if it is currently possible to fix this. I had the idea of adding a type hint to the *args keyword, so something like this:

@overload
        def __new__(cls, __iter1: _T2:=Sequence[_T1], *args: _T2, strict: bool = ...) -> zip[tuple[_T1]]: 

I'm unsure if this is valid python syntax and if it would result in the desired behavior. I'm also unsure how python would decide between the proposed constructor and the one that is currently being used during typechecking my example:
https://github.com/python/typeshed/blob/7b3fff714a48f0413141ba10344f9473e3ec4a18/stdlib/builtins.pyi#L1675-L1676

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 damit, das kommentierte zip(*test_list)-Beispiel nachzustellen, und lies die zip-Überladungen in stdlib/builtins.pyi um die Zeilen 1673-1715. Sieh dir das verlinkte typeshed-Issue und das frühere Pylance-Issue an, bevor du eine Änderung an den Überladungen bewertest. Erledigt ist es, wenn die entpackten Variablen als tuple[int] und tuple[str] abgeleitet werden, ohne Zuweisungswarnungen.

Vom Indexierungsmodell aus dem Issue-Text verfasst.

Bewertung

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

Neue Issues direkt in Ihr Postfach

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