DESCRIPTION.rst 2.2 KB

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