@@ -201,10 +201,27 @@ def import_from_node(node: cst.SimpleStatementLine, config: Config) -> SortableI
201201 if node .body [0 ].relative :
202202 stem = "." * len (node .body [0 ].relative ) + stem
203203
204- for name in node .body [0 ].names :
204+ # For single-line imports with preserve_inline_comments, attach trailing
205+ # comments to the specific item instead of the import level
206+ is_single_line = not node .body [0 ].lpar
207+ single_item_count = len (node .body [0 ].names )
208+
209+ for idx , name in enumerate (node .body [0 ].names ):
205210 items .append (item_from_node (name , stem , comments .initial ))
206211 comments .initial = []
207212
213+ # If preserving inline comments and this is a single-line import with
214+ # one item, move first_inline comments to the item's inline comments
215+ if (
216+ config .preserve_inline_comments
217+ and is_single_line
218+ and single_item_count == 1
219+ and idx == 0
220+ and comments .first_inline
221+ ):
222+ items [- 1 ].comments .inline .extend (comments .first_inline )
223+ comments .first_inline .clear ()
224+
208225 else :
209226 raise TypeError
210227
@@ -240,6 +257,14 @@ def import_to_node(
240257) -> cst .BaseStatement :
241258 if config .magic_commas and imp .stem and imp .trailing_comma :
242259 return import_to_node_multi (imp , module )
260+
261+ # If preserve_inline_comments is enabled and any item has inline comments,
262+ # use multi-line format to preserve them
263+ if config .preserve_inline_comments and imp .stem :
264+ has_item_comments = any (item .comments .inline for item in imp .items )
265+ if has_item_comments :
266+ return import_to_node_multi (imp , module )
267+
243268 node = import_to_node_single (imp , module )
244269 content = indent + render_node (node , module ).rstrip ()
245270 # basic imports can't be reflowed, so only deal with from-imports
0 commit comments