Broke type conversion out into hooke.util.convert and expanded its use.
[hooke.git] / hooke / util / convert.py
1 # Copyright
2
3 """Type conversion utilities.
4 """
5
6 CONVERT_FROM_STRING = {
7     'string': lambda x: x,
8     'bool': lambda x: x == 'True',
9     'int': lambda x: int(x),
10     'float': lambda x: float(x),
11     }
12 """Functions converting strings to values, keyed by type.
13 """
14
15 ANALOGS = {
16     'file': 'string',
17     'point': 'int',
18     }
19 """Types that may be treated as other types.
20
21 These types may have optional special handling on the UI end
22 (e.g. file picker dialogs), but it is not required.
23 """
24
25 RAW_TYPES = [
26     'curve',
27     'dict',
28     'driver',
29     'function',
30     'object',
31     'playlist',
32     ]
33 """List of types that should not be converted.
34 """
35
36 def to_string(value, type):
37     """Convert `value` from `type` to a unicode string.
38     """
39     type = ANALOGS.get(type, type)
40     if type in RAW_TYPES:
41         return value
42     return unicode(value)
43
44 def from_string(value, type):
45     """Convert `value` from a string to `type`.
46     """
47     type = ANALOGS.get(type, type)
48     if type in RAW_TYPES:
49         return value
50     fn = globals()['_string_to_%s' % type]
51     return fn(value)
52
53 def _string_to_string(value):
54     return unicode(value)
55
56 def _string_to_bool(value):
57     return value == 'True'
58
59 def _string_to_int(value):
60     return int(value)
61
62 def _string_to_float(value):
63     return float(value)