Skip to content

Commit de3b206

Browse files
committed
feat: Add no_leading_zeroes kwarg to Number
1 parent 39cd264 commit de3b206

File tree

3 files changed

+25
-2
lines changed

3 files changed

+25
-2
lines changed

CHANGELOG.rst

+5
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,8 @@
1+
1.12.0 - July 29, 2024
2+
----------------------
3+
4+
- feat: :class:`.Number` accepts a ``no_leading_zeroes`` keyword argument, to indicate whether to disallow numbers with leading zeroes (not including a single zero, or a single zero before a decimal).
5+
16
1.11.0 - May 27, 2024
27
---------------------
38

agate/data_types/number.py

+7-2
Original file line numberDiff line numberDiff line change
@@ -29,14 +29,16 @@ class Number(DataType):
2929
provided by the specified :code:`locale`.
3030
:param currency_symbols:
3131
A sequence of currency symbols to strip from numbers.
32+
:param no_leading_zeroes:
33+
Whether to disallow leading zeroes.
3234
"""
3335
def __init__(self, locale='en_US', group_symbol=None, decimal_symbol=None,
34-
currency_symbols=DEFAULT_CURRENCY_SYMBOLS, **kwargs):
36+
currency_symbols=DEFAULT_CURRENCY_SYMBOLS, no_leading_zeroes=None, **kwargs):
3537
super().__init__(**kwargs)
3638

3739
self.locale = Locale.parse(locale)
38-
3940
self.currency_symbols = currency_symbols
41+
self.no_leading_zeroes = no_leading_zeroes
4042

4143
# Suppress Babel warning on Python 3.6
4244
# See #665
@@ -91,6 +93,9 @@ def cast(self, d):
9193
d = d.replace(self.group_symbol, '')
9294
d = d.replace(self.decimal_symbol, '.')
9395

96+
if self.no_leading_zeroes and len(d) > 1 and d[0] == '0' and d[1] != '.':
97+
raise CastError('Can not parse value "%s" as Decimal without leading zeroes' % d)
98+
9499
try:
95100
return Decimal(d) * sign
96101
# The Decimal class will return an InvalidOperation exception on most Python implementations,

tests/test_data_types.py

+13
Original file line numberDiff line numberDiff line change
@@ -188,6 +188,19 @@ def test_cast_error(self):
188188
with self.assertRaises(CastError):
189189
self.type.cast('quack')
190190

191+
def test_cast_error_leading_zeroes(self):
192+
data_type = Number(no_leading_zeroes=True)
193+
194+
self.assertEqual(data_type.cast('0'), Decimal('0'))
195+
self.assertEqual(data_type.cast('0.123'), Decimal('0.123'))
196+
self.assertEqual(data_type.cast('123'), Decimal('123'))
197+
198+
with self.assertRaises(CastError):
199+
data_type.cast('01')
200+
201+
with self.assertRaises(CastError):
202+
data_type.cast('00.11')
203+
191204

192205
class TestDate(unittest.TestCase):
193206
def setUp(self):

0 commit comments

Comments
 (0)