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 omittin
(
node, annotate_fields=True, include_attributes=False,
*,
indent=None, show_empty=False,
)
| 115 | |
| 116 | |
| 117 | def dump( |
| 118 | node, annotate_fields=True, include_attributes=False, |
| 119 | *, |
| 120 | indent=None, show_empty=False, |
| 121 | ): |
| 122 | """ |
| 123 | Return a formatted dump of the tree in node. This is mainly useful for |
| 124 | debugging purposes. If annotate_fields is true (by default), |
| 125 | the returned string will show the names and the values for fields. |
| 126 | If annotate_fields is false, the result string will be more compact by |
| 127 | omitting unambiguous field names. Attributes such as line |
| 128 | numbers and column offsets are not dumped by default. If this is wanted, |
| 129 | include_attributes can be set to true. If indent is a non-negative |
| 130 | integer or string, then the tree will be pretty-printed with that indent |
| 131 | level. None (the default) selects the single line representation. |
| 132 | If show_empty is False, then empty lists and fields that are None |
| 133 | will be omitted from the output for better readability. |
| 134 | """ |
| 135 | def _format(node, level=0): |
| 136 | if indent is not None: |
| 137 | level += 1 |
| 138 | prefix = '\n' + indent * level |
| 139 | sep = ',\n' + indent * level |
| 140 | else: |
| 141 | prefix = '' |
| 142 | sep = ', ' |
| 143 | if isinstance(node, AST): |
| 144 | cls = type(node) |
| 145 | args = [] |
| 146 | args_buffer = [] |
| 147 | allsimple = True |
| 148 | keywords = annotate_fields |
| 149 | for name in node._fields: |
| 150 | try: |
| 151 | value = getattr(node, name) |
| 152 | except AttributeError: |
| 153 | keywords = True |
| 154 | continue |
| 155 | if value is None and getattr(cls, name, ...) is None: |
| 156 | keywords = True |
| 157 | continue |
| 158 | if not show_empty: |
| 159 | if value == []: |
| 160 | field_type = cls._field_types.get(name, object) |
| 161 | if getattr(field_type, '__origin__', ...) is list: |
| 162 | if not keywords: |
| 163 | args_buffer.append(repr(value)) |
| 164 | continue |
| 165 | elif isinstance(value, Load): |
| 166 | field_type = cls._field_types.get(name, object) |
| 167 | if field_type is expr_context: |
| 168 | if not keywords: |
| 169 | args_buffer.append(repr(value)) |
| 170 | continue |
| 171 | if not keywords: |
| 172 | args.extend(args_buffer) |
| 173 | args_buffer = [] |
| 174 | value, simple = _format(value, level) |