Skip to content

Megesh07/Megesh07-Python-Docstring-Generator

Repository files navigation

Python Docstring Generator

Automated docstring generation with multiple style support, error detection, and inline comments

Python Streamlit License

🌐 Live Demo

Try it now: Python Docstring Generator πŸš€

Experience the app live without any installation required!


πŸ“– Overview

Python Docstring Generator is a powerful, template-based tool that automatically generates professional docstrings for your Python code. It supports multiple docstring styles (Google, NumPy, reST), detects code issues, and adds helpful inline commentsβ€”all through a clean, intuitive web interface.

✨ Key Features

  • 🎨 Multiple Docstring Styles - Google, NumPy, and reStructuredText (reST)
  • βœ… Docstring Validation - Validates generated docstrings for quality, completeness, and PEP 257 compliance
  • πŸ” Error Detection - Identifies syntax errors, unused imports, and missing type hints
  • πŸ’¬ Inline Comments - Automatically adds comments for complex code constructs
  • βœ… Smart Detection - Preserves existing docstrings
  • 🎯 Selective Generation - Review and accept only the docstrings you want
  • ⚑ Instant Generation - Template-based, no API calls required
  • 🎨 Clean UI - Simple 3-step workflow

πŸ—οΈ Architecture

Architecture Diagram

System Components

graph TB
    A[User uploads Python file] --> B[Parser Module]
    B --> C[AST Analysis]
    C --> D[Generator Module]
    C --> E[Validator Module]
    C --> F[Error Detector]
    C --> G[Comment Generator]
    D --> H[Docstring Generation]
    E --> I[Quality Validation]
    F --> J[Issue Detection]
    G --> K[Inline Comments]
    H --> L[Inserter Module]
    I --> L
    J --> L
    K --> L
    L --> M[Enhanced Python File]
    M --> N[User Download]
Loading

Module Breakdown

Module Purpose Key Functions
Parser (parser.py) Extracts function/class metadata using AST parse_python_file()
Generator (generator.py) Creates docstrings in multiple styles generate_function_docstring(), generate_class_docstring()
Validator (validator.py) Validates docstring quality and compliance validate_docstring(), check_pep257_compliance()
Error Detector (error_detector.py) Identifies code issues detect_issues()
Comment Generator (comment_generator.py) Adds inline comments generate_inline_comments()
Inserter (inserter.py) Combines docstrings into source code insert_docstrings()
Models (models.py) Data structures for metadata FunctionInfo, ClassInfo, Parameter
App (app.py) Streamlit UI and workflow Main application

πŸš€ Quick Start

Installation

# Clone the repository
git clone https://github.com/Megesh07/Python-Doctring-Generator.git
cd Python-Docstring-Generator

# Install dependencies
pip install -r requirements.txt

Run the Application

streamlit run app.py

The app will open in your browser at http://localhost:8501


πŸ“š How It Works

Step 1: Upload Python File

Upload any Python file (.py) through the web interface.

Step 2: Review Generated Docstrings

  • View all generated docstrings
  • See detected code issues
  • Accept or reject individual docstrings

Step 3: Download Enhanced Code

Download your Python file with the accepted docstrings and inline comments.


🎨 Docstring Styles

Google Style (Default)

def calculate_sum(a: int, b: int) -> int:
    """
    Calculate Sum function.

    Args:
        a (int): The a parameter.
        b (int): The b parameter.

    Returns:
        int: Return value.
    """
    return a + b

NumPy Style

def calculate_sum(a: int, b: int) -> int:
    """
    Calculate Sum function.

    Parameters
    ----------
    a : int
        The a parameter.
    b : int
        The b parameter.

    Returns
    -------
    int
        Return value.
    """
    return a + b

reST Style

def calculate_sum(a: int, b: int) -> int:
    """
    Calculate Sum function.

    :param a: The a parameter.
    :type a: int
    :param b: The b parameter.
    :type b: int
    :returns: Return value.
    :rtype: int
    """
    return a + b

πŸ” Features in Detail

1. Docstring Generation

  • Purpose: Generates clear function/class descriptions
  • Parameters: Documents all parameters with types and defaults
  • Returns: Includes return type information
  • Filters: Automatically excludes self and cls parameters

2. Error Detection

Detects and reports:

  • βœ… Syntax errors
  • βœ… Unused imports
  • βœ… Missing type hints (parameters)
  • βœ… Missing return type hints

3. Inline Comments

Automatically adds comments for:

  • List comprehensions
  • Dictionary comprehensions
  • Lambda functions
  • Try-except blocks
  • Context managers

4. Existing Docstring Detection

  • Preserves existing docstrings
  • Shows "Already documented" status
  • Skips generation for documented items

5. Docstring Validation

The validator ensures every generated docstring meets professional standards.

What it validates:

  • βœ… PEP 257 Compliance

    • Summary line format and punctuation
    • Blank line after summary (multi-line docstrings)
    • Proper docstring structure
  • βœ… Format Compliance

    • Google style: Args: and Returns: sections
    • NumPy style: Dashed section headers
    • reST style: :param and :returns: directives
  • βœ… Completeness

    • All parameters documented
    • Return type documented (if applicable)
    • No missing information

Quality Scoring (0-100):

  • 90-100: βœ… Excellent - Production-ready
  • 70-89: ⚠️ Good - Minor improvements suggested
  • 0-69: ❌ Needs improvement - Review warnings

Example Validation Output:

calculate_area (Line 5)
βœ… Validation: 100/100 (Excellent)

View docstring:
  """
  Calculate Area function.

  Args:
      length: The length parameter.
      width: The width parameter.
  """

πŸ“ Project Structure

Python-Docstring-Generator/
β”œβ”€β”€ app.py                     # Main Streamlit application
β”œβ”€β”€ models.py                  # Data classes (FunctionInfo, ClassInfo, etc.)
β”œβ”€β”€ parser.py                  # AST-based Python code parser
β”œβ”€β”€ generator.py               # Multi-style docstring generator
β”œβ”€β”€ validator.py               # Docstring quality validator
β”œβ”€β”€ inserter.py                # Docstring insertion logic
β”œβ”€β”€ error_detector.py          # Code issue detection
β”œβ”€β”€ comment_generator.py       # Inline comment generation
β”œβ”€β”€ sample.py                  # Example Python file for testing
β”œβ”€β”€ requirements.txt           # Python dependencies
β”œβ”€β”€ README.md                  # This file
β”œβ”€β”€ architecture_diagram.png   # System architecture diagram
└── .gitignore                 # Git ignore rules

πŸ› οΈ Technical Details

Technologies Used

  • Python 3.8+ - Core language
  • Streamlit - Web UI framework
  • AST (Abstract Syntax Tree) - Code parsing
  • Dataclasses - Data structures

Key Design Decisions

  1. Template-Based Generation

    • No AI/API dependencies
    • Instant generation
    • Completely offline
    • Free to use
  2. AST Parsing

    • Accurate code analysis
    • Extracts metadata reliably
    • Handles complex Python syntax
  3. Multi-Style Support

    • Supports 3 major docstring styles
    • Easy to add new styles
    • Consistent formatting

πŸ“Š Example Usage

Input Code

def calculate_area(length, width):
    return length * width

class DataProcessor:
    def process(self):
        return [x * 2 for x in self.data]

Generated Output (Google Style)

def calculate_area(length, width):
    """
    Calculate Area function.

    Args:
        length: The length parameter.
        width: The width parameter.
    """
    return length * width

class DataProcessor:
    """
    Data Processor class.

    Provides methods: process.
    """
    def process(self):
        """
        Process function.
        """
        return [x * 2 for x in self.data]  # List comprehension

🎯 Use Cases

  • Code Documentation - Quickly document existing codebases
  • Code Review - Ensure all functions are documented
  • Learning - Understand proper docstring formatting
  • Standardization - Enforce consistent documentation style
  • Open Source - Prepare code for public release

🀝 Contributing

Contributions are welcome! Please feel free to submit a Pull Request.


πŸ“ License

This project is licensed under the MIT License - see the LICENSE file for details.


πŸ™ Acknowledgments

  • Built with Streamlit
  • Inspired by Python documentation best practices
  • Supports PEP 257 docstring conventions

πŸ“§ Contact

For questions or feedback, please open an issue on GitHub.

About

No description, website, or topics provided.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Contributors 2

  •  
  •  

Languages