8000 gh-130167: Optimise ``textwrap.dedent()`` by AA-Turner · Pull Request #131919 · python/cpython · GitHub
[go: up one dir, main page]

Skip to content

gh-130167: Optimise textwrap.dedent() #131919

< 8000 div class="d-flex flex-order-2 flex-md-order-1 mx-2">
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 11 commits into from
Mar 31, 2025
Prev Previous commit
Next Next commit
Further micro-optimisation for entirely blank input
  • Loading branch information
AA-Turner committed Mar 30, 2025
commit 19e76d3efde3527eb2b38fa6cea65b17be22d4d7
9 changes: 5 additions & 4 deletions Lib/textwrap.py
Original file line number Diff line number Diff line change
Expand Up @@ -429,13 +429,14 @@ def dedent(text):
if not text:
return text

lines = text.split('\n')
# If the input is entirely whitespace, return normalized lines
if text.isspace():
return '\n' * text.count('\n')

non_blank_lines = [l for l in lines if l and not l.isspace()]
if not non_blank_lines:
return '\n'.join([l if l and not l.isspace() else '' for l in lines])
lines = text.split('\n')

# Get length of leading whitespace, inspired by ``os.path.commonprefix()``
non_blank_lines = [l for l in lines if l and not l.isspace()]
l1 = min(non_blank_lines)
l2 = max(non_blank_lines)
margin = 0
Expand Down
Loading
0