-
Notifications
You must be signed in to change notification settings - Fork 0
/
__init__.py
110 lines (96 loc) · 2.99 KB
/
__init__.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
# coding: utf-8
"""
stringtopy is a small library to convert strings to a specified type (e.g.
int, float or bool), allowing more human friendly input similar to
configparser.
:copyright: (c) 2016 James Tocknell
:license: 3-clause BSD
"""
from fractions import Fraction
# versioneer stuff
from ._version import get_versions
__version__ = get_versions()['version']
del get_versions
BOOLEAN_TRUE = {'1', 'yes', 'true', 'on', }
BOOLEAN_FALSE = {'0', 'no', 'false', 'off', }
def str_to_float_converter(use_none_on_fail=False):
"""
Returns a human friendly float converter, can use use_none_on_fail to
return None if value cannot be converted.
"""
def str_to_float_func(s):
"""
Convert a string to a float
"""
try:
return float(Fraction(s))
except ValueError:
if use_none_on_fail:
return None
raise
return str_to_float_func
def str_to_int_converter(use_none_on_fail=False):
"""
Returns a human friendly int converter, can use use_none_on_fail to return
None if value cannot be converted.
"""
def str_to_int_func(s):
"""
Convert a string to a int
"""
try:
frac = Fraction(s)
if frac.denominator == 1:
return int(frac)
raise ValueError("{} is not an integer".format(frac))
except ValueError:
if use_none_on_fail:
return None
raise
return str_to_int_func
def str_to_bool_converter(
boolean_true=None, boolean_false=None, additional=True
):
"""
Returns a human friendly bool converter.
Parameters
----------
additional : bool
If True, include the stringtopy defaults for True and False to the list
of items considered True and False.
boolean_true : iterable of str
List of str to consider as True
boolean_false : iterable of str
List of str to consider as False
"""
if boolean_true is None:
boolean_true = set()
else:
boolean_true = set(boolean_true)
if boolean_false is None:
boolean_false = set()
else:
boolean_false = set(boolean_false)
if additional:
boolean_true.update(BOOLEAN_TRUE)
boolean_false.update(BOOLEAN_FALSE)
if not boolean_true.isdisjoint(boolean_false):
raise ValueError(
"{} are both True and False".format(boolean_true & boolean_false)
)
def str_to_bool_func(s):
"""
Convert a string to a bool, based on settings
"""
s = s.strip().lower()
if s in boolean_true:
return True
if s in boolean_false:
return False
raise ValueError("{} is neither True nor False.".format(s))
return str_to_bool_func
# versions using defaults so that users can import the actual functions, rather
# than creating their own
str_to_float = str_to_float_converter()
str_to_int = str_to_int_converter()
str_to_bool = str_to_bool_converter()