Index: Lib/lib2to3/tests/test_fixers.py =================================================================== --- Lib/lib2to3/tests/test_fixers.py (revision 75274) +++ Lib/lib2to3/tests/test_fixers.py (working copy) @@ -3238,6 +3238,46 @@ """ self.check(b, a) + b = r""" + try: + m = list(s) + m.sort() + except: pass + """ + + a = r""" + try: + m = sorted(s) + except: pass + """ + self.check(b, a) + + b = r""" + try: + m = list(s) + # foo + m.sort() + except: pass + """ + + a = r""" + try: + m = sorted(s) + # foo + except: pass + """ + self.check(b, a) + + b = r""" + m = list(s) + # more comments + m.sort()""" + + a = r""" + m = sorted(s) + # more comments""" + self.check(b, a) + def test_sort_simple_expr(self): b = """ v = t Index: Lib/lib2to3/fixes/fix_idioms.py =================================================================== --- Lib/lib2to3/fixes/fix_idioms.py (revision 75274) +++ Lib/lib2to3/fixes/fix_idioms.py (working copy) @@ -130,5 +130,24 @@ else: raise RuntimeError("should not have reached here") sort_stmt.remove() - if next_stmt: - next_stmt[0].prefix = sort_stmt.prefix + + btwn = sort_stmt.prefix + # keep any prefix lines between the sort_stmt and the list_call + # and shove them right after the sorted() call. + if "\n" in btwn: + if next_stmt: + # new prefix should be everything from the sort_stmt's prefix + # up to the last newline, then the old prefix after a new line + prefix_lines = (btwn.rpartition("\n")[0], next_stmt[0].prefix) + next_stmt[0].prefix = "\n".join(prefix_lines) + else: + assert list_call.parent + assert list_call.next_sibling is None + # put a BlankLine after list_call and set its prefix + from ..fixer_util import BlankLine + end_line = BlankLine() + list_call.parent.append_child(end_line) + assert list_call.next_sibling is end_line + # new prefix should be everything up to the first new line + # of sort_stmt's prefix + end_line.prefix = btwn.rpartition("\n")[0]