T(...).format(n=...) crashes with ValueError when the entry's smallest plural key is greater than n

Abierto Apto para principiantes
#12 0 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
74/100
Tipo de issue
Error
Claridad
Bien especificado
Estado de actividad
Activo
Stack tecnológico
python
Área
backend

Línea de trabajo

Empieza en pluralize/__init__.py, en la búsqueda de _translator alrededor de la línea 168, donde las claves de plural se convierten en enteros y se filtran según n. Comprueba cómo gestiona el proyecto las formas de reserva y las claves mal formadas, y añade pruebas para cantidades inferiores a la clave disponible más pequeña y para claves no numéricas. El objetivo se cumple cuando el renderizado ya no genera un ValueError sin controlar para estas entradas de traducción y las pruebas cubren el comportamiento de reserva.

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

Descripción

ValueError: max() iterable argument is empty when the smallest plural key in a translation is larger than n

If a translation entry only has plural forms for larger counts, rendering it with a smaller n crashes instead of falling back to a form.

Example — a partially filled cs.json (only the plural form was ever filled in, so the entry has just one key):

{"bed": {"5": "postelí"}}
>>> from pluralize import Translator
>>> T = Translator('translations')
>>> T.select('cs')
>>> print(T("bed").format(n=1))
ValueError: max() iterable argument is empty

Traceback on current master (pluralize/init.py line 168):

  File "pluralize/__init__.py", line 168, in _translator
    k = max(int(i) for i in translations.keys() if int(i) <= n)
ValueError: max() iterable argument is empty

The best-match lookup filters the keys with int(i) <= n, and when every key in the entry is greater than n (here: only key is 5, n is 1 — also n=0 for any entry that doesn't define a "0" form), the generator is empty and max() raises. The README's own Czech example ({"0": "no postel", "1": "postel", "2": "postele", "5": "postelí"}) shows that entries commonly skip the 0 form, so T("bed").format(n=0) on an entry like {"1": "postel", "5": "postelí"} hits the same crash.

Two smaller variants of the same line:

  • a non-numeric key in an entry (files written by other i18n tools, e.g. {"bed": {"many": "postelí"}}) raises ValueError: invalid literal for int() with base 10: 'many' from the same int(i);
  • the crash happens at render time inside str()/format(), so the error surfaces far from the file that caused it.

Suggested fix: default the lookup instead of crashing, e.g.

candidates = [int(i) for i in translations if str(int(i) if i.isdigit() else -1) == i and int(i) <= n]  # or: skip non-numeric keys
if candidates:
    k = max(candidates)
    text = translations[str(k)].format(**kwargs)
else:
    # fall back to the entry's first (smallest) form or the original text
    smallest = min(translations.values())  # or keep the original text

Whatever the preferred fallback semantics, a malformed/partial translation file shouldn't take down rendering with a bare ValueError.

Verified on current master (20260519.2, pluralize/init.py:168).

Lenguaje dominante
Python
Estrellas
14
Forks
5
Métricas de merge de PR
Sin PR fusionados en 30 d

Preparar el entorno

Este proyecto no incluye contenedor de desarrollo, Dockerfile ni guía de contribución, así que la configuración corre por tu cuenta: empieza por su README y consulta nuestra guía para la primera contribución para los pasos generales.

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.

Issues similares

Más issues de Python

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.