python / python/typing

Proposal: Programmatically create types

Abierto
#1,371 18 comentarios 1 reacción 0 asignados Ver en GitHub

Nadie ha tomado este issue todavía.

topic: feature
Lenguaje dominante
Python
Estrellas
1.8k
Forks
302
Merge medio
23 h
PR fusionados (30 d)
8

Descripción

This proposal is aimed at solving two related problem. First, when defining a multi-ary operator on Numpy arrays, e.g., leaky integral, then you ideally want to bake in Numpy type promotion rules. However, even Numpy doesn't use its own type promotion rules in its type annotations.

So, my suggestion is the following:

from typing import SyntheticType

def ResultType(*args: Any) -> SyntheticType[DType]:
  return result_type(*args)  # Something like this, but would have to deal with e.g., numpy.ndarray[typing.Any, numpy.dtype[numpy.floating[typing.Any]]]

# Then...
    @overload
    def __add__(self: T, other: U) -> NDArray[ResultType[T, U]]: ...  # type: ignore[misc]

The type checker could be called with a special argument, like --create_synthetic_stubs. This would

  • Run type checking and collect a list of unique argument tuples to synthetic type functions like ResultType.
  • Start a Python interpreter and call the synthetic type functions using the the arguments (which are Python objects representing types, e.g., T=float and U=numpy.ndarray[typing.Any, numpy.dtype[numpy.floating[typing.Any]]]).
  • It would then write the results to some pyi file in some canonical table-like format, like:
    `ResultType: SyntheticTypeMapping = {(float, float): float, ...}

The table could either be just stored in the cache. Users of the library would have to generate this file, which means type checkers run code in the library.

The other problem this solves is one that I would like to annotate dataclasses whose elements can be None or int besides whatever they've specified as. See here for a description as to why. It would be pretty easy to code a Python transformation from a dataclass type to a new dataclass type with the transformed field types.

I realize this is pretty extreme, but the payoff would be commensurate.

Guía de contribución

No hay ninguna guía de contribución indexada para este repositorio

Primeros pasos

  1. Lee el issue completo y luego la guía de contribución del proyecto.
  2. Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
  3. Haz un fork del repositorio y trabaja en una rama.
  4. Abre un pull request que haga referencia al número del issue.

Línea de trabajo

Comienza con la propuesta y sus referencias enlazadas a tjax leaky_integral.py, las anotaciones de tipos de NumPy y los pytrees de JAX. Revisa el flujo de trabajo de SyntheticType propuesto, el paso de recopilación del type-checker, el formato de los stubs generados y la transformación de dataclass; después, determina si el alcance puede convertirse en un diseño acordado. La tarea estaría terminada cuando exista una dirección o especificación decidida, no con un pequeño cambio aislado.

Escrito por el modelo de indexación a partir del texto del issue.

Evaluación

Stack tecnológico
numpy, python
Área
devtools
Tipo de issue
Nueva funcionalidad
Dificultad
5/5
Tiempo estimado
Más de una semana
Estado de actividad
Estancado
Claridad
Necesita aclaración
Aptitud para principiantes
20/100

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.