3 """Type conversion utilities.
12 """Types that may be treated as other types.
14 These types may have optional special handling on the UI end
15 (e.g. file picker dialogs), but it is not required.
26 """List of types that should not be converted.
29 def to_string(value, type, count=1):
30 """Convert `value` from `type` to a unicode string.
32 type = ANALOGS.get(type, type)
36 values = [to_string(v, type) for v in value]
37 return '[%s]' % ', '.join(values)
40 def from_string(value, type, count=1):
41 """Convert `value` from a string to `type`.
45 >>> from_string('abcde', type='string')
47 >>> from_string('None', type='string')
48 >>> from_string(None, type='string')
49 >>> from_string('true', type='bool')
51 >>> from_string('false', type='bool')
53 >>> from_string(None, type='bool')
55 >>> from_string('123', type='int')
57 >>> from_string('123', type='float')
60 type = ANALOGS.get(type, type)
63 fn = globals()['_string_to_%s' % type]
65 assert value.startswith('[') and value.endswith(']'), value
66 value = value[1:-1] # strip off brackets
67 values = [from_string(v, type) for v in value.split(', ')]
68 assert count == -1 or len(values) == count, (
69 'array with %d != %d values: %s'
70 % (len(values), count, values))
74 def _string_to_string(value):
75 if value in [None, 'None'] or len(value) == 0:
79 def _string_to_bool(value):
80 return hasattr(value, 'lower') and value.lower() == 'true'
82 def _string_to_int(value):
83 if value in [None, 'None']:
87 def _string_to_float(value):
88 if value in [None, 'None']: