Skip to content

Instantly share code, notes, and snippets.

@DarwinAwardWinner
Created August 25, 2011 19:30
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DarwinAwardWinner/1171593 to your computer and use it in GitHub Desktop.
Save DarwinAwardWinner/1171593 to your computer and use it in GitHub Desktop.
Fix the line breaks in a Python functions's doc string
import textwrap
def refill_docstring(func, *args, **kwargs):
"""Fix the text wrapping in a function's docstring.
This can be useful when creating doc strings dynamically.
Additional args are options to textwrap.TextWrapper."""
wrapper = textwrap.TextWrapper(*args, **kwargs)
# Remove trailing whitespace from all lines
docstring = re.sub(r'[^\S\n]*\n[^\S\n]*', '\n', func.__doc__)
# Split on double newline
paragraphs = re.split(r"[^\S\n]*\n(?:\s*\n)+", func.__doc__)
dedented_paragraphs = filter(None, map(textwrap.dedent, paragraphs))
filled_paragraphs = map(wrapper.fill, dedented_paragraphs)
func.__doc__ = "\n\n".join(filled_paragraphs)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment