Broke type conversion out into hooke.util.convert and expanded its use.
[hooke.git] / hooke / config.py
index c1776c8eee6367056490269c1e54a0dc0d6b8fe7..1c5c4874d53d4191078b599f8fb5aa6e91e8e380 100644 (file)
@@ -26,6 +26,7 @@ import textwrap
 import unittest
 
 from .compat.odict import odict as OrderedDict
+from .util.convert import to_string, from_string
 
 
 DEFAULT_PATHS = [
@@ -39,24 +40,6 @@ specific user files, so the user can override the sysadmin who
 in turn overrides the developer defaults.
 """
 
-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.
-"""
-
-CONVERT_TO_STRING = {
-    'string': lambda x: x,
-    'bool': lambda x: str(x),
-    'int': lambda x: str(x),
-    'float': lambda x: str(x),
-    }
-"""Functions converting values to strings, keyed by type.
-"""
-
 class Setting (object):
     """An entry (section or option) in HookeConfigParser.
     """
@@ -64,7 +47,7 @@ class Setting (object):
                  help=None, wrap=True):
         self.section = section
         self.option = option
-        self.value = CONVERT_TO_STRING[type](value)
+        self.value = to_string(value=value, type=type)
         self.type = type
         self.help = help
         self.wrap = wrap
@@ -316,13 +299,13 @@ class HookeConfigParser (configparser.RawConfigParser):
         for i,kv in enumerate(items):
             key,value = kv
             setting = self._default_settings_dict[(section, key)]
-            items[i] = (key, CONVERT_FROM_STRING[setting.type](value))
+            items[i] = (key, from_string(value=value, type=setting.type))
         return items
 
     def set(self, section, option, value):
         """Set an option."""
         setting = self._default_settings_dict[(section, option)]
-        value = CONVERT_TO_STRING[setting.type](value)
+        value = to_string(value=value, type=setting.type)
         # Can't use super() because RawConfigParser is a classic class
         #return super(HookeConfigParser, self).set(section, option, value)
         configparser.RawConfigParser.set(self, section, option, value)