Methods in this class recursively traverse an AST and output source code for the abstract syntax; original formatting is disregarded.
| 681 | _ALL_QUOTES = (*_SINGLE_QUOTES, *_MULTI_QUOTES) |
| 682 | |
| 683 | class _Unparser(NodeVisitor): |
| 684 | """Methods in this class recursively traverse an AST and |
| 685 | output source code for the abstract syntax; original formatting |
| 686 | is disregarded.""" |
| 687 | |
| 688 | def __init__(self, *, _avoid_backslashes=False): |
| 689 | self._source = [] |
| 690 | self._precedences = {} |
| 691 | self._type_ignores = {} |
| 692 | self._indent = 0 |
| 693 | self._avoid_backslashes = _avoid_backslashes |
| 694 | self._in_try_star = False |
| 695 | |
| 696 | def interleave(self, inter, f, seq): |
| 697 | """Call f on each item in seq, calling inter() in between.""" |
| 698 | seq = iter(seq) |
| 699 | try: |
| 700 | f(next(seq)) |
| 701 | except StopIteration: |
| 702 | pass |
| 703 | else: |
| 704 | for x in seq: |
| 705 | inter() |
| 706 | f(x) |
| 707 | |
| 708 | def items_view(self, traverser, items): |
| 709 | """Traverse and separate the given *items* with a comma and append it to |
| 710 | the buffer. If *items* is a single item sequence, a trailing comma |
| 711 | will be added.""" |
| 712 | if len(items) == 1: |
| 713 | traverser(items[0]) |
| 714 | self.write(",") |
| 715 | else: |
| 716 | self.interleave(lambda: self.write(", "), traverser, items) |
| 717 | |
| 718 | def maybe_newline(self): |
| 719 | """Adds a newline if it isn't the start of generated source""" |
| 720 | if self._source: |
| 721 | self.write("\n") |
| 722 | |
| 723 | def fill(self, text=""): |
| 724 | """Indent a piece of text and append it, according to the current |
| 725 | indentation level""" |
| 726 | self.maybe_newline() |
| 727 | self.write(" " * self._indent + text) |
| 728 | |
| 729 | def write(self, *text): |
| 730 | """Add new source parts""" |
| 731 | self._source.extend(text) |
| 732 | |
| 733 | @contextmanager |
| 734 | def buffered(self, buffer = None): |
| 735 | if buffer is None: |
| 736 | buffer = [] |
| 737 | |
| 738 | original_source = self._source |
| 739 | self._source = buffer |
| 740 | yield buffer |