Auto-Documenting Python Code
A while ago I thought about auto-documenting Python code, here’s what resulted from those experiments. (It’s far away from production quality, so use at your own risk)#
Let’s assume we have a Python file without docstrings:
class HalloWelt: def Hallo(welt): return welt print(HalloWelt.Hallo("Welt")) |
My experimental Python code:
import re class Dokumenter: """ Fügt einer bestehenden Python-Datei Docstrings hinzu, falls keine vorhanden sind. """ def dokumentme(filename): print(">> Prüfe",filename,"auf Docstrings\n") with open(filename+"_bak", 'w') as outfile: with open(filename, 'r') as infile: rowIter= iter(infile) for row in rowIter: # schreibe die Zeile auf jeden Fall in die Zieldatei outfile.write(row) # Ist in der Zeile ein 'def ' vorhanden? if "def " in row: # suche erstes Zeichen, das kein Docstring ist index = re.search('\S', row).start() whitespace = row[:index] whitespaceLen = len(whitespace) if " " in whitespace: blanks = True else: blanks = False print(whitespaceLen,blanks) print(">> Funktionsdefinition gefunden") print(">> Schreibe Docstring") print(">> Whitespaces",index) outfile.write('"""\nHallo Welt\n"""\n') print(row) Dokumenter.dokumentme("dokme.py") # Tests, Datei mit und ohne Dokstring,unterschiedliche Einrückungstiefe # extrahiere die Parameter |
Output:
class HalloWelt: def Hallo(welt): """ Hallo Welt """ return welt print(HalloWelt.Hallo("Welt")) |