1 # Copyright (C) 2010 W. Trevor King <wking@drexel.edu>
3 # This file is part of Hooke.
5 # Hooke is free software: you can redistribute it and/or modify it
6 # under the terms of the GNU Lesser General Public License as
7 # published by the Free Software Foundation, either version 3 of the
8 # License, or (at your option) any later version.
10 # Hooke is distributed in the hope that it will be useful, but WITHOUT
11 # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
12 # or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General
13 # Public License for more details.
15 # You should have received a copy of the GNU Lesser General Public
16 # License along with Hooke. If not, see
17 # <http://www.gnu.org/licenses/>.
19 """Type conversion utilities.
28 """Types that may be treated as other types.
30 These types may have optional special handling on the UI end
31 (e.g. file picker dialogs), but it is not required.
42 """List of types that should not be converted.
45 def to_string(value, type, count=1):
46 """Convert `value` from `type` to a unicode string.
48 type = ANALOGS.get(type, type)
52 values = [to_string(v, type) for v in value]
53 return '[%s]' % ', '.join(values)
56 def from_string(value, type, count=1):
57 """Convert `value` from a string to `type`.
61 >>> from_string('abcde', type='string')
63 >>> from_string('None', type='string')
64 >>> from_string(None, type='string')
65 >>> from_string('true', type='bool')
67 >>> from_string('false', type='bool')
69 >>> from_string(None, type='bool')
71 >>> from_string('123', type='int')
73 >>> from_string('123', type='float')
76 type = ANALOGS.get(type, type)
79 fn = globals()['_string_to_%s' % type]
81 assert value.startswith('[') and value.endswith(']'), value
82 value = value[1:-1] # strip off brackets
83 values = [from_string(v, type) for v in value.split(', ')]
84 assert count == -1 or len(values) == count, (
85 'array with %d != %d values: %s'
86 % (len(values), count, values))
90 def _string_to_string(value):
91 if value in [None, 'None'] or len(value) == 0:
95 def _string_to_bool(value):
96 return hasattr(value, 'lower') and value.lower() == 'true'
98 def _string_to_int(value):
99 if value in [None, 'None']:
103 def _string_to_float(value):
104 if value in [None, 'None']: