Advertisement
mwchase

Flexible doc adding

Nov 29th, 2016
105
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.60 KB | None | 0 0
  1. def trim(docstring):
  2.     """Remove insignificant indentation from a docstring.
  3.  
  4.    This implementation is taken directly from PEP-0257.
  5.    """
  6.     if not docstring:
  7.         return ''
  8.     # Convert tabs to spaces (following the normal Python rules)
  9.     # and split into a list of lines:
  10.     lines = docstring.expandtabs().splitlines()
  11.     # Determine minimum indentation (first line doesn't count):
  12.     indent = sys.maxint
  13.     for line in lines[1:]:
  14.         stripped = line.lstrip()
  15.         if stripped:
  16.             indent = min(indent, len(line) - len(stripped))
  17.     # Remove indentation (first line is special):
  18.     trimmed = [lines[0].strip()]
  19.     if indent < sys.maxint:
  20.         for line in lines[1:]:
  21.             trimmed.append(line[indent:].rstrip())
  22.     # Strip off trailing and leading blank lines:
  23.     while trimmed and not trimmed[-1]:
  24.         trimmed.pop()
  25.     while trimmed and not trimmed[0]:
  26.         trimmed.pop(0)
  27.     # Return a single string:
  28.     return '\n'.join(trimmed)
  29.  
  30.  
  31. class WithDoc:
  32.  
  33.     def __new__(cls, *args):
  34.         if not args:
  35.             raise ValueError('Not enough args')
  36.         if len(args) > 2:
  37.             raise ValueError('Too many args')
  38.         if len(args) == 2:
  39.             obj, doc = args
  40.             return cls(doc)(obj)
  41.         else:
  42.             return super().__new__(cls)
  43.  
  44.     def __init__(self, doc):
  45.         self.doc = trim(doc)
  46.  
  47.     def __call__(self, obj):
  48.         existing = trim(obj.__doc__)
  49.         if existing:
  50.             obj.__doc__ = self.doc + '\n\n' + existing
  51.         else:
  52.             obj.__doc__ = self.doc
  53.         return obj
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement