@@ -65,8 +65,31 @@ def __init__(self, column, row, value, message):
6565 self .message = message
6666
6767
68+ def convert_boolean (string_value ):
69+ """Converts a string to a boolean (see CONVERTERS).
70+ There is a converter function for each column type.
71+
72+ Boolean strings are independent of case. Values interpreted as True
73+ are: "yes", "true", "on", "1". values interpreted as False are
74+ "no", "false", "off", "0". Any other value will result in a ValueError.
75+
76+ :param string_value: The string to convert
77+
78+ :raises: ValueError if the string cannot be represented by a boolean
79+ """
80+
81+ lean_string_value = string_value .strip ().lower ()
82+ if lean_string_value in ['yes' , 'true' , 'on' , '1' ]:
83+ return True
84+ elif lean_string_value in ['no' , 'false' , 'off' , '0' ]:
85+ return False
86+
87+ # Not recognised boolean if we get here
88+ raise ValueError ('Unrecognised boolean ({})' .format (lean_string_value ))
89+
90+
6891def convert_int (string_value ):
69- """Converts a string to integer (see CONVERTERS).
92+ """Converts a string to to an integer (see CONVERTERS).
7093 There is a converter function for each column type.
7194
7295 :param string_value: The string to convert
@@ -77,7 +100,7 @@ def convert_int(string_value):
77100
78101
79102def convert_float (string_value ):
80- """Converts string to float (see CONVERTERS).
103+ """Converts string to a float (see CONVERTERS).
81104 There is a converter function for each column type.
82105
83106 :param string_value: The string to convert
@@ -98,7 +121,8 @@ def convert_string(string_value):
98121
99122# A map of column type names (case-insensitive) to string conversion function.
100123# If a column is 'name:INT' then we call 'convert_int()' for the column values.
101- CONVERTERS = {'int' : convert_int ,
124+ CONVERTERS = {'boolean' : convert_boolean ,
125+ 'int' : convert_int ,
102126 'float' : convert_float ,
103127 'string' : convert_string }
104128
@@ -114,7 +138,8 @@ class TypedColumnReader(object):
114138 where, if the column header defines a type, the value is converted to that
115139 type.
116140
117- There is built-in support for ``int``, ``float`` and ``string`` data types.
141+ There is built-in support for ``boolean``,
142+ ``int``, ``float`` and ``string`` data types.
118143
119144 As an example, the following is a comma-separated header for a file with
120145 columns ``names`` "smiles", "comment", "hac" and "ratio" where
@@ -128,7 +153,6 @@ class TypedColumnReader(object):
128153 * If a column value is empty/blank the corresponding dictionary
129154 value is ``None``
130155
131-
132156 """
133157
134158 def __init__ (self , csv_file ,
0 commit comments