1 # Copyright (C) 2010-2012 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 under the
6 # terms of the GNU Lesser General Public License as published by the Free
7 # Software Foundation, either version 3 of the License, or (at your option) any
10 # Hooke is distributed in the hope that it will be useful, but WITHOUT ANY
11 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
12 # A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
15 # You should have received a copy of the GNU Lesser General Public License
16 # along with Hooke. If not, see <http://www.gnu.org/licenses/>.
18 """Type conversion utilities.
27 """Types that may be treated as other types.
29 These types may have optional special handling on the UI end
30 (e.g. file picker dialogs), but it is not required.
41 """List of types that should not be converted.
44 def to_string(value, type, count=1):
45 """Convert `value` from `type` to a unicode string.
47 type = ANALOGS.get(type, type)
51 values = [to_string(v, type) for v in value]
52 return '[%s]' % ', '.join(values)
55 def from_string(value, type, count=1):
56 """Convert `value` from a string to `type`.
60 >>> from_string('abcde', type='string')
62 >>> from_string('None', type='string')
63 >>> from_string(None, type='string')
64 >>> from_string('true', type='bool')
66 >>> from_string('false', type='bool')
68 >>> from_string(None, type='bool')
70 >>> from_string('123', type='int')
72 >>> from_string('123', type='float')
75 type = ANALOGS.get(type, type)
78 fn = globals()['_string_to_%s' % type]
80 assert value.startswith('[') and value.endswith(']'), value
81 value = value[1:-1] # strip off brackets
82 values = [from_string(v, type) for v in value.split(', ')]
83 assert count == -1 or len(values) == count, (
84 'array with %d != %d values: %s'
85 % (len(values), count, values))
89 def _string_to_string(value):
90 if value in [None, 'None'] or len(value) == 0:
94 def _string_to_bool(value):
95 return hasattr(value, 'lower') and value.lower() == 'true'
97 def _string_to_int(value):
98 if value in [None, 'None']:
102 def _string_to_float(value):
103 if value in [None, 'None']: