Skip to content

Commit 2b3f500

Browse files
committed
minor optimizations for simulataneously comptuing min + max + normalization
1 parent 6aa88a2 commit 2b3f500

File tree

1 file changed

+18
-5
lines changed

1 file changed

+18
-5
lines changed

Lib/textwrap.py

Lines changed: 18 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -432,15 +432,28 @@ def dedent(text):
432432
lines = text.split('\n')
433433

434434
# Get length of leading whitespace, inspired by ``os.path.commonprefix()``.
435-
non_blank_lines = [l for l in lines if l and not l.isspace()]
436-
l1 = min(non_blank_lines, default='')
437-
l2 = max(non_blank_lines, default='')
438-
margin = 0
435+
l1 = None
436+
l2 = None
437+
for i, line in enumerate(lines):
438+
# Compute min + max concurrently + normalize others
439+
if line and not line.isspace():
440+
if l1 is None or line < l1:
441+
l1 = line
442+
if l2 is None or line > l2:
443+
l2 = line
444+
else:
445+
lines[i] = ''
446+
447+
if l1 is None:
448+
l1 = ''
449+
439450
for margin, c in enumerate(l1):
440451
if c != l2[margin] or c not in ' \t':
441452
break
453+
else:
454+
return '\n'.join(lines)
442455

443-
return '\n'.join([l[margin:] if not l.isspace() else '' for l in lines])
456+
return '\n'.join([line[margin:] for line in lines])
444457

445458

446459
def indent(text, prefix, predicate=None):

0 commit comments

Comments
 (0)