Skip to content

Commit

Permalink
Make int_convert stateless (#119)
Browse files Browse the repository at this point in the history
* Add test for stateful int_convert

* Make int_convert stateless

If there is a "d"-type parameter in parser format,
converter is created with unspecified base.
After parsing first number, the base of this number
is stored in the class
and the same base is assumed
for all subsequent numbers parsed by this Parser instance.
  • Loading branch information
maxxk committed Sep 10, 2020
1 parent 55467d2 commit 3cf6e15
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 7 deletions.
15 changes: 8 additions & 7 deletions parse.py
Original file line number Diff line number Diff line change
Expand Up @@ -536,24 +536,25 @@ def __call__(self, string, match):
sign = 1
number_start = 0

base = self.base
# If base wasn't specified, detect it automatically
if self.base is None:
if base is None:

# Assume decimal number, unless different base is detected
self.base = 10
base = 10

# For number formats starting with 0b, 0o, 0x, use corresponding base ...
if string[number_start] == '0' and len(string) - number_start > 2:
if string[number_start + 1] in 'bB':
self.base = 2
base = 2
elif string[number_start + 1] in 'oO':
self.base = 8
base = 8
elif string[number_start + 1] in 'xX':
self.base = 16
base = 16

chars = int_convert.CHARS[: self.base]
chars = int_convert.CHARS[: base]
string = re.sub('[^%s]' % chars, '', string.lower())
return sign * int(string, self.base)
return sign * int(string, base)


class convert_first:
Expand Down
4 changes: 4 additions & 0 deletions test_parse.py
Original file line number Diff line number Diff line change
Expand Up @@ -1059,6 +1059,10 @@ def test_width_empty_input(self):
res = parse.parse('{:2d}', '')
self.assertIsNone(res)

def test_int_convert_stateless_base(self):
parser = parse.Parser("{:d}")
self.assertEqual(parser.parse("1234")[0], 1234)
self.assertEqual(parser.parse("0b1011")[0], 0b1011)

if __name__ == '__main__':
unittest.main()
Expand Down

0 comments on commit 3cf6e15

Please sign in to comment.