`SelectionList.toggle()` with a value that isn't in the list selects it and then raises `KeyError`

Abierto Apto para principiantes
#6,767 1 comentario 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
frontend

Línea de trabajo

Empieza en src/textual/widgets/_selection_list.py en _toggle(), luego lee _select(), _deselect() y la consulta de _values que se usa para enviar SelectionToggled; _make_selection() explica por qué _select() se ejecuta antes de que se rellene _values. Reproduce el problema con el fragmento del issue y luego haz que toggle() no haga nada ante un valor desconocido antes de cualquier mutación o envío de mensajes, manteniendo intacta la ruta de select()/_make_selection(). Ejecuta las pruebas existentes de la lista de selección en tests/ para confirmar que no haya regresiones; se considera terminado cuando no hay KeyError, no hay SelectedChanged y selected no cambia.

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

Descripción

Hi! I hit this while writing generated tests against Textual's widgets.

Calling SelectionList.toggle() with a value that isn't one of the list's options changes the selection, posts SelectedChanged, and only then raises KeyError. The value stays in selected, and deselect_all() doesn't remove it, since that only walks the options.

import asyncio
from textual.app import App, ComposeResult
from textual.widgets import SelectionList

class ToggleApp(App):
    def compose(self) -> ComposeResult:
        yield SelectionList(("One", 1), ("Two", 2))

    def on_selection_list_selected_changed(self, event: SelectionList.SelectedChanged) -> None:
        print("SelectedChanged, selected =", event.selection_list.selected)

async def main() -> None:
    app = ToggleApp()
    async with app.run_test() as pilot:
        selection_list = app.query_one(SelectionList)
        try:
            selection_list.toggle(3)  # 3 is not a value in the list
        except Exception as error:
            print("toggle(3) raised", type(error).__name__, error)
        await pilot.pause()
        print("selected after toggle(3):", selection_list.selected)
        selection_list.deselect_all()
        selection_list.select(4)  # also not in the list
        await pilot.pause()
        print("selected after select(4):", selection_list.selected)

asyncio.run(main())

Output (the same on 8.2.7 and on main at 5e5b7ef):

toggle(3) raised KeyError 3
SelectedChanged, selected = [3]
selected after toggle(3): [3]
SelectedChanged, selected = [3, 4]
selected after select(4): [3, 4]

_toggle() calls _select() (or _deselect()) and then looks the value up in _values to post SelectionToggled, which raises for an unknown value after the change has been made.

I'd expect toggle() of an unknown value to change nothing, the way deselect() of an unknown value does. select() of an unknown value also adds it to selected without complaint (last two lines). Is that intended? _make_selection() relies on _select() before _values is filled in, so I've left select() alone in the PR.

Textual 8.2.7 and main (5e5b7ef), Python 3.13, macOS.

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.