44955a574791a9fd04f6d717b2daae45a6960cdc
[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     'path': 'string',
18     'point': 'int',
19     }
20 """Types that may be treated as other types.
21
22 These types may have optional special handling on the UI end
23 (e.g. file picker dialogs), but it is not required.
24 """
25
26 RAW_TYPES = [
27     'curve',
28     'dict',
29     'driver',
30     'function',
31     'object',
32     'playlist',
33     ]
34 """List of types that should not be converted.
35 """
36
37 def to_string(value, type, count=1):
38     """Convert `value` from `type` to a unicode string.
39     """
40     type = ANALOGS.get(type, type)
41     if type in RAW_TYPES:
42         return value
43     if count != 1:
44         values = [to_string(v, type) for v in value]
45         return '[%s]' % ', '.join(values)
46     return unicode(value)
47
48 def from_string(value, type, count=1):
49     """Convert `value` from a string to `type`.
50     """
51     type = ANALOGS.get(type, type)
52     if type in RAW_TYPES:
53         return value
54     fn = globals()['_string_to_%s' % type]
55     if count != 1:
56         assert value.startswith('[') and value.endswith(']'), value
57         value = value[1:-1]  # strip off brackets
58         values = [from_string(v, type) for v in value.split(', ')]
59         assert count == -1 or len(values) == count, (
60             'array with %d != %d values: %s'
61             % (len(values), count, values))
62         return values
63     return fn(value)
64
65 def _string_to_string(value):
66     return unicode(value)
67
68 def _string_to_bool(value):
69     return value == 'True'
70
71 def _string_to_int(value):
72     return int(value)
73
74 def _string_to_float(value):
75     return float(value)