Skip to content

Commit

Permalink
loader: replace trim_docstring with builtin
Browse files Browse the repository at this point in the history
The `trim_docstring` function can be replaced by a builtin function
from the `inspect` module: `cleandoc`.

See also: https://docs.python.org/2/library/inspect.html#inspect.cleandoc

This:

```
inspect.cleandoc(func.__doc__ or '').splitlines()
```

Is functionnaly similar to this:

```
trim_docstring(func.__doc__)
```

It's even better, since the original function used to keep initial
indent and empty multi-line between non-empty lines. Since it was used
in one place only, it is safe to assume it can be replaced without
loss for the project by the builtin `inspect.cleandoc` function.

Example:

```
>>> data = """First line is not empty
...     Second line is direct after it.
...
...     Last line.
...
...     """
>>> inspect.cleandoc(data).splitlines()
['First line is not empty', 'Second line is direct after it.', '', 'Last line.']
>>> trim_docstring(data)
['First line is not empty', '    Second line is direct after it.', '', '    Last line.']
```
  • Loading branch information
Exirel committed Dec 27, 2018
1 parent 225590d commit 3683b86
Showing 1 changed file with 2 additions and 22 deletions.
24 changes: 2 additions & 22 deletions sopel/loader.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
from __future__ import unicode_literals, absolute_import, print_function, division

import imp
import inspect
import os.path
import re
import sys
Expand Down Expand Up @@ -111,27 +112,6 @@ def enumerate_modules(config, show_all=False):
return modules


def trim_docstring(doc):
"""Get the docstring as a series of lines that can be sent"""
if not doc:
return []
lines = doc.expandtabs().splitlines()
indent = sys.maxsize
for line in lines[1:]:
stripped = line.lstrip()
if stripped:
indent = min(indent, len(line) - len(stripped))
trimmed = [lines[0].strip()]
if indent < sys.maxsize:
for line in lines[1:]:
trimmed.append(line[:].rstrip())
while trimmed and not trimmed[-1]:
trimmed.pop()
while trimmed and not trimmed[0]:
trimmed.pop(0)
return trimmed


def clean_callable(func, config):
"""Compiles the regexes, moves commands into func.rule, fixes up docs and
puts them in func._docs, and sets defaults"""
Expand All @@ -140,7 +120,7 @@ def clean_callable(func, config):
prefix = config.core.prefix
help_prefix = config.core.help_prefix
func._docs = {}
doc = trim_docstring(func.__doc__)
doc = inspect.cleandoc(func.__doc__ or '').splitlines()
example = None

func.unblockable = getattr(func, 'unblockable', False)
Expand Down

0 comments on commit 3683b86

Please sign in to comment.