Flesh out command line help messages.
[hooke.git] / hooke / util / convert.py
index 44955a574791a9fd04f6d717b2daae45a6960cdc..70ae5741c5240939be39f01bdd123942805aec07 100644 (file)
@@ -1,16 +1,24 @@
-# Copyright
+# Copyright (C) 2010 W. Trevor King <wking@drexel.edu>
+#
+# This file is part of Hooke.
+#
+# Hooke is free software: you can redistribute it and/or modify it
+# under the terms of the GNU Lesser General Public License as
+# published by the Free Software Foundation, either version 3 of the
+# License, or (at your option) any later version.
+#
+# Hooke is distributed in the hope that it will be useful, but WITHOUT
+# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
+# or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General
+# Public License for more details.
+#
+# You should have received a copy of the GNU Lesser General Public
+# License along with Hooke.  If not, see
+# <http://www.gnu.org/licenses/>.
 
 """Type conversion utilities.
 """
 
-CONVERT_FROM_STRING = {
-    'string': lambda x: x,
-    'bool': lambda x: x == 'True',
-    'int': lambda x: int(x),
-    'float': lambda x: float(x),
-    }
-"""Functions converting strings to values, keyed by type.
-"""
 
 ANALOGS = {
     'file': 'string',
@@ -47,6 +55,23 @@ def to_string(value, type, count=1):
 
 def from_string(value, type, count=1):
     """Convert `value` from a string to `type`.
+
+    Examples
+    --------
+    >>> from_string('abcde', type='string')
+    u'abcde'
+    >>> from_string('None', type='string')
+    >>> from_string(None, type='string')
+    >>> from_string('true', type='bool')
+    True
+    >>> from_string('false', type='bool')
+    False
+    >>> from_string(None, type='bool')
+    False
+    >>> from_string('123', type='int')
+    123
+    >>> from_string('123', type='float')
+    123.0
     """
     type = ANALOGS.get(type, type)
     if type in RAW_TYPES:
@@ -63,13 +88,19 @@ def from_string(value, type, count=1):
     return fn(value)
 
 def _string_to_string(value):
+    if value in [None, 'None'] or len(value) == 0:
+        return None
     return unicode(value)
 
 def _string_to_bool(value):
-    return value == 'True'
+    return hasattr(value, 'lower') and value.lower() == 'true'
 
 def _string_to_int(value):
+    if value in [None, 'None']:
+        return None
     return int(value)
 
 def _string_to_float(value):
+    if value in [None, 'None']:
+        return None
     return float(value)