Watchers of computed reactives run in a different order on each run

Abierto Apto para principiantes
#6,790 2 comentarios 0 reacciones 0 asignados Ver en GitHub

Nadie ha tomado este issue todavía.

Evaluación

Dificultad
2/5
Tiempo estimado
1-3 horas
Aptitud para principiantes
72/100
Tipo de issue
Error
Claridad
Bien especificado
Estado de actividad
Activo
Stack tecnológico
python
Área
backend

Línea de trabajo

Empieza en Reactive._compute, donde el issue identifica la iteración sobre los nombres de reactivos calculados. Busca las pruebas existentes de reactivos y añade una prueba de regresión que registre las llamadas de los watchers cuando cambie un reactivo fuente. Está terminado cuando el orden de los watchers es determinista entre ejecuciones con distintos valores de PYTHONHASHSEED y las pruebas relevantes pasan.

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

Descripción

Hi! I hit this while writing tests that record the order of watcher calls. Reactive._compute loops over obj._reactives.keys() & obj._computes, a set of strings, so the order of the computes, and of the watchers they trigger, depends on string hashing, which Python randomises per process.

import asyncio

import textual
from textual.app import App
from textual.reactive import reactive

class ComputeApp(App):
    value = reactive(0)
    alpha = reactive(0)
    beta = reactive(0)
    gamma = reactive(0)
    delta = reactive(0)

    def __init__(self) -> None:
        super().__init__()
        self.calls: list[str] = []

    def compute_alpha(self) -> int:
        return self.value + 1

    def compute_beta(self) -> int:
        return self.value + 2

    def compute_gamma(self) -> int:
        return self.value + 3

    def compute_delta(self) -> int:
        return self.value + 4

    def watch_alpha(self) -> None:
        self.calls.append("alpha")

    def watch_beta(self) -> None:
        self.calls.append("beta")

    def watch_gamma(self) -> None:
        self.calls.append("gamma")

    def watch_delta(self) -> None:
        self.calls.append("delta")

async def main() -> None:
    app = ComputeApp()
    async with app.run_test() as pilot:
        app.calls.clear()
        app.value = 10
        await pilot.pause()
        print(app.calls)

asyncio.run(main())

Run five times with different PYTHONHASHSEED values, on main (5e5b7ef), Python 3.13:

PYTHONHASHSEED=0: ['alpha', 'delta', 'beta', 'gamma']
PYTHONHASHSEED=1: ['beta', 'delta', 'gamma', 'alpha']
PYTHONHASHSEED=2: ['delta', 'gamma', 'alpha', 'beta']
PYTHONHASHSEED=3: ['gamma', 'beta', 'delta', 'alpha']
PYTHONHASHSEED=4: ['gamma', 'alpha', 'beta', 'delta']

8.2.7 gives a different mix for the same seeds. Without PYTHONHASHSEED set, the order changes from run to run.

The values are right either way, since reading a computed reactive computes it. Only the order of the watchers moves. I expected the same order on every run. A one-line fix is to sort the names in _compute, which makes the order alphabetical. Declaration order would be nicer, but it would mean walking every reactive on each change, so I went for sorting. Happy to do it the other way if you prefer.

Lenguaje dominante
Python
Estrellas
37.7k
Forks
1.5k
Métricas de merge de PR
Sin PR fusionados en 30 d

Preparar el entorno

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.

Más de Textualize/textual

Todos los issues de Textualize/textual

Issues similares

Más issues de Python

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.