python / python/mypy

`dataclasses.replace` should be able to return differently-parametrized generic dataclasses

Abierto
#19,694 0 comentarios 0 reacciones 0 asignados Ver en GitHub

Nadie ha tomado este issue todavía.

feature
Lenguaje dominante
Python
Estrellas
20.6k
Forks
3.3k
Merge medio
1 d 18 h
PR fusionados (30 d)
54

Descripción

Feature

Consider an instance of a generic dataclass on which we call dataclasses.replace in such a way that the replacement would change the type argument (because it changes the types of fields that involve the type parameter):

from dataclasses import dataclass, replace

@dataclass(frozen=True)
class A[T]:
  a: T

a_int: A[int] = A(a=1)
a_str: A[str] = replace(a_int, a="1")

Mypy currently reports errors for the last line:

example.py:9: error: Incompatible types in assignment (expression has type "A[int]", variable has type "A[str]")  [assignment]
example.py:9: error: Argument "a" to "replace" of "A[int]" has incompatible type "str"; expected "int"  [arg-type]
Found 2 errors in 1 file (checked 1 source file)

To me, it seems like this should be allowed and Mypy should understand that the replace call will return an instance of A[str], only reporting errors when the replacements have types that are completely incompatible with the class's field definitions.

Pitch

Users can currently work around the lack of this feature by defining their own replace method with overloads, e.g.:

@dataclass(frozen=True)
class A[T]:
  a: T

  @overload
  def replace[U](self, *, a: U) -> A[U]: ...

  @overload
  def replace(self) -> A[T]: ...

  # None as default for simplicity, in reality a unique sentinel may be better
  def replace(self, *, a: U | None = None) -> A[T] | A[U]:
    # With e.g. Pyright, we can just write:
    # return A(a=a) if a is not None else A(a=self.a)
    # But Mypy as of 1.17.1 doesn't like that
    # (see https://github.com/python/mypy/issues/19534),
    # so we have to be a bit more verbose:
    x: A[T] | A[U]
    if a is not None:
      x = A(a=a)
    else:
      x = A(a=self.a)
    return x

But this gets old fast, especially when there are N > 1 type parameters and you have to write out overloads for all 2N possible replace calls.

To me personally, it's not that urgent and I can live with the workaround for now (thankfully, in my specific situation I only have 2 type parameters at most). Still, it would be nice if this "just worked".

Additional context

The same issue would apply to the new (Python 3.13+) copy.replace and object.__replace__ methods, but these don't even have replacement argument type checking like dataclass.replace does yet, so I guess it's way too early for that.

Other languages

In Rust, the equivalent for its copy-replacing-only-some-fields idiom is available in nightly builds (but not stable yet):

Guía de contribución

Abrir la guía de contribución

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 el ejemplo mínimo de dataclass genérico del issue y sigue cómo mypy infiere los argumentos y los tipos de retorno de dataclasses.replace. Añade cobertura de regresión específica que muestre que cambiar un parámetro de tipo se acepta, mientras que las sustituciones realmente incompatibles siguen produciendo errores; el issue no indica ningún archivo fuente ni ninguna ruta de prueba existente.

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

Evaluación

Stack tecnológico
python
Área
tooling
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
35/100

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.