@@ -93,26 +93,35 @@ def _convert(node):
9393
9494def dump (node , annotate_fields = True , include_attributes = False ):
9595 """
96- Return a formatted dump of the tree in *node*. This is mainly useful for
97- debugging purposes. The returned string will show the names and the values
98- for fields. This makes the code impossible to evaluate, so if evaluation is
99- wanted *annotate_fields* must be set to False. Attributes such as line
96+ Return a formatted dump of the tree in node. This is mainly useful for
97+ debugging purposes. If annotate_fields is true (by default),
98+ the returned string will show the names and the values for fields.
99+ If annotate_fields is false, the result string will be more compact by
100+ omitting unambiguous field names. Attributes such as line
100101 numbers and column offsets are not dumped by default. If this is wanted,
101- * include_attributes* can be set to True .
102+ include_attributes can be set to true .
102103 """
103104 def _format (node ):
104105 if isinstance (node , AST ):
105- fields = [(a , _format (b )) for a , b in iter_fields (node )]
106- rv = '%s(%s' % (node .__class__ .__name__ , ', ' .join (
107- ('%s=%s' % field for field in fields )
108- if annotate_fields else
109- (b for a , b in fields )
110- ))
106+ args = []
107+ keywords = annotate_fields
108+ for field in node ._fields :
109+ try :
110+ value = getattr (node , field )
111+ except AttributeError :
112+ keywords = True
113+ else :
114+ if keywords :
115+ args .append ('%s=%s' % (field , _format (value )))
116+ else :
117+ args .append (_format (value ))
111118 if include_attributes and node ._attributes :
112- rv += fields and ', ' or ' '
113- rv += ', ' .join ('%s=%s' % (a , _format (getattr (node , a )))
114- for a in node ._attributes )
115- return rv + ')'
119+ for a in node ._attributes :
120+ try :
121+ args .append ('%s=%s' % (a , _format (getattr (node , a ))))
122+ except AttributeError :
123+ pass
124+ return '%s(%s)' % (node .__class__ .__name__ , ', ' .join (args ))
116125 elif isinstance (node , list ):
117126 return '[%s]' % ', ' .join (_format (x ) for x in node )
118127 return repr (node )
0 commit comments