Python Foundational
MicrosoftOfficialPublished by Microsoft
- Skill
- Guidelines
- Software development
- MIT
- No issues found
AutoGineer summary
Written by AutoGineer from the skill’s own files, not by the author
The python-foundational skill provides a core checklist of best practices for Python development. It covers naming conventions, import organization, Pythonic idioms, function and class design, type safety, error handling, and architectural principles. Designed to be loaded automatically for Python changes, it serves as a baseline for maintaining readable, maintainable, and robust codebases by establishing shared expectations for code structure and design.
What it does
- Defines standard naming conventions for classes, functions, variables, and constants.
- Provides guidelines for organizing imports and using Pythonic idioms like comprehensions and context managers.
- Establishes requirements for type hinting and documentation via docstrings.
- Outlines principles for error handling, such as raising specific exceptions and avoiding bare except clauses.
- Promotes design principles like DRY (Don't Repeat Yourself) and simplicity-first development.
- Offers a severity rubric to help distinguish between runtime issues and maintainability improvements.
When to use it
- During code reviews to ensure new Python code aligns with project standards.
- When establishing a baseline for Python code quality in a new or existing repository.
- To provide consistent guidance on Pythonic patterns and anti-patterns.
- When refactoring code to improve maintainability and adherence to design principles.
Advantages
- Promotes consistency across the codebase by providing a unified set of standards.
- Reduces maintenance overhead by encouraging self-documenting code and shared helpers.
- Helps catch potential issues early through type safety and robust error handling practices.
- Prevents premature complexity by advocating for simple, direct implementations.
Usage examples
- “Review this Python function for adherence to foundational standards.”
- The agent evaluates the function against the checklist, checking for proper naming, type hints, docstrings, and error handling, providing feedback based on the severity rubric.
- “Does this code follow the DRY principle?”
- The agent analyzes the logic for duplication and suggests extracting repeated code into a shared helper function if applicable.
- “How should I structure my imports in this module?”
- The agent provides the standard three-tier grouping pattern: standard library, third-party packages, and local project imports.
- “Is this use of a mutable default argument acceptable?”
- The agent flags the use of mutable defaults as an anti-pattern and suggests a safer alternative, such as using None as a default.
Install
Download the skill as a ZIP:
https://mp-staging.autogineer.com/agent-skills/microsoft/python-foundational/downloadUnzip it into the cross-client skills folder of your project:
mkdir -p .agents/skills && unzip python-foundational.zip -d .agents/skills
Documentation by Microsoft
Python Foundational Coding Standards Skill
Overview
Foundational Python excellence that every diff must satisfy. This skill is loaded first for any .py change. All higher-order skills build on it.
This content is a skill rather than an instructions file for three reasons: skills are distributed through the CLI plugin and VS Code extension without requiring consumers to copy files into their repo; new language skills can be added without modifying the review agent itself; and skills are loaded on demand, keeping the context window small when the diff contains no Python.
Core Checklist
1. Readability & Style
Use Python naming:
PascalCaseclasses,snake_casefunctions/variables,UPPER_SNAKE_CASEconstants,_private members.Group imports: stdlib → third-party → local (blank line between groups, no trailing whitespace).
2. Pythonic Idioms
Prefer comprehensions for simple transforms; use explicit loops for complex logic/side-effects.
Always use
withfor files, locks, DB connections.Prefer
dataclass/NamedTuple/Enumfor data holders.Use
pathliboveros.path; timezone-awaredatetimewhen relevant.Use
*keyword-only arguments for multi-optional functions.Never use mutable defaults or
global/nonlocalunless strictly required.
3. Function & Class Design
Keep functions small and single-responsibility.
Add docstrings to all public APIs (follow repo style).
Document unavoidable side-effects.
Follow codebase’s class-member ordering (if defined).
4. Type Safety Foundations
Add type hints to all public APIs, module vars, and class attributes.
Use PEP 695 (3.12+) or
TypeVarfor generics.Avoid
Anyexcept in thin wrappers.
5. Error Handling
Raise specific exceptions; never bare
except:(broadexcept Exception:only at app boundaries with logging).No silent failures or generic error messages.
Provide context, expected state, and guidance in every exception.
6. Anti-Patterns to Avoid
Never use
eval,exec, orpickleon untrusted data.Never hard-code secrets.
7. Maintainability
Prefer self-documenting code; comments only for "why".
Use structured logging instead of
print.Flag overly long/complex functions that resist testing.
8. Architectural Fit
Align with existing patterns; do not re-implement shared functionality or bypass established layers.
Place code in the correct module/package.
9. Design Principles
Eliminate duplication: extract repeated logic into a shared helper so fixes propagate automatically.
Prefer the simplest implementation that satisfies current requirements. Introduce abstractions only when a second concrete use case appears.
Limit change breadth: every modified line should trace to the stated purpose of the change.
Before flagging seemingly unused code, verify it is not a protocol implementation, framework hook, public API, or entry point invoked externally.
Match solution complexity to problem complexity. A duplicated function warrants a shared helper, not an event-driven architecture.
References
| File | Covers | Purpose |
|---|---|---|
| design-principles.md | Section 9 | Rationale and examples for the design principles |
| code-style-patterns.md | Sections 1–5 | Concrete code examples for style, idioms, type safety, class design, and error handling |
Severity Rubric
| Severity | Definition |
|---|---|
| High | Causes incorrect behavior, data loss, or security exposure at runtime |
| Medium | Degrades maintainability, readability, or violates a project convention with no immediate runtime impact |
| Low | Cosmetic, stylistic, or minor improvement opportunity |
Troubleshooting
| Symptom | Check |
|---|---|
| Skill not loaded | Confirm the diff contains .py files. The agent selects skills by matching file types in the changed files against skill descriptions. |
| No findings generated | Verify the Skills Loaded footer in the review output lists python-foundational. If listed but no findings appear, the diff may already satisfy the checklist. |
| Severity seems miscalibrated | Compare against the Severity Rubric above. High requires runtime impact; medium is maintainability-only. |
Contributing
Follow these conventions when extending this skill:
Checklist items belong in SKILL.md. Each bullet is a single, actionable check an agent or reviewer can apply to a diff. Keep bullets concise: one sentence, no code.
Reference files live in
references/and provide examples or rationale for the covered checklist items. Each reference file covers a contiguous range of sections. Update the References table when adding a new file.Before adding a new checklist item, confirm it does not duplicate an existing bullet in any section. Place it in the section that matches its primary concern. If it spans concerns, prefer the more specific section.
Name new reference files after the topic they cover (e.g.,
async-patterns.md). Include a frontmatterdescriptionthat states which sections the file supports. Add a row to the References table in SKILL.md.Checklist items and examples must be portable across codebases. Use generic module names and describe anti-patterns by their behavior, not by specific directory or file names.
Files
- ATTRIBUTION.mdAdded by AutoGineer851 B
- LICENSELicence file added by AutoGineer1.1 KiB
- SKILL.md6.6 KiB
- references/code-style-patterns.md6.6 KiB
- references/design-principles.md4.0 KiB
references/code-style-patterns.md
title: Code Style Patterns description: Concrete before/after examples for Sections 1 through 5 of the python-foundational skill checklist author: microsoft/hve-core ms.date: 2026-10-13 ms.topic: reference keywords:
python
coding-standards
code-patterns estimated_reading_time: 4
Code Style Patterns
Concrete before/after examples for Sections 1–5 of the python-foundational skill checklist.
Naming Conventions
Python naming conventions remove ambiguity.
# Classes: PascalCase
class ModelTrainer:
pass
# Functions and variables: snake_case
def train_model():
training_data = []
# Constants: UPPER_SNAKE_CASE
MAX_SEQUENCE_LENGTH = 2048
DEFAULT_LEARNING_RATE = 1e-4
# Private members: leading underscore
def _internal_helper():
pass
_internal_cache = {}Import Organization
The three-tier grouping makes dependency boundaries visible at a glance: what comes from the standard library, what comes from third-party packages, and what is local to the project.
# 1. Standard library
import os
import sys
from pathlib import Path
# 2. Third-party
import numpy as np
from anthropic import Anthropic
# 3. Local
from myproject.core.trainer import Trainer
from myproject.utils.config import load_configKeyword-Only Arguments
The * separator forces callers to name optional parameters, preventing silent positional misassignment when a function has multiple options of the same type.
Before
def train(data: list, learning_rate: float = 1e-4, batch_size: int = 32):
pass
# Caller can silently swap learning_rate and batch_size
train(data, 32, 1e-4)After
def train(
data: list,
*,
learning_rate: float = 1e-4,
batch_size: int = 32,
) -> None:
pass
# Caller must name each optional parameter
train(data, learning_rate=1e-3, batch_size=64)Type Hints
Type annotations turn implicit assumptions into machine-checkable contracts, catching mismatched types before runtime and enabling richer IDE support.
Function Signatures
def fetch_records(
query: str,
*,
limit: int = 100,
include_deleted: bool = False,
) -> list[dict[str, str]]:
"""Fetch records matching a query."""
...
def find_user(user_id: int) -> User | None:
"""Return the user or None if not found."""
...Dataclass with Typed Attributes
from dataclasses import dataclass, field
from typing import ClassVar
@dataclass
class TrainingConfig:
"""Configuration for a training run."""
model_name: str
learning_rate: float = 1e-4
batch_size: int = 32
tags: list[str] = field(default_factory=list)
MAX_EPOCHS: ClassVar[int] = 100Docstrings
Docstrings capture intent and contracts that code alone cannot express: parameter constraints, exception triggers, and return semantics. Consistent docstrings across a project also power IDE tooltips and automated documentation generators.
Function Docstring
def process_data(
data: list[dict],
*,
batch_size: int = 32,
validate: bool = True,
) -> ProcessResult:
"""Process data with validation and batching.
Args:
data: Input data as list of dicts with 'id' and 'content' keys.
batch_size: Number of items to process per batch.
validate: Whether to validate input data.
Returns:
ProcessResult containing processed items, errors, and metrics.
Raises:
ValueError: If data is empty or has an invalid format.
"""Class Docstring
class DataProcessor:
"""Data processing orchestrator for batch operations.
Handles the complete data processing workflow including validation,
transformation, batching, and error handling.
Args:
config: Processing configuration.
batch_size: Number of items per batch.
Attributes:
config: Processing configuration.
batch_size: Configured batch size.
metrics: Processing metrics tracker.
"""
def __init__(self, config: APIConfig, *, batch_size: int = 32) -> None:
self.config = config
self.batch_size = batch_size
self.metrics = MetricsTracker()Error Messages
Generic error messages force the caller to reproduce the failure, attach a debugger, and walk the call stack just to understand what went wrong. A specific message surfaces the root cause immediately and cuts debugging time.
Before
def load_config(path):
if not path.exists():
raise FileNotFoundError("File not found")After
def load_config(path: Path) -> dict:
"""Load configuration file."""
if not path.exists():
raise FileNotFoundError(
f"Config file not found: {path}\n"
f"Expected YAML file with keys: model, data, training\n"
f"See example: docs/examples/config.yaml"
)
try:
with open(path) as f:
return yaml.safe_load(f)
except yaml.YAMLError as e:
raise ValueError(
f"Invalid YAML in config file: {path}\n"
f"Error: {e}"
) from eCustom Exception Hierarchies
In applications with multiple error categories, a base application exception enables callers to catch broad or narrow as needed. Derive specific exceptions from it rather than raising bare Exception or ValueError for domain-specific errors.
class AppError(Exception):
"""Base exception for the application."""
class ConfigError(AppError):
"""Configuration error."""
class ValidationError(AppError):
"""Validation error."""
def validate_config(config: dict) -> None:
"""Validate configuration."""
required = ["database", "api_key", "settings"]
missing = [k for k in required if k not in config]
if missing:
raise ConfigError(
f"Missing required config keys: {missing}\n"
f"Required: {required}"
)Class Member Organization
A suggested ordering convention that improves scanability. Follow the codebase's established convention when one exists.
class Model:
"""Model class."""
# 1. Class variables
DEFAULT_LR = 1e-4
# 2. __init__
def __init__(self, name: str) -> None:
self.name = name
# 3. Public methods
def train(self, data: list) -> None:
"""Public training method."""
pass
# 4. Private methods
def _prepare_data(self, data: list) -> list:
"""Private helper method."""
pass
# 5. Properties
@property
def num_parameters(self) -> int:
"""Number of trainable parameters."""
return sum(p.size for p in self.parameters())Requirements and compatibility
Written for: GitHub Copilot, Claude Code
Works with: Claude Code, Claude apps, OpenAI Codex, GitHub Copilot, Cursor, Gemini CLI, Kiro, OpenCode, Goose, Amp, Roo Code, JetBrains Junie, Factory Droid, Devin (ex-Windsurf), Mistral Vibe, OpenHands, Letta
“Works with” means the tool reads the open Agent Skills format; a skill written for one tool may use features others lack.
Needs: Claude Code frontmatter, Needs Python
Security
No issues found by our static scan· No issues found
A static scan is not a guarantee. Skills are third-party content: review a skill before you let an agent use it.
Attribution and licence
- Published by
- Microsoft
- Publisher
- Microsoft (Official)
- Source
- microsoft/hve-core · .github/skills/coding-standards/python-foundational · commit f425e94
- Licence
- MIT License (redistribution allowed)
- LICENSE (added by AutoGineer from LICENSE)
- ATTRIBUTION.md (written by AutoGineer)
- Synced
AutoGineer is not affiliated with or endorsed by Microsoft.
Download ZIP
The ZIP holds the skill’s files, its licence files and an ATTRIBUTION.md. Download python-foundational.zip