README.rst
1visitor
2=======
3
4A tiny library to facilitate `visitor
5<https://en.wikipedia.org/wiki/Visitor_pattern>`_ implementation in Python
6(which are slightly peculiar due to dynamic typing). In fact, it is so small,
7you may just be better off copy & pasting the source straight into your
8project...
9
10
11Example use
12-----------
13
14A simple JSON-encoder:
15
16.. code-block:: python
17
18 from visitor import Visitor
19
20
21 class JSONEncoder(Visitor):
22 def __init__(self):
23 self.indent = 0
24
25 def escape_str(self, s):
26 # note: this is not a good escape function, do not use this in
27 # production!
28 s = s.replace('\\', '\\\\')
29 s = s.replace('"', '\\"')
30 return '"' + s + '"'
31
32 def visit_list(self, node):
33 self.indent += 1
34 s = '[\n' + ' ' * self.indent
35 s += (',\n' + ' ' * self.indent).join(self.visit(item)
36 for item in node)
37 self.indent -= 1
38 s += '\n' + ' ' * self.indent + ']'
39 return s
40
41 def visit_str(self, node):
42 return self.escape_str(node)
43
44 def visit_int(self, node):
45 return str(node)
46
47 def visit_bool(self, node):
48 return 'true' if node else 'false'
49
50 def visit_dict(self, node):
51 self.indent += 1
52 s = '{\n' + ' ' * self.indent
53 s += (',\n' + ' ' * self.indent).join(
54 '{}: {}'.format(self.escape_str(key), self.visit(value))
55 for key, value in sorted(node.items())
56 )
57 self.indent -= 1
58 s += '\n' + ' ' * self.indent + '}'
59 return s
60
61
62 data = [
63 'List', 'of', 42, 'items', True, {
64 'sub1': 'some string',
65 'sub2': {
66 'sub2sub1': False,
67 'sub2sub2': 123,
68 }
69 }
70 ]
71
72 print(JSONEncoder().visit(data))
73
74
75
76Output::
77
78 [
79 "List",
80 "of",
81 42,
82 "items",
83 true,
84 {
85 "sub1": "some string",
86 "sub2": {
87 "sub2sub1": false,
88 "sub2sub2": 123
89 }
90 }
91 ]
92