python / python/typing

PEP 692 follow up: Unpacking compatibility with dataclass/others

Ouverte
#1,495 11 commentaires 101 réactions 0 personnes assignées Voir sur GitHub

Personne n'a encore pris cette issue.

topic: feature
Langage dominant
Python
Étoiles
1.8k
Forks
302
Merge moyen
23 h
PR mergées (30 j)
8

Description

The Unpack addition has been great, however a lot of our code has an existing library of dataclasses instead of typed dictionaries. Here's a dummy example using one of the more common patterns that will suffer from this: factory methods.

from dataclasses import dataclass

from typing import Unpack


@dataclass
class Person:
    name: str
    age: int


# ERR: Expected TypeDict argument for Unpack
def person_factory(**kwargs: Unpack[Person]):
    return Person(**kwargs)


if __name__ == "__main__":
    steve = person_factory(name="Steve", age=42)

Right now, the "fix" for us would be to duplicate the dataclass as TypedDict, but code duplication is obviously not ideal. If there's another way, please let me know, otherwise I think a really valuable enhancement to the Unpack method would be to allow it to accept other objects, such as a dataclass or a pydantic BaseModel given the popularity of pydantic and FastAPI.

Antoher use case I can think of would be to be able to Unpack[function] or Unpack[class]. Common examples here would include matplotlib and plotly, where plotting functions often expose kwargs which just get passed to a child function. That child function has all the documentation and type hinting you'd need, but its unusable unless its copied into a TypeDict (I believe). For a concrete example, the top level maptlotlib plt.plot() function takes kwargs which are passed to the Line2D class

Guide de contribution

Aucun guide de contribution indexé pour ce dépôt

Par où commencer

  1. Lisez l'issue en entier, puis le guide de contribution du projet.
  2. Signalez en commentaire que vous la prenez — cela évite que deux personnes fassent le même travail.
  3. Forkez le dépôt et travaillez sur une branche.
  4. Ouvrez une pull request qui référence le numéro de l'issue.

Piste de recherche

Lisez d’abord le comportement de Unpack de PEP 692 et l’exemple de méthode de fabrique. Comparez ensuite les cas demandés de dataclass, pydantic BaseModel et fonction/classe, puis définissez le périmètre pris en charge et les exigences de compatibilité. C’est terminé lorsque la proposition définit un comportement décidé et testable, plutôt que de se limiter à des workarounds TypedDict dupliqués.

Rédigé par le modèle d'indexation à partir du texte de l'issue.

Évaluation

Stack technique
python
Domaine
developer-experience
Type d'issue
Fonctionnalité
Difficulté
5/5
Temps estimé
Plus d'une semaine
Activité
Calme
Clarté
À clarifier
Accessibilité débutants
35/100

Recevez les nouvelles issues par e-mail

Un résumé court des issues GitHub adaptées aux débutants.