Skip to content

Commit f04fdcd

Browse files
showemptyattrs option on Node.show() (#570)
* hideemptyattrs option on Node.show() * slight simplification * prefer positive logic
1 parent 156eae7 commit f04fdcd

File tree

1 file changed

+9
-4
lines changed

1 file changed

+9
-4
lines changed

pycparser/c_ast.py

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -55,7 +55,7 @@ def children(self):
5555
"""
5656
pass
5757

58-
def show(self, buf=sys.stdout, offset=0, attrnames=False, nodenames=False, showcoord=False, _my_node_name=None):
58+
def show(self, buf=sys.stdout, offset=0, attrnames=False, showemptyattrs=True, nodenames=False, showcoord=False, _my_node_name=None):
5959
""" Pretty print the Node and all its attributes and
6060
children (recursively) to a buffer.
6161
@@ -69,6 +69,9 @@ def show(self, buf=sys.stdout, offset=0, attrnames=False, nodenames=False, showc
6969
True if you want to see the attribute names in
7070
name=value pairs. False to only see the values.
7171
72+
showemptyattrs:
73+
False if you want to suppress printing empty attributes.
74+
7275
nodenames:
7376
True if you want to see the actual node names
7477
within their parents.
@@ -84,12 +87,13 @@ def show(self, buf=sys.stdout, offset=0, attrnames=False, nodenames=False, showc
8487
buf.write(lead + self.__class__.__name__+ ': ')
8588

8689
if self.attr_names:
90+
is_empty = lambda v: v is None or (hasattr(v, '__len__') and len(v) == 0)
91+
nvlist = [(n, getattr(self,n)) for n in self.attr_names \
92+
if showemptyattrs or not is_empty(getattr(self,n))]
8793
if attrnames:
88-
nvlist = [(n, getattr(self,n)) for n in self.attr_names]
8994
attrstr = ', '.join('%s=%s' % nv for nv in nvlist)
9095
else:
91-
vlist = [getattr(self, n) for n in self.attr_names]
92-
attrstr = ', '.join('%s' % v for v in vlist)
96+
attrstr = ', '.join('%s' % v for (_,v) in nvlist)
9397
buf.write(attrstr)
9498

9599
if showcoord:
@@ -101,6 +105,7 @@ def show(self, buf=sys.stdout, offset=0, attrnames=False, nodenames=False, showc
101105
buf,
102106
offset=offset + 2,
103107
attrnames=attrnames,
108+
showemptyattrs=showemptyattrs,
104109
nodenames=nodenames,
105110
showcoord=showcoord,
106111
_my_node_name=child_name)

0 commit comments

Comments
 (0)