METADATA 2.5 KB

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