python / python/typing

How to alias `Annotated` to a subscriptable type

Ouverte
#779 3 commentaires 2 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

Hi, I want to create a type alias that simply wraps a tuple into Annotated.

PEP 593

I want to be able to write

SpecialReturn[int, bool, str]

And get

Annotated[Tuple[int, bool, str], 'special return!']

Among other things, I've tried:

class SpecialReturn():
    def __class_getitem__(self, params: Tuple[Any, ...]) -> Tuple[Any, ...]:
        return typing.cast(
            Tuple[Any, ...],
            _typing.Annotated[
                typing.Tuple.__getitem__(params),
                'multiple_return',
            ]
        )

Which mypy is happy with the declaration, but not using it:

import typing

from typing import Annotated, Any, Tuple


class SpecialReturn():
    def __class_getitem__(self, params: Tuple[Any, ...]) -> Tuple[Any, ...]:
        return typing.cast(
            Tuple[Any, ...],
            Annotated[
                typing.Tuple.__getitem__(params),
                'multiple_return',
            ]
        )


def test() -> SpecialReturn[int, int]:
    return 1, 2
test8.py:17: error: "SpecialReturn" expects no type arguments, but 2 given
test8.py:18: error: Incompatible return value type (got "Tuple[int, int]", expected "SpecialReturn")

Which happens because I guess mypy does not evaluate the type annotation, it just treats SpecialReturn as a separate type. I am not sure what is the reasoning behind this, but I assume there it makes sense in some way(?).

So, is there any alternative? How do achieve this? I essentially want to alias Tuple and be able to find out at runtime if the type is a normal tuple or my special one.

My first jab at this, and what I think makes most sense to a Python developer is the following

from typing import Tuple


class SpecialReturn(Tuple):
    pass


def test() -> SpecialReturn[int, int]:
    return 1, 2

But mypy can't handle it either:

test.py:4: error: Missing type parameters for generic type "Tuple"
test.py:8: error: "SpecialReturn" expects no type arguments, but 2 given
test.py:9: error: Incompatible return value type (got "Tuple[int, int]", expected "SpecialReturn")

I was thinking maybe something like this was possible with Annotated, but it seems not.

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

Commencez par lire PEP 593 et les exemples de cette issue, puis examinez la manière dont le typing project représente Annotated, les alias génériques et class_getitem. L’issue ne nomme aucun fichier, test ou point d’entrée de l’implémentation, et sa résolution nécessiterait de déterminer si ce comportement doit être pris en charge et comment il devrait être spécifié.

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

Évaluation

Stack technique
python
Domaine
devtools
Type d'issue
Fonctionnalité
Difficulté
5/5
Temps estimé
Plus d'une semaine
Activité
À l'abandon
Clarté
À clarifier
Accessibilité débutants
20/100

Recevez les nouvelles issues par e-mail

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