diff --git a/Lib/lib2to3/refactor.py b/Lib/lib2to3/refactor.py index 55fd60fa27c3da9..3ec50458a9b57df 100644 --- a/Lib/lib2to3/refactor.py +++ b/Lib/lib2to3/refactor.py @@ -592,12 +592,21 @@ def refactor_doctest(self, block, lineno, indent, filename): return block if self.refactor_tree(tree, filename): new = str(tree).splitlines(keepends=True) + # Adjust lineno for lines inserted before + jmp = 0 + for n in new: + if n == '\n': break + jmp += 1 + pre = new[:jmp] # Undo the adjustment of the line numbers in wrap_toks() below. - clipped, new = new[:lineno-1], new[lineno-1:] + clipped, new = new[jmp:lineno-1+jmp], new[lineno-1+jmp:] assert clipped == ["\n"] * (lineno-1), clipped if not new[-1].endswith("\n"): new[-1] += "\n" - block = [indent + self.PS1 + new.pop(0)] + block = [] + if pre: + block += [indent + self.PS1 + line for line in pre] + block += [indent + self.PS1 + new.pop(0)] if new: block += [indent + self.PS2 + line for line in new] return block diff --git a/Lib/lib2to3/tests/test_fixers.py b/Lib/lib2to3/tests/test_fixers.py index 3da5dd845c93c66..446b79a357435c1 100644 --- a/Lib/lib2to3/tests/test_fixers.py +++ b/Lib/lib2to3/tests/test_fixers.py @@ -428,6 +428,30 @@ def test_unchanged(self): s = "reduce()" self.unchanged(s) +class Test_doctests(FixerTestCase): + fixer = "reduce" + + def check(self, before, after, ignore_warnings=False): + before = support.reformat(before) + after = support.reformat(after) + output = self.refactor.refactor_docstring(before, self.filename) + self.assertEqual(after, output) + + def test_reduce(self): + # See issue 12611 + b = """\ + ''' + >>> reduce(lambda x, y: x + y, seq) + ''' + """ + a = """\ + ''' + >>> from functools import reduce + >>> reduce(lambda x, y: x + y, seq) + ''' + """ + self.check(b, a) + class Test_print(FixerTestCase): fixer = "print" diff --git a/Misc/NEWS.d/next/Library/2019-08-13-09-27-23.bpo-12611.e06VtJ.rst b/Misc/NEWS.d/next/Library/2019-08-13-09-27-23.bpo-12611.e06VtJ.rst new file mode 100644 index 000000000000000..0b82e1a6c9288f8 --- /dev/null +++ b/Misc/NEWS.d/next/Library/2019-08-13-09-27-23.bpo-12611.e06VtJ.rst @@ -0,0 +1 @@ +2to3 converting doctest using reduce(). Patch by Aldwin Pollefeyt.