@@ -98,26 +98,35 @@ def _convert(node):
9898
9999def dump (node , annotate_fields = True , include_attributes = False ):
100100 """
101- Return a formatted dump of the tree in *node*. This is mainly useful for
102- debugging purposes. The returned string will show the names and the values
103- for fields. This makes the code impossible to evaluate, so if evaluation is
104- wanted *annotate_fields* must be set to False. Attributes such as line
101+ Return a formatted dump of the tree in node. This is mainly useful for
102+ debugging purposes. If annotate_fields is true (by default),
103+ the returned string will show the names and the values for fields.
104+ If annotate_fields is false, the result string will be more compact by
105+ omitting unambiguous field names. Attributes such as line
105106 numbers and column offsets are not dumped by default. If this is wanted,
106- * include_attributes* can be set to True .
107+ include_attributes can be set to true .
107108 """
108109 def _format (node ):
109110 if isinstance (node , AST ):
110- fields = [(a , _format (b )) for a , b in iter_fields (node )]
111- rv = '%s(%s' % (node .__class__ .__name__ , ', ' .join (
112- ('%s=%s' % field for field in fields )
113- if annotate_fields else
114- (b for a , b in fields )
115- ))
111+ args = []
112+ keywords = annotate_fields
113+ for field in node ._fields :
114+ try :
115+ value = getattr (node , field )
116+ except AttributeError :
117+ keywords = True
118+ else :
119+ if keywords :
120+ args .append ('%s=%s' % (field , _format (value )))
121+ else :
122+ args .append (_format (value ))
116123 if include_attributes and node ._attributes :
117- rv += fields and ', ' or ' '
118- rv += ', ' .join ('%s=%s' % (a , _format (getattr (node , a )))
119- for a in node ._attributes )
120- return rv + ')'
124+ for a in node ._attributes :
125+ try :
126+ args .append ('%s=%s' % (a , _format (getattr (node , a ))))
127+ except AttributeError :
128+ pass
129+ return '%s(%s)' % (node .__class__ .__name__ , ', ' .join (args ))
121130 elif isinstance (node , list ):
122131 return '[%s]' % ', ' .join (_format (x ) for x in node )
123132 return repr (node )
0 commit comments