211-python-clean-code

A rule set for writing maintainable Python, with extra guidance for data-analysis code. It covers formatting, type hints, documentation, validation, logging, errors, and secret handling.

In plain words
What is it for?
Use it when creating or reviewing Python functions that transform data, document their behavior, handle failures, or connect to outside services.
Why use it?
It gives consistent standards for Python code and reduces common maintenance, debugging, and security problems.

Cursor rule

Install

Getting it into your agent

One page per mod, every tool's command on it. A separate URL per tool would split the same page into five that compete with each other.

agentmods
npx agentmods add rules/hamzaamjad/cursor-rules/211-python-clean-code
Clone the repo
git clone --depth 1 https://github.com/hamzaamjad/cursor-rules
Per session 0 Nothing until a file matches its globs; then the whole rule loads.
When invoked 1,089 The whole file, excluding the scripts and references it only reads on demand.
Security scan A 0 findings. Scan, not verified.
Origin original No closer match found in the catalogue.
Token cost

What it costs to keep this loaded

Counted locally with the o200k_base tokenizer, which is exact for GPT models; Claude uses its own tokenizer and its counts differ. Treat this as one consistent yardstick across the catalogue rather than a bill. Prices are per million input tokens.

ModelPer sessionOnce invoked
Fable 5 $0.00000 $0.01089
Opus 5 $0.00000 $0.00544
Sonnet 5 $0.00000 $0.00218
Haiku 4.5 $0.00000 $0.00109

Measured yesterday against content hash 5dcba0e1c4f4, method: parsed. Prices are Anthropic first-party input rates as of 2026-08-30, from the pricing page.

Security

Grade A, and why

211-python-clean-code scanned grade A with 0 findings against 26 rules in 11 categories — prompt injection, anti-refusal, data exfiltration, privilege escalation, supply chain, agent snooping, system-prompt leakage, SSRF and excessive agency — measured yesterday.

A static scan of the body, not an audit. Every finding is printed with the line that produced it so you can judge whether it matters here. A mod is markdown that instructs an agent; that is exactly why what it instructs is worth reading.

Nothing flagged

None of the 26 patterns this scan looks for appear in this file: no shell pipes, no recursive deletes, no credential paths, no hidden text, no instruction-override or anti-refusal phrasing, no agent-config snooping. That is not a guarantee, it is the absence of the things that are checkable.

rules/200-domain/211-python-clean-code.mdc · 108 lines

How it starts

The opening of the file, as written. The whole thing — 108 lines — stays where its author put it; the contents beside it link to each section on GitHub.

python-clean-code.mdc

  • Purpose: Ensure maintainable, consistent, and robust Python code, with special emphasis on data analytics workflows. Research shows: Clean code practices reduce maintenance time by 40-60% and bug density by 15-50% (Martin, 2008).

  • General Python Standards:

    • Conform to PEP 8; enforce with Black/flake8 and pre-commit hooks.
    • Use type hints for all public functions/methods; validate with mypy.
    • Document each function with a one-sentence summary and Google-style Args/Returns/Raises.
    • Use the logging module (structured logs); avoid print for diagnostics.
    • Validate inputs; raise specific exceptions. Wrap external calls in try/except, log context.
    • No plaintext secrets or credentials—use environment variables or a secrets manager.
    • Prefer explicit imports; avoid wildcard (*) imports.
    • Respect a max line length of 88 characters (Black standard).
    • Cognitive Load Optimization: Keep functions under 20 lines (CLT index <0.6)
    • Chain of Code Pattern: Include executable examples in docstrings for complex logic
  • Data Analytics Specific Patterns:

    1. Data Transformation Functions:

      • Include explicit input validation for required columns
      • Use proper data types (e.g., datetime for date fields, not strings)
      • Handle null values explicitly and document handling strategy
      • Implement defensive copying to prevent unintended mutations
      • Add logging at appropriate points in the transformation process
      • Example pattern:
        def transform_revenue_data(df: pd.DataFrame) -> pd.DataFrame:
            """Transform revenue data for analysis.
            
            Args:
                df: DataFrame containing raw revenue data
                    Required columns: ['date', 'customer_id', 'amount']
                    
            Returns:
                DataFrame with transformed data and additional metrics
                
            Raises:
                ValueError: If required columns are missing
            """
            # Validate input
            required_cols = ['date', 'customer_id', 'amount']
            if not all(col in df.columns for col in required_cols):
                raise ValueError(f"Missing required columns. Required: {required_cols}")
                
            # Convert date to datetime if needed
            if not pd.api.types.is_datetime64_any_dtype(df['date']):
                df['date'] = pd.to_datetime(df['date'])
                
            # Add calculated columns
            result = df.copy()  # Defensive copy
            result['month'] = result['date'].dt.to_period('M')
            
            # Log transformation details
            logger.info(f"Transformed revenue data shape: {result.shape}")
            
            return result
        
    2. Performance Best Practices:

      • Use vectorized operations instead of loops for pandas operations
      • Avoid multiple GroupBy operations on the same dimensions
      • Implement chunking for large dataset operations
      • Consider memory usage for large transformations
      • Use appropriate indexes for database operations
      • Tree of Thoughts Optimization: For complex transformations, prototype 3 approaches:
        # Approach 1: Direct vectorization
        df['metric'] = df['value'] * df['weight']
        
        # Approach 2: Apply with caching
        @lru_cache(maxsize=1000)
        def compute_metric(value, weight): 
            return value * weight
        df['metric'] = df.apply(lambda x: compute_metric(x['value'], x['weight']), axis=1)
        
        # Approach 3: Numpy operations
        df['metric'] = np.multiply(df['value'].values, df['weight'].values)
        
        # Benchmark and select best (typically 15-30% performance gain)
        

Read the full file on GitHub · 108 lines

Changes

What this file has done since we first saw it

Hashed on every crawl. A supply-chain change to an agent config is a question of when, not whether, so the history is kept rather than the latest state alone.

  1. yesterday First seen · 108 lines · 0 tokens per session scan A 5dcba0e1c4f4

Subscribe to this mod's changes

211-python-clean-code is a cursor rule published in the GitHub repository hamzaamjad/cursor-rules (2 stars, last pushed 1y ago), licensed MIT. It costs nothing until one of its globs matches a file; then it loads 1,089 tokens. A static security scan graded it A with 0 findings. No closer match exists in the catalogue, so it is treated as the original; first seen 2026-08-31.