summaryrefslogtreecommitdiffstats
path: root/Lib
diff options
context:
space:
mode:
authorSerhiy Storchaka <storchaka@gmail.com>2016-11-14 17:30:36 (GMT)
committerSerhiy Storchaka <storchaka@gmail.com>2016-11-14 17:30:36 (GMT)
commit39d2dfef447fbc957d75f2d3806a3a80c814a2d0 (patch)
treea0a4ad03a2c4e1bb0fe2cb07f3301e702561d6a3 /Lib
parent38c8b7d2922c20010930eedacdccf61fb2246761 (diff)
parent5ae6c776a8fc96df95597a9b24109c7448131276 (diff)
downloadcpython-39d2dfef447fbc957d75f2d3806a3a80c814a2d0.zip
cpython-39d2dfef447fbc957d75f2d3806a3a80c814a2d0.tar.gz
cpython-39d2dfef447fbc957d75f2d3806a3a80c814a2d0.tar.bz2
Issue #28563: Make plural form selection more lenient and accepting
non-integer numbers. Django tests depend on this.
Diffstat (limited to 'Lib')
-rw-r--r--Lib/gettext.py12
-rw-r--r--Lib/test/test_gettext.py16
2 files changed, 20 insertions, 8 deletions
diff --git a/Lib/gettext.py b/Lib/gettext.py
index 7032efa..57d2c74 100644
--- a/Lib/gettext.py
+++ b/Lib/gettext.py
@@ -158,6 +158,14 @@ def _parse(tokens, priority=-1):
return result, nexttok
+def _as_int(n):
+ try:
+ i = round(n)
+ except TypeError:
+ raise TypeError('Plural value must be an integer, got %s' %
+ (n.__class__.__name__,)) from None
+ return n
+
def c2py(plural):
"""Gets a C expression as used in PO files for plural forms and returns a
Python function that implements an equivalent expression.
@@ -181,11 +189,11 @@ def c2py(plural):
elif c == ')':
depth -= 1
- ns = {}
+ ns = {'_as_int': _as_int}
exec('''if True:
def func(n):
if not isinstance(n, int):
- raise ValueError('Plural value must be an integer.')
+ n = _as_int(n)
return int(%s)
''' % result, ns)
return ns['func']
diff --git a/Lib/test/test_gettext.py b/Lib/test/test_gettext.py
index 55bff4f..a852443 100644
--- a/Lib/test/test_gettext.py
+++ b/Lib/test/test_gettext.py
@@ -440,12 +440,16 @@ class PluralFormsTestCase(GettextBaseTest):
self.assertRaises(ZeroDivisionError, f, 0)
def test_plural_number(self):
- f = gettext.c2py('1')
- self.assertEqual(f(1), 1)
- self.assertRaises(ValueError, f, 1.0)
- self.assertRaises(ValueError, f, '1')
- self.assertRaises(ValueError, f, [])
- self.assertRaises(ValueError, f, object())
+ f = gettext.c2py('n != 1')
+ self.assertEqual(f(1), 0)
+ self.assertEqual(f(2), 1)
+ self.assertEqual(f(1.0), 0)
+ self.assertEqual(f(2.0), 1)
+ self.assertEqual(f(1.1), 1)
+ self.assertRaises(TypeError, f, '2')
+ self.assertRaises(TypeError, f, b'2')
+ self.assertRaises(TypeError, f, [])
+ self.assertRaises(TypeError, f, object())
class GNUTranslationParsingTest(GettextBaseTest):