python / python/typing

Generic specialization?

Abierto
#1,250 2 comentarios 0 reacciones 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

I was wondering if it was possible to redefine what a particular generic means for a particular type (and maybe its subclasses, superclasses depending on covariance/contravariance?).

My use case comes from the scikit-learn API. In this API each "estimator" class has two set of attributes: those that are passed to __init__ and those that are computed after calling .fit() to fit the model. The convention is that the latest ones end with an underscore.
Also the fit method returns self.

In addition to that, there are methods, like predict, that are only allowed after fitting.

Currently the code that uses this library is like this:

my_estimator = MyEstimator(param1, param2)
my_estimator.fit(X_train, y_train)

# Now is safe to access fit attributes and call predict, score, etc
print(my_estimator.fitted_attr1_)
print(my_estimator.predict(X_test))

The idea was to allow Mypy (or other analyzer) to check these invariants using additional types. Instead of typing fit as:

def fit(self, X: ..., y: ...) -> Self

we could type it as

def fit(self, X: ..., y: ...) -> Fitted[Self]

We then would need a way to:

  • Define that Fitted[T] is a subclass of T. Similar to #802.
  • Define the particular fit attributes of Fitted[T] for a particular T.
  • Define that some methods. such as predict can only be used with a Fitted[T] object, and not with a T object.
  • Define that Fitted[Fitted[T]] == Fitted[T].

Then, only a small change would be needed in the previous code to allow type checkers to detect whether the invariants have been broken:

my_estimator = MyEstimator(param1, param2)
my_estimator = my_estimator.fit(X_train, y_train) # Line changed

# Now is safe to access fit attributes and call predict, score, etc
print(my_estimator.fitted_attr1_)
print(my_estimator.predict(X_test))

This is only a possibility. Alternatives include:

  • Defining a subclass just for the type-checker in a if TYPE_CHECKING: environment. This works for the basic usage illustrated here, but not in other generic cases, e.g.: typing a function that accepts a fitted estimator of any type. It also creates a parallel class structure, which should also be subclassed by subclasses, etc.
  • Just typing the whole class and don't let type-checkers to verify these invariants.

However I think that adding this flexibility to the type system could maybe help in other cases.

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 los ejemplos propuestos de Fitted[T] en este issue y lee el issue referenciado #802. Compara la herencia mediante subclases, la especialización, las restricciones de métodos y el comportamiento de idempotencia solicitados con las alternativas descritas; el trabajo se consideraría terminado cuando se haya acordado un diseño del sistema de tipos y los detalles de especificación correspondientes.

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

Evaluación

Stack tecnológico
python
Área
developer-experience
Tipo de issue
Nueva funcionalidad
Dificultad
5/5
Tiempo estimado
Más de una semana
Estado de actividad
Estancado
Claridad
Bastante claro
Aptitud para principiantes
25/100

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.