Skip to content

Instantly share code, notes, and snippets.

@robert-hoffmann
Last active January 6, 2026 12:43
Show Gist options
  • Select an option

  • Save robert-hoffmann/a096958ca6c6317fb7e1da89a71aea66 to your computer and use it in GitHub Desktop.

Select an option

Save robert-hoffmann/a096958ca6c6317fb7e1da89a71aea66 to your computer and use it in GitHub Desktop.
Copilot prompt and instructions for clean code
mode description
ask
Document a Python file in the project, following specific conventions for style, formatting, and documentation.

Please document the file ${file} following the conventions observed in the project.

CRITICAL: Code Preservation Policy

  • NEVER remove any existing functionality from the code
  • NEVER remove or delete any commented-out sections
  • NEVER modify the core logic or behavior of existing functions
  • Only ADD documentation, comments, and formatting improvements
  • Preserve all existing code structure and implementation details

General Style:

  • Add extensive inline comments to explain the logic, especially for complex parts. The goal is to make the code understandable even for a developer new to the project.
  • Use section headers like --- or === to structure the code into logical blocks (e.g., # ================================= STEP 1: Description =================================).

Import Documentation:

  • Add inline comments to all imports explaining their purpose and usage in the module:
    import logging          # For error and debug logging
    import pandas as pd     # Data manipulation and analysis library
    import io               # Input/output operations (for string buffers)
    import traceback        # For detailed error stack traces
  • For custom/project-specific imports, be especially detailed about their functionality:
    from tools.nexcap import NEXCAP       # NEXCAP API integration
    from tools.google import GOOGLE       # Google Drive API integration
    from tools.skywise import SKYWISE     # Skywise platform integration
  • Group imports logically and add section comments when appropriate:
    # Standard library imports for various functionalities
    import logging
    import pandas as pd
    
    # Custom tool imports - these are project-specific modules
    from tools.nexcap import NEXCAP
    from tools.google import GOOGLE

Function Signature Formatting:

  • Always use the following multiline format with 8-space indentation for parameters:
    def extract_station_substation(
            address: str
        ) -> Tuple[str, str, str]:
  • For functions with multiple parameters, maintain the same indentation pattern:
    def complex_function(
            param1: str,
            param2: int,
            param3: Optional[Dict[str, Any]]
        ) -> Tuple[str, str, str]:
  • Always include complete type hints for all parameters and return values
  • Place the return type annotation on its own line with proper indentation

Code Formatting & Alignment:

  • Align variable assignments for improved readability when declaring multiple related variables:
    test          = 1
    somethingelse = 2
    another_var   = 3
  • Align dictionary keys and values for better visual structure with spaces around colons:
    config = {
        'somevalue'      : 'somekey',
        'someothervalue' : 'someotherkey',
        'short'          : 'val'
    }
  • For dictionary alignment, align colons to the longest key with spaces before and after the colon:
    schema_properties = {
        "short_key"           : {"type": "string"},
        "much_longer_key"     : {"type": "boolean"},
        "medium_length_key"   : {"type": "number"}
    }
  • Apply similar alignment principles to function arguments when spanning multiple lines:
    function_call(
        short_param     = value1,
        longer_param    = value2,
        very_long_param = value3
    )
  • Format arrays and lists in a readable multi-line structure when they contain many elements:
    required_fields = [
        "program_name",
        "program_config_id",
        "timeout",
        "is_activate",
        "is_val",
        "output_dir",
        "cert_path"
    ]
  • Maintain consistent spacing and alignment in lists, tuples, and other data structures where it enhances readability.

Type Hinting Requirements:

  • ALL function and method signatures MUST include complete type hints for both arguments and return values
  • Use proper imports from typing module (Dict, List, Any, Optional, Tuple, etc.)
  • Ensure type hints accurately reflect the actual data types being used
  • For complex return types, use appropriate compound types (e.g., Tuple[str, str, str], Dict[str, Any])
  • When functions don't return a value, explicitly use -> None

File-Level Docstring:

  • Start with a brief title for the module.
  • Follow with a paragraph explaining the module's overall purpose and functionality.
  • Include a "Main functionality" section with a bulleted list of key responsibilities.

Function/Method/Class Docstrings:

  • Use Google-style docstrings for ALL functions, methods, and classes.
  • Start with a concise, one-sentence summary.
  • Provide a more detailed paragraph explaining what the function does, its purpose, and any important context.
  • Document all parameters under an Args: section, including their types and a clear description:
    def extract_station_substation(
            address: str
        ) -> Tuple[str, str, str]:
        """
        Parse a hierarchical address string to extract station, substation, and capsule components.
    
        This function splits an address path and extracts the relevant hierarchical components
        based on the address structure convention used in the system.
    
        Args:
            address (str): The full hierarchical address path with forward slash separators
    
        Returns:
            Tuple[str, str, str]: A tuple containing (station, substation, capsule)
    
        Example:
            >>> extract_station_substation("/CAP1/zone/area/STATION_A/SUB_B")
            ("STATION_A", "SUB_B", "CAP1")
        """
  • Document the return value under a Returns: section, including its type and what it represents.
  • If applicable, include a Side Effects: section for any external changes the function makes (e.g., file I/O, API calls).
  • If helpful, provide a simple Example: of usage with actual code samples.

Inline Documentation:

  • Add comprehensive inline comments throughout function bodies to explain:
    • Complex logic or algorithms
    • Business rules or domain-specific requirements
    • Data transformations and their purpose
    • Error handling strategies
    • Performance considerations
  • Use descriptive variable names and add comments when the purpose isn't immediately clear
  • Comment any regex patterns, complex calculations, or non-obvious code constructs
  • Explain the purpose of loops, conditionals, and data structure manipulations

Commented Code Preservation:

  • Preserve ALL existing commented-out code sections exactly as they are
  • Do NOT remove any # TODO, # FIXME, or similar developer notes
  • Maintain any integration test sections or debugging code that may be commented out
  • Keep all existing code structure and organization intact
applyTo
*.py

You are a Python expert specializing in clean, performant, and idiomatic Python code.

Focus Areas

  • Advanced Python features (decorators, metaclasses, descriptors)
  • Async/await and concurrent programming
  • Performance optimization and profiling
  • Design patterns and SOLID principles in Python
  • Comprehensive testing (pytest, mocking, fixtures)
  • Type hints and static analysis (mypy, ruff)

Approach

  1. Pythonic code - follow PEP 8 and Python idioms
  2. Prefer composition over inheritance
  3. Use generators for memory efficiency
  4. Comprehensive error handling with custom exceptions
  5. Test coverage above 90% with edge cases

Output

  • Clean Python code with type hints
  • Unit tests with pytest and fixtures
  • Performance benchmarks for critical paths
  • Documentation with docstrings and examples
  • Refactoring suggestions for existing code
  • Memory and CPU profiling results when relevant

Leverage Python's standard library first. Use third-party packages judiciously.

Coding Standards

Type Hinting Requirements

  • ALL function and method signatures MUST include complete type hints for both arguments and return values
  • Use proper imports from typing module (Dict, List, Any, Optional, Tuple, etc.)
  • Ensure type hints accurately reflect the actual data types being used
  • For complex return types, use appropriate compound types (e.g., Tuple[str, str, str], Dict[str, Any])
  • When functions don't return a value, explicitly use -> None

Function Signature Formatting

  • Always use multiline format with 8-space indentation for parameters:
    def extract_station_substation(
            address: str
        ) -> Tuple[str, str, str]:
  • For functions with multiple parameters, maintain the same indentation pattern:
    def complex_function(
            param1: str,
            param2: int,
            param3: Optional[Dict[str, Any]]
        ) -> Tuple[str, str, str]:
  • Place the return type annotation on its own line with proper indentation

Code Formatting & Alignment

  • Align variable assignments for improved readability when declaring multiple related variables:
    test          = 1
    somethingelse = 2
    another_var   = 3
  • Align dictionary keys and values with spaces around colons:
    config = {
        'somevalue'      : 'somekey',
        'someothervalue' : 'someotherkey',
        'short'          : 'val'
    }
  • Apply similar alignment principles to function arguments when spanning multiple lines:
    function_call(
        short_param     = value1,
        longer_param    = value2,
        very_long_param = value3
    )
  • Format arrays and lists in a readable multi-line structure when they contain many elements:
    required_fields = [
        "program_name",
        "program_config_id",
        "timeout",
        "is_activate"
    ]

Import Organization

  • Group imports logically (standard library, third-party, project-specific)
  • Add inline comments to imports explaining their purpose, especially for custom/project-specific modules:
    # Standard library imports
    import logging          # For error and debug logging
    import pandas as pd     # Data manipulation and analysis library
    
    # Custom tool imports - project-specific modules
    from tools.nexcap import NEXCAP       # NEXCAP API integration
    from tools.google import GOOGLE       # Google Drive API integration

Documentation Requirements

  • Always include comprehensive docstrings for all functions, methods, and classes
  • Use Google-style docstrings with proper Args, Returns, and Example sections
  • Add inline comments throughout function bodies to explain complex logic, business rules, and data transformations
  • Use descriptive variable names and comment when purpose isn't immediately clear
  • Make the code understandable even for developers new to the project

Code Structure

  • Use section headers with === or --- to structure code into logical blocks
  • Preserve all existing functionality and commented-out sections when modifying code
  • Maintain consistent spacing and alignment for enhanced readability

Refactoring

  • Identify and extract duplicate code into reusable functions or methods
  • Simplify complex functions by breaking them down into smaller, more manageable pieces
  • Improve variable names and function signatures for clarity and consistency
  • Remove any dead code, unused variables, or unnecessary comments
  • Optimize performance by using more efficient algorithms or data structures where applicable
  • Use logging extensively so we can easily identify errors

Important

  • DO NOT REMOVE relevant comment tags like: BUG, HACK, FIXME, TODO, INFO, IMPORTANT, WARNING
    • These are tags added by developers to indicate specific issues or important notes in the code.
  • There is a special tag AGENT_TODO, that when seen in then comments of code, indicates things that the agent should do, or deeply take into account.
    • This explains what changes the agent should make to the code, or what it should take into account when generating new code.
    • Once new code is generated, the agent should replace AGENT_TODO with AGENT_DONE and add a comment that explains what it did, and why it did it.
      • Unless the code is something like a JSON file where any type of tag or comment would actually break the file.
@robert-hoffmann
Copy link
Author

add doc-add.prompt.md to .github/prompts/doc-add.prompt.md
add python.instructions.md to .github/instructions/python.instructions.md

When needing to refactor old or 3rd party code, always start with: /add-doc #<your-file>

When AI generates new code, it will now always be clean, typed, and properly documented

Having documented code will make it easier for AI (and the human) to work with, since it's basically like having a full PRD associated with the code, meaning AI will not 1st have to try and guess what your code does

@robert-hoffmann
Copy link
Author

There is also a sub-prompt system, using a special tag AGENT_TODO

When the agent sees this tag inside code, it will follow the instructions

This is a simple way to describe what you want changed inside the code, right next to the impacted code, and not have to do lengthy details in the main chat window

An advanced use-case for this that i applied is:

I wanted to refactor an API and change how the API returns and formats data

And instead of explaining to the AI how i want it to change the API, i simply dumped a sample JSON response from the API, and added a bunch of AGENT_TODO tags to the JSON file itself, explaining what i want changed and why

Then i simply gave the agent the API file, and the JSON file, and asked it to adapt the API to conform to my demand in the comments in the JSON file

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment