Return a formatted dump of the tree in node. This is mainly useful for debugging purposes. If annotate_fields is true (by default), the returned string will show the names and the values for fields. If annotate_fields is false, the result string will be more compact by om
(node, annotate_fields=True, include_attributes=False, *, indent=None)
| 111 | |
| 112 | |
| 113 | def dump(node, annotate_fields=True, include_attributes=False, *, indent=None): |
| 114 | """ |
| 115 | Return a formatted dump of the tree in node. This is mainly useful for |
| 116 | debugging purposes. If annotate_fields is true (by default), |
| 117 | the returned string will show the names and the values for fields. |
| 118 | If annotate_fields is false, the result string will be more compact by |
| 119 | omitting unambiguous field names. Attributes such as line |
| 120 | numbers and column offsets are not dumped by default. If this is wanted, |
| 121 | include_attributes can be set to true. If indent is a non-negative |
| 122 | integer or string, then the tree will be pretty-printed with that indent |
| 123 | level. None (the default) selects the single line representation. |
| 124 | """ |
| 125 | def _format(node, level=0): |
| 126 | if indent is not None: |
| 127 | level += 1 |
| 128 | prefix = '\n' + indent * level |
| 129 | sep = ',\n' + indent * level |
| 130 | else: |
| 131 | prefix = '' |
| 132 | sep = ', ' |
| 133 | if isinstance(node, AST): |
| 134 | cls = type(node) |
| 135 | args = [] |
| 136 | allsimple = True |
| 137 | keywords = annotate_fields |
| 138 | for name in node._fields: |
| 139 | try: |
| 140 | value = getattr(node, name) |
| 141 | except AttributeError: |
| 142 | keywords = True |
| 143 | continue |
| 144 | if value is None and getattr(cls, name, ...) is None: |
| 145 | keywords = True |
| 146 | continue |
| 147 | value, simple = _format(value, level) |
| 148 | allsimple = allsimple and simple |
| 149 | if keywords: |
| 150 | args.append('%s=%s' % (name, value)) |
| 151 | else: |
| 152 | args.append(value) |
| 153 | if include_attributes and node._attributes: |
| 154 | for name in node._attributes: |
| 155 | try: |
| 156 | value = getattr(node, name) |
| 157 | except AttributeError: |
| 158 | continue |
| 159 | if value is None and getattr(cls, name, ...) is None: |
| 160 | continue |
| 161 | value, simple = _format(value, level) |
| 162 | allsimple = allsimple and simple |
| 163 | args.append('%s=%s' % (name, value)) |
| 164 | if allsimple and len(args) <= 3: |
| 165 | return '%s(%s)' % (node.__class__.__name__, ', '.join(args)), not args |
| 166 | return '%s(%s%s)' % (node.__class__.__name__, prefix, sep.join(args)), False |
| 167 | elif isinstance(node, list): |
| 168 | if not node: |
| 169 | return '[]', True |
| 170 | return '[%s%s]' % (prefix, sep.join(_format(x, level)[0] for x in node)), False |