File tree Expand file tree Collapse file tree 2 files changed +33
-0
lines changed
python_toolbox/misc_tools
test_python_toolbox/test_misc_tools Expand file tree Collapse file tree 2 files changed +33
-0
lines changed Original file line number Diff line number Diff line change @@ -341,6 +341,18 @@ def pocket(*args):
341341_decimal_number_pattern = \
342342 re .compile ('''^-?(?:(?:[0-9]+(?:.[0-9]*)?)|(?:.[0-9]+))$''' )
343343def 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 )
Original file line number Diff line number Diff line change 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' )
You can’t perform that action at this time.
0 commit comments