You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

51 lines
1.4 KiB

  1. from __future__ import unicode_literals
  2. import sys
  3. import ast
  4. import six
  5. class Printer(ast.NodeVisitor):
  6. def __init__(self, file=sys.stdout, indent=" "):
  7. self.indentation = 0
  8. self.indent_with = indent
  9. self.f = file
  10. # overridden to make the API obvious
  11. def visit(self, node):
  12. super(Printer, self).visit(node)
  13. def write(self, text):
  14. self.f.write(six.text_type(text))
  15. def generic_visit(self, node):
  16. if isinstance(node, list):
  17. nodestart = "["
  18. nodeend = "]"
  19. children = [("", child) for child in node]
  20. else:
  21. nodestart = type(node).__name__ + "("
  22. nodeend = ")"
  23. children = [(name + "=", value) for name, value in ast.iter_fields(node)]
  24. if len(children) > 1:
  25. self.indentation += 1
  26. self.write(nodestart)
  27. for i, pair in enumerate(children):
  28. attr, child = pair
  29. if len(children) > 1:
  30. self.write("\n" + self.indent_with * self.indentation)
  31. if isinstance(child, (ast.AST, list)):
  32. self.write(attr)
  33. self.visit(child)
  34. else:
  35. self.write(attr + repr(child))
  36. if i != len(children) - 1:
  37. self.write(",")
  38. self.write(nodeend)
  39. if len(children) > 1:
  40. self.indentation -= 1