def trim(docstring):
"""Remove insignificant indentation from a docstring.
This implementation is taken directly from PEP-0257.
"""
if not docstring:
return ''
# Convert tabs to spaces (following the normal Python rules)
# and split into a list of lines:
lines = docstring.expandtabs().splitlines()
# Determine minimum indentation (first line doesn't count):
indent = sys.maxint
for line in lines[1:]:
stripped = line.lstrip()
if stripped:
indent = min(indent, len(line) - len(stripped))
# Remove indentation (first line is special):
trimmed = [lines[0].strip()]
if indent < sys.maxint:
for line in lines[1:]:
trimmed.append(line[indent:].rstrip())
# Strip off trailing and leading blank lines:
while trimmed and not trimmed[-1]:
trimmed.pop()
while trimmed and not trimmed[0]:
trimmed.pop(0)
# Return a single string:
return '\n'.join(trimmed)
class WithDoc:
def __new__(cls, *args):
if not args:
raise ValueError('Not enough args')
if len(args) > 2:
raise ValueError('Too many args')
if len(args) == 2:
obj, doc = args
return cls(doc)(obj)
else:
return super().__new__(cls)
def __init__(self, doc):
self.doc = trim(doc)
def __call__(self, obj):
existing = trim(obj.__doc__)
if existing:
obj.__doc__ = self.doc + '\n\n' + existing
else:
obj.__doc__ = self.doc
return obj
Comments