Skip to content

Commit 5ae6c77

Browse files
committedNov 14, 2016
Issue #28563: Make plural form selection more lenient and accepting
non-integer numbers. Django tests depend on this.
2 parents c9e08d8 + 5ca92ab commit 5ae6c77

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
@@ -441,12 +441,16 @@ def test_division(self):
441441
self.assertRaises(ZeroDivisionError, f, 0)
442442

443443
def test_plural_number(self):
444-
f = gettext.c2py('1')
445-
self.assertEqual(f(1), 1)
446-
self.assertRaises(ValueError, f, 1.0)
447-
self.assertRaises(ValueError, f, '1')
448-
self.assertRaises(ValueError, f, [])
449-
self.assertRaises(ValueError, f, object())
444+
f = gettext.c2py('n != 1')
445+
self.assertEqual(f(1), 0)
446+
self.assertEqual(f(2), 1)
447+
self.assertEqual(f(1.0), 0)
448+
self.assertEqual(f(2.0), 1)
449+
self.assertEqual(f(1.1), 1)
450+
self.assertRaises(TypeError, f, '2')
451+
self.assertRaises(TypeError, f, b'2')
452+
self.assertRaises(TypeError, f, [])
453+
self.assertRaises(TypeError, f, object())
450454

451455

452456
class GNUTranslationParsingTest(GettextBaseTest):

0 commit comments

Comments
 (0)
Please sign in to comment.