MCPcopy Create free account
hub / github.com/ActiveState/code / serialize

Function serialize

recipes/Python/576943_Serialize_Deserialize/recipe-576943.py:36–70  ·  view source on GitHub ↗

Serializes some of the fundamental data types in Python. Serialization function designed to not possess the same security flaws as the cPickle and pickle modules. At present, the following data types are supported: set, frozenset, list, tuple, dict, int, long, bool, comple

(root)

Source from the content-addressed store, hash-verified

34 (name,func) for (_,func,name) in supporteddict.itervalues())
35
36def serialize(root):
37 """
38 Serializes some of the fundamental data types in Python.
39
40 Serialization function designed to not possess the same security flaws
41 as the cPickle and pickle modules. At present, the following data types
42 are supported:
43
44 set, frozenset, list, tuple, dict, int, long, bool, complex, float,
45 None, str, unicode
46
47 To convert the serialized object back into a Python object, pass the text
48 through the deserialize function.
49
50 >>> deserialize(serialize((1, 2, 3+4j, ['this', 'is', 'a', 'list'])))
51 (1, 2, (3+4j), ['this', 'is', 'a', 'list'])
52 """
53 stack = collections.deque([ (0,(root,)) ])
54 lintree, eid = collections.deque(), 0
55 while stack:
56 uid, focus = stack.pop()
57 for element in focus:
58 eid += 1
59 if hasattr(focus, "keys"): # Support for dictionaries
60 lintree.appendleft((eid, uid, 'C', "tuple"))
61 stack.append((eid, (element, focus[element])))
62 elif hasattr(element, "__iter__"):
63 lintree.appendleft((eid, uid, 'C', itertable[type(element)]))
64 stack.append((eid, element))
65 else:
66 elementtype = type(element)
67 serializefunc, _, label = supporteddict[elementtype]
68 lintree.appendleft((eid, uid, label, serializefunc(element)))
69
70 return '\n'.join(str(element) for entry in lintree for element in entry)
71
72def deserialize(text):
73 """

Callers 1

testFunction · 0.70

Calls 5

strFunction · 0.85
popMethod · 0.45
appendleftMethod · 0.45
appendMethod · 0.45
joinMethod · 0.45

Tested by

no test coverage detected