Pandaaaa906

stupidly detect docstring

Feb 19th, 2021 (edited)
488
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.71 KB | None | 0 0
  1. import re
  2. import inspect
  3. from importlib import import_module
  4.  
  5. fp = r"scratch_1.py"
  6.  
  7. module_name = inspect.getmodulename(fp)
  8. module = import_module(module_name)
  9.  
  10.  
  11. funcs = tuple((k, v) for k, v in inspect.getmembers(module) if inspect.isfunction(v))
  12. for func_name, func in funcs:
  13.     lines, offset = inspect.getsourcelines(func)
  14.     doc_string = inspect.getdoc(func)
  15.     print(f'function: {func_name}, id: {func} start at line {offset}.')
  16.     print(f'doc string is: {repr(doc_string)}')
  17.  
  18.     def_index = None
  19.     doc_index_s = None
  20.     doc_index_e = None
  21.  
  22.     for sub_index, line in enumerate(lines):
  23.         # detect def line ends
  24.         if def_index is None:
  25.             m = re.search(r'\):\s*(#.+)?\n', line)
  26.             if m:
  27.                 def_index = sub_index
  28.             continue
  29.         # detect no docstring
  30.         if doc_index_s is None and re.search(r'^\s*\w', line):
  31.             break
  32.         # detect docstring start
  33.         if doc_index_s is None:
  34.             if re.search(r'^\s+["\']{3}.*(#.+)?\n', line):
  35.                 doc_index_s = sub_index
  36.                 continue
  37.             elif re.search(r'^\s+["\']', line):
  38.                 doc_index_s = sub_index
  39.                 doc_index_e = sub_index
  40.                 break
  41.         # detect docstring end
  42.         if doc_index_s:
  43.             if re.search(r'(?!=\\)[\'"]\s*(#.+)?\n', line):
  44.                 doc_index_e = sub_index
  45.  
  46.         # break if doc string collected
  47.         if doc_index_s and doc_index_e:
  48.             break
  49.  
  50.     print('Doc string lines are:')
  51.     print(''.join(f'[{i:>2}] {line}' for i, line in enumerate(lines[doc_index_s:doc_index_e+1], start=offset+doc_index_s)))
  52.     pass
  53.  
  54. if __name__ == '__main__':
  55.     pass
Add Comment
Please, Sign In to add comment