@@ -182,7 +182,9 @@ def split_generic_value(node: Node, indent: int, line_length: int) -> list[str]:
182182 return [stringify_single_line_node (node )]
183183
184184
185- def split_generic_list (middle : list [Node ], indent : int , line_length : int ) -> list [str ]:
185+ def split_generic_list (
186+ middle : list [Node ], indent : int , line_length : int , trailing_comma : bool = True
187+ ) -> list [str ]:
186188 """Split list elements into one-per-line strings, each pre-indented."""
187189 elements : list [str ] = []
188190 for element in middle :
@@ -196,25 +198,27 @@ def split_generic_list(middle: list[Node], indent: int, line_length: int) -> lis
196198 lines = split_generic_value (element , indent , line_length )
197199 elements .append (" " * indent + lines [0 ])
198200 elements .extend (lines [1 :])
199- # Always add a trailing comma on multi-line lists , on the last
201+ # Ensure trailing comma state matches the desired setting , on the last
200202 # non-comment element (so it doesn't end up after a trailing comment).
201203 for i in range (len (elements ) - 1 , - 1 , - 1 ):
202204 if elements [i ].lstrip ().startswith ("#" ):
203205 continue
204- if not elements [i ].endswith ("," ):
206+ if trailing_comma and not elements [i ].endswith ("," ):
205207 elements [i ] = elements [i ] + ","
208+ elif not trailing_comma and elements [i ].endswith ("," ):
209+ elements [i ] = elements [i ][:- 1 ]
206210 break
207211 return elements
208212
209213
210214def maybe_split_generic_list (
211- nodes : list [Node ], indent : int , line_length : int
215+ nodes : list [Node ], indent : int , line_length : int , trailing_comma : bool = True
212216) -> list [str ]:
213217 """Try a single-line rendering; fall back to split_generic_list if too long."""
214218 string = " " * indent + stringify_single_line_nodes (nodes )
215219 if len (string ) < line_length :
216220 return [string ]
217- return split_generic_list (nodes , indent , line_length )
221+ return split_generic_list (nodes , indent , line_length , trailing_comma )
218222
219223
220224def split_rval_list (node : Node , indent : int , line_length : int ) -> list [str ]:
@@ -236,7 +240,9 @@ def split_rval_call(node: Node, indent: int, line_length: int) -> list[str]:
236240 first = text (node .children [0 ]) + "("
237241 last = " " * indent + text (node .children [- 1 ])
238242 middle = node .children [2 :- 1 ]
239- elements = maybe_split_generic_list (middle , indent + 2 , line_length )
243+ elements = maybe_split_generic_list (
244+ middle , indent + 2 , line_length , trailing_comma = False
245+ )
240246 return [first , * elements , last ]
241247
242248
0 commit comments