Skip to content

Commit 5ca92ab

Browse files
Issue #28563: Make plural form selection more lenient and accepting
non-integer numbers. Django tests depend on this.
2 parents 84293af + 60ac989 commit 5ca92ab

File tree

2 files changed

+20
-8
lines changed

2 files changed

+20
-8
lines changed

Lib/gettext.py

+10-2
Original file line numberDiff line numberDiff line change
@@ -158,6 +158,14 @@ def _parse(tokens, priority=-1):
158158

159159
return result, nexttok
160160

161+
def _as_int(n):
162+
try:
163+
i = round(n)
164+
except TypeError:
165+
raise TypeError('Plural value must be an integer, got %s' %
166+
(n.__class__.__name__,)) from None
167+
return n
168+
161169
def c2py(plural):
162170
"""Gets a C expression as used in PO files for plural forms and returns a
163171
Python function that implements an equivalent expression.
@@ -181,11 +189,11 @@ def c2py(plural):
181189
elif c == ')':
182190
depth -= 1
183191

184-
ns = {}
192+
ns = {'_as_int': _as_int}
185193
exec('''if True:
186194
def func(n):
187195
if not isinstance(n, int):
188-
raise ValueError('Plural value must be an integer.')
196+
n = _as_int(n)
189197
return int(%s)
190198
''' % result, ns)
191199
return ns['func']

Lib/test/test_gettext.py

+10-6
Original file line numberDiff line numberDiff line change
@@ -371,12 +371,16 @@ def test_division(self):
371371
self.assertRaises(ZeroDivisionError, f, 0)
372372

373373
def test_plural_number(self):
374-
f = gettext.c2py('1')
375-
self.assertEqual(f(1), 1)
376-
self.assertRaises(ValueError, f, 1.0)
377-
self.assertRaises(ValueError, f, '1')
378-
self.assertRaises(ValueError, f, [])
379-
self.assertRaises(ValueError, f, object())
374+
f = gettext.c2py('n != 1')
375+
self.assertEqual(f(1), 0)
376+
self.assertEqual(f(2), 1)
377+
self.assertEqual(f(1.0), 0)
378+
self.assertEqual(f(2.0), 1)
379+
self.assertEqual(f(1.1), 1)
380+
self.assertRaises(TypeError, f, '2')
381+
self.assertRaises(TypeError, f, b'2')
382+
self.assertRaises(TypeError, f, [])
383+
self.assertRaises(TypeError, f, object())
380384

381385

382386
class GNUTranslationParsingTest(GettextBaseTest):

0 commit comments

Comments
 (0)