Created
August 25, 2011 19:30
-
-
Save DarwinAwardWinner/1171593 to your computer and use it in GitHub Desktop.
Fix the line breaks in a Python functions's doc string
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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