python / python/typing

Annotate function which return a specific module (e.g. `-> Literal[np]`)

Ouverte
#1,039 7 commentaires 6 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

Problem

Currently it's not possible to annotate a function which return a specific module, like:

np = load_numpy()  # def load_numpy() -> ??:

x = np.array(123)  # << I want to have auto-complete & type checking here
  • -> types.ModuleType does not work as too generic (no auto-complete, nor static type checking,...)
  • Protocol is not applicable in practice: maintaining a numpy protocol which has 500+ symbols is just not realistic

Use case

Here are some concrete use-case where this feature is needed (also collected from this thread comments):

  1. Numpy Enancement Propopsal 37 propose a recipe to have code working with various numpy implementation ( numpy, jax.numpy, tensorflow.numpy):

    def duckarray_add_random(array):
        module = np.get_array_module(array)           # def get_array_module() -> Literal[np]
        noise = module.random.randn(*array.shape)     # << I want to have auto-complete & type checking here
        return array + noise
    

    I developed my version at https://github.com/google/etils/tree/main/etils/enp#code-that-works-with-nparray-jnparray-tftensor

  2. Lazy imports is a common pattern to only import a module if needed. Like: https://github.com/tensorflow/datasets/blob/76f8591def26afaca16340b06d057553582f6163/tensorflow_datasets/core/lazy_imports_lib.py#L40-L197

    beam = lazy_import.apache_beam
    
    beam.Pipeline()  # << No auto-completion
    
  3. From another user comment: Similar issue to to 1. encountered at: https://github.com/data-apis/array-api/issues/267

  4. From another user comment:

    I encountered a similar issue before. Although not with with the return type but rather version dependent imports, e.g. assign either ast (Py >= 3.8) or typed_ast.ast3 to a common variable.

Proposal

I would like to annotate my function as:

def load_numpy() -> Literal[np]:

Or:

def load_numpy() -> np:

For the lazy-loading case, typing.TYPE_CHECKING pattern could be used:

if typing.TYPE_CHECKING:
  import numpy as np


def load_numpy() -> Literal[np]:
  import numpy as np
  return np

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 la Proposal et les exemples liés d’importation de NumPy, de lazy-import et dépendants de la version, puis examinez la discussion existante sur le typing issue. Aucun fichier d’implémentation ni test n’est nommé ; c’est terminé lorsque la manière prise en charge d’exprimer un retour dont la valeur est un module, ainsi que son comportement en matière d’auto-complétion et de vérification de types, est spécifiée.

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

Évaluation

Stack technique
python
Domaine
tooling
Type d'issue
Fonctionnalité
Difficulté
5/5
Temps estimé
Plus d'une semaine
Activité
À l'abandon
Clarté
Plutôt claire
Accessibilité débutants
25/100

Recevez les nouvelles issues par e-mail

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