python / python/typing

Request: an AssertingTypeGuard type for TypeGuard-like semantics

Ouverte
#930 6 commentaires 28 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

There is a frequent pattern of TypeGuard-like functions which assert or otherwise raise an exception if a type constraint is not met.

For example, https://github.com/microsoft/pyright/issues/2007 points to a case in which unittest provides assertIsNotNone, but a type-checker cannot infer that type narrowing has occurred. Arguably, the popular typeguard library is based around an implementation of "asserting" type guards. (One which deduces what assertions should be made from the annotations.)

TypeGuards allow for semantics like

y: str
assert is_list_of_str(x)
assert len(x) > 0
y = x[0]

An AssertingTypeGuard would allow for

y: str
assert_is_nonempty_list_of_str(x)  # note, this encodes another runtime check, the len check
y = x[0]

This becomes especially valuable if we consider that you might not want to do this all with assert. I may, as an author, prefer my own custom exceptions, e.g.

def assert_is_nonempty_list_of_str(x) -> AssertingTypeGuard[list[str]]:
    if not isinstance(x, list):
        raise ExpectedListError(x)
    if not x:
        raise EmptyContainerError(x)
    if not all(isinstance(y, str) for y in x):
        raise ContainedInvalidTypeError(x, str)
    return x

(Apologies if this repo is the wrong place to submit this request/idea. I'm happy to go through another process if necessary.)

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

La demande n’identifie aucun fichier d’implémentation ni aucun test. Commencez par examiner les exemples de TypeGuard, l’issue Pyright liée et la discussion sur la bibliothèque typeguard ; déterminez si un AssertingTypeGuard doit faire partie de la spécification de typing et définissez la sémantique attendue du narrowing et des exceptions avant l’implémentation.

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é
Plutôt claire
Accessibilité débutants
35/100

Recevez les nouvelles issues par e-mail

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