# HG changeset patch # User Jeff Hammel # Date 1341420877 25200 # Node ID 56db0b2b90af326959f72bd49673d8bdb6b40cfe # Parent d1911d9b5b198c66935ae4bd7d25a677a389ec27 fix casting diff -r d1911d9b5b19 -r 56db0b2b90af configuration/configuration.py --- a/configuration/configuration.py Thu Jun 28 14:54:29 2012 -0700 +++ b/configuration/configuration.py Wed Jul 04 09:54:37 2012 -0700 @@ -313,11 +313,19 @@ _type = self.option_dict[key].get('type') if _type is None and 'default' in self.option_dict[key]: _type = type(self.option_dict[key]['default']) - if _type is not None and not isinstance(value, _type): + if _type is not None: + tocast = True try: - config[key] = _type(value) - except BaseException, e: - raise TypeCastException("Could not coerce %s, %s, to type %s: %s" % (key, value, _type.__name__, e)) + if isinstance(value, _type): + tocast = False + except TypeError: + # type is a type-casting function, not a proper type + pass + if tocast: + try: + config[key] = _type(value) + except BaseException, e: + raise TypeCastException("Could not coerce %s, %s, to type %s: %s" % (key, value, _type.__name__, e)) return config diff -r d1911d9b5b19 -r 56db0b2b90af setup.py --- a/setup.py Thu Jun 28 14:54:29 2012 -0700 +++ b/setup.py Wed Jul 04 09:54:37 2012 -0700 @@ -4,7 +4,7 @@ import os -version = "0.2.2" +version = "0.3" dependencies = ['PyYAML'] try: diff -r d1911d9b5b19 -r 56db0b2b90af tests/unit.py --- a/tests/unit.py Thu Jun 28 14:54:29 2012 -0700 +++ b/tests/unit.py Wed Jul 04 09:54:37 2012 -0700 @@ -5,6 +5,7 @@ """ import configuration +import datetime import os import sys import tempfile @@ -184,5 +185,23 @@ self.assertEqual(example.config['preferences'], default_prefs) os.remove(tf) + def test_typecast(self): + """casting example""" + + def todate(string): + return datetime.datetime.strptime(string, "%Y%m%d") + + # make an example class + class TypecastExample(configuration.Configuration): + options = {'datestring': {'type': todate}} + example = TypecastExample() + + # parse a date string + example({'datestring': "20120704"}) + + # ensure it works correctly + expected = datetime.datetime(2012, 7, 4, 0, 0) + self.assertEqual(example.config['datestring'], expected) + if __name__ == '__main__': unittest.main()