Debian Codegraph @

contrib/pyqt-reduce-handler.py

raw
1 """
2 This example demonstrates how to add a custom handler to serialize
3 Qt's QPointF class jsonpickle using qtpy.
4
5 """
6
7 import sys
8 import unittest
9
10 from qtpy import QtCore
11
12 import jsonpickle
13 from jsonpickle import handlers
14
15 text_type = eval('unicode') if str is bytes else str
16
17
18 class QReduceHandler(handlers.BaseHandler):
19 def flatten(self, obj, data):
20 pickler = self.context
21 if not pickler.unpicklable:
22 return text_type(obj)
23 flatten = pickler.flatten
24 data['__reduce__'] = [flatten(i, reset=False) for i in obj.__reduce__()[1]]
25 return data
26
27 def restore(self, data):
28 unpickler = self.context
29 restore = unpickler.restore
30 reduced = [restore(i, reset=False) for i in data['__reduce__']]
31 modulename = reduced[0]
32 classname = reduced[1]
33 args = reduced[2]
34 __import__(modulename)
35 module = sys.modules[modulename]
36 factory = getattr(module, classname)
37
38 return factory(*args)
39
40
41 handlers.register(QtCore.QPointF, QReduceHandler)
42
43
44 class QtTestCase(unittest.TestCase):
45 def test_QPointF_roundtrip(self):
46 expect = QtCore.QPointF(1.0, 2.0)
47 json = jsonpickle.encode(expect)
48 actual = jsonpickle.decode(json)
49 self.assertEqual(expect, actual)