Skip to content

Commit abcb5af

Browse files
committed
-
1 parent 5f680dc commit abcb5af

File tree

2 files changed

+33
-0
lines changed

2 files changed

+33
-0
lines changed

source_py3/python_toolbox/misc_tools/misc_tools.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -341,6 +341,18 @@ def pocket(*args):
341341
_decimal_number_pattern = \
342342
re.compile('''^-?(?:(?:[0-9]+(?:.[0-9]*)?)|(?:.[0-9]+))$''')
343343
def decimal_number_from_string(string):
344+
'''
345+
Turn a string like '7' or '-32.55' into the corresponding number.
346+
347+
Ensures that it was given a number. (This might be more secure than using
348+
something like `int` directly.)
349+
350+
Uses `int` for ints and `float` for floats.
351+
'''
352+
if isinstance(string, bytes):
353+
string = string.decode()
354+
if not isinstance(string, str):
355+
raise Exception("%s isn't a decimal number." % string)
344356
if not _decimal_number_pattern.match(string):
345357
raise Exception("%s isn't a decimal number." % string)
346358
return float(string) if '.' in string else int(string)
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
# Copyright 2009-2014 Ram Rachum.
2+
# This program is distributed under the MIT license.
3+
4+
'''Testing module for `find_clear_place_on_circle`.'''
5+
6+
import nose.tools
7+
8+
from python_toolbox import cute_testing
9+
10+
from python_toolbox.misc_tools import decimal_number_from_string
11+
12+
13+
def test():
14+
assert decimal_number_from_string('7') == 7
15+
assert type(decimal_number_from_string('7')) == int
16+
assert decimal_number_from_string('-12.34') == -12.34
17+
assert type(decimal_number_from_string('-12.34')) == float
18+
with cute_testing.RaiseAssertor():
19+
decimal_number_from_string(31412)
20+
with cute_testing.RaiseAssertor():
21+
decimal_number_from_string('JJfa')

0 commit comments

Comments
 (0)