| 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 |
| 171 | return repr(node), True |
| 172 | |
| 173 | if not isinstance(node, AST): |
| 174 | raise TypeError('expected AST, got %r' % node.__class__.__name__) |