Revision 473ab806 lib/objectutils.py

b/lib/objectutils.py
21 21
"""Module for object related utils."""
22 22

  
23 23

  
24
#: Supported container types for serialization/de-serialization (must be a
25
#: tuple as it's used as a parameter for C{isinstance})
26
_SEQUENCE_TYPES = (list, tuple, set, frozenset)
27

  
28

  
24 29
class AutoSlots(type):
25 30
  """Meta base class for __slots__ definitions.
26 31

  
......
91 96

  
92 97
    """
93 98
    raise NotImplementedError
99

  
100

  
101
def ContainerToDicts(container):
102
  """Convert the elements of a container to standard Python types.
103

  
104
  This method converts a container with elements to standard Python types. If
105
  the input container is of the type C{dict}, only its values are touched.
106
  Those values, as well as all elements of input sequences, must support a
107
  C{ToDict} method returning a serialized version.
108

  
109
  @type container: dict or sequence (see L{_SEQUENCE_TYPES})
110

  
111
  """
112
  if isinstance(container, dict):
113
    ret = dict([(k, v.ToDict()) for k, v in container.items()])
114
  elif isinstance(container, _SEQUENCE_TYPES):
115
    ret = [elem.ToDict() for elem in container]
116
  else:
117
    raise TypeError("Unknown container type '%s'" % type(container))
118

  
119
  return ret
120

  
121

  
122
def ContainerFromDicts(source, c_type, e_type):
123
  """Convert a container from standard python types.
124

  
125
  This method converts a container with standard Python types to objects. If
126
  the container is a dict, we don't touch the keys, only the values.
127

  
128
  @type source: None, dict or sequence (see L{_SEQUENCE_TYPES})
129
  @param source: Input data
130
  @type c_type: type class
131
  @param c_type: Desired type for returned container
132
  @type e_type: element type class
133
  @param e_type: Item type for elements in returned container (must have a
134
    C{FromDict} class method)
135

  
136
  """
137
  if not isinstance(c_type, type):
138
    raise TypeError("Container type '%s' is not a type" % type(c_type))
139

  
140
  if source is None:
141
    source = c_type()
142

  
143
  if c_type is dict:
144
    ret = dict([(k, e_type.FromDict(v)) for k, v in source.items()])
145
  elif c_type in _SEQUENCE_TYPES:
146
    ret = c_type(map(e_type.FromDict, source))
147
  else:
148
    raise TypeError("Unknown container type '%s'" % c_type)
149

  
150
  return ret

Also available in: Unified diff