---
name: python-coding
description: Use for implementing Python code with a strict standard for correctness, clarity, safety, testability, and maintainability. This skill encodes a comprehensive Python coding doctrine for autonomous agents.
---
## Purpose

This skill defines a self-sufficient Python coding standard for an autonomous agent. It exists to enforce strong Python engineering principles without any dependency on user questioning, clarification loops, feedback prompts, or conversational behavior. The document is intentionally limited to Python coding principles, implementation discipline, structural quality, safety, and maintainability.

## Core operating model

The agent operates by interpreting the task, deriving a workable implementation model, and executing against that model using sound Python engineering judgment. The skill does not instruct the agent to ask questions, request clarification, solicit feedback, or negotiate requirements. When information is incomplete, the agent should adopt conservative, explicit, internally consistent assumptions and continue toward the most robust reasonable solution.

The objective is not conversational helpfulness. The objective is correct, readable, testable, maintainable Python code.

## Primary priorities

The priority order is:

1. correctness;
2. clarity;
3. reliability;
4. safety;
5. testability;
6. maintainability;
7. performance;
8. extensibility.

If tradeoffs appear, the preferred solution is the one that remains easiest to understand, validate, and safely modify.

## Scope of the skill

This skill covers:

- Python scripts;
- application modules;
- command-line tools;
- services and background workers;
- file processing;
- API integration;
- refactoring;
- bug fixing;
- code hardening;
- automated test creation.

This skill is not a product management policy, communication framework, or feedback protocol. It is a pure coding doctrine.

## Task interpretation principles

### Derive a concrete execution model

Every task must be translated internally into:

- expected inputs;
- expected outputs;
- constraints;
- operational environment;
- failure modes;
- data transformation steps;
- validation requirements.

If details are missing, the agent should infer the narrowest reasonable interpretation that allows a safe and coherent implementation.

### Default assumption policy

When requirements are underspecified, default to the following unless the task clearly implies otherwise:

- use Python 3.11+ compatible syntax where practical;
- prefer standard library first;
- prefer simple module structure over abstraction-heavy design;
- prefer deterministic behavior over implicit magic;
- prefer explicit validation over permissive parsing;
- prefer synchronous code unless concurrency materially improves the result;
- prefer filesystem-safe, network-safe, and failure-aware behavior.

### Internal decomposition

Every non-trivial task should be internally decomposed into:

1. data boundaries;
2. transformation logic;
3. side effects;
4. error paths;
5. tests;
6. usage surface.

The implementation should reflect this decomposition in code structure.

## Python design principles

### Readability over cleverness

Python code must prioritize readability over cleverness. Avoid compressed tricks, implicit behavior, obscure syntax stunts, and unnecessary indirection. Prefer code that another engineer can understand quickly without reconstructing hidden intent.

### Simplicity over premature abstraction

Do not introduce abstraction earlier than needed. Avoid speculative base classes, overly generic frameworks, unnecessary wrappers, and indirection layers that do not reduce real complexity.

### Functions before classes

Prefer functions unless the problem truly requires:

- shared state;
- lifecycle control;
- dependency encapsulation;
- domain object modeling;
- polymorphic behavior;
- extension through stable interfaces.

Classes must exist because they simplify the design, not because object orientation feels formal.

### Explicitness over hidden coupling

Inputs, outputs, dependencies, and side effects should be obvious from the code. Avoid hidden global state, import-time behavior, mutable module-level configuration, and spooky action across files.

## Code style rules

### General style

Code should follow idiomatic Python and align with PEP 8 expectations. It should be formatted consistently and structured so that logical sections are visually obvious.

### Naming

Use:

- `snake_case` for variables, functions, and modules;
- `PascalCase` for classes;
- `UPPER_CASE` for constants.

Names must express meaning and role. Avoid vague names like `data`, `item`, `obj`, `res`, or `temp` unless the scope is extremely local and obvious.

### Function size

Functions should stay focused. A function that performs multiple unrelated responsibilities should be split. A function should ideally have one clear reason to change.

### Nesting control

Prefer guard clauses and early returns over deep indentation. Control flow should remain easy to scan.

### Comments

Comments should explain non-obvious reasoning, domain constraints, protocol quirks, invariants, or intentional tradeoffs. Comments should never merely restate code line by line.

### Docstrings

Docstrings are appropriate for:

- public APIs;
- reusable modules;
- non-obvious logic boundaries;
- functions with important contracts;
- functions that may raise meaningful exceptions.

Docstrings should describe behavior, inputs, outputs, and significant failure conditions.

## Types and data modeling

### Type hints by default

Use type hints wherever practical. Types improve readability, editor assistance, safe refactoring, and contract clarity.

Type hints should be used for:

- public functions;
- complex internal functions;
- return values;
- collections with meaningful contained types;
- callback signatures when relevant.

### Data structures

Choose structures according to usage characteristics:

- `list` for ordered collections;
- `tuple` for fixed-structure records or immutable groups;
- `set` for membership testing and uniqueness;
- `dict` for keyed lookup;
- `deque` for queue-like edge operations;
- `dataclass` for lightweight structured records;
- `pydantic` models when validation and serialization are central.

### Data contracts

External data must be normalized into explicit internal structures as early as possible. Raw dictionaries should not leak deeply through the codebase when a stronger structure would clarify behavior.

## Module and project structure

### Separation of concerns

Separate:

- domain logic;
- I/O;
- configuration;
- integration code;
- command entry points;
- tests.

Pure logic should remain isolated from filesystem, network, database, and shell behavior whenever possible.

### File organization

Avoid monolithic files when the codebase exceeds trivial size. Prefer structure such as:

- `main.py` or `cli.py` for execution entry;
- `config.py` for configuration loading;
- `models.py` or `models/` for data contracts;
- `services/` for business logic;
- `adapters/` or `clients/` for external integrations;
- `utils/` only for genuinely reusable, low-level helpers;
- `tests/` for automated tests.

### Dependency direction

Higher-level orchestration may depend on lower-level utilities, but low-level reusable modules should not depend on application entrypoints or CLI concerns.

## Error handling principles

### Raise precise exceptions

Do not use bare `except:`. Catch only the errors that are expected and meaningfully handled.

### Preserve failure meaning

Exceptions should communicate real failure causes. Do not erase useful debugging information with vague fallback behavior.

### Fail clearly

If recovery is not valid, fail explicitly. Silent fallback behavior is only acceptable when it is intentionally safe and consistent with the system’s goals.

### Validate boundaries early

Validate external input close to the system boundary. Invalid states should be prevented early rather than allowed to spread through deeper layers.

### Use logging intentionally

Use `logging` for operational visibility. Logs should:

- add context;
- avoid secrets;
- distinguish severity levels;
- support diagnosis of failures and flow.

`print()` is not a substitute for application logging outside throwaway scripts.

## Input validation and safety

All external input is untrusted. This includes:

- command-line arguments;
- environment variables;
- file contents;
- HTTP responses;
- API payloads;
- database results;
- user-generated text;
- third-party data.

The agent should validate type, format, required fields, structural assumptions, and known constraints before relying on such input.

## Security rules

### Forbidden or heavily restricted patterns

Avoid unless the task explicitly requires and justifies them:

- `eval()`;
- `exec()`;
- unsafe deserialization;
- shell command construction with untrusted input;
- dynamic import tricks without clear need;
- logging secrets or tokens;
- hardcoded credentials.

### Filesystem safety

Use safe path handling, preferably via `pathlib`. Avoid path traversal risks, accidental overwrite behavior, and blind trust in relative paths from untrusted sources.

### Network safety

HTTP clients should use:

- explicit timeouts;
- response validation;
- failure handling;
- authentication hygiene;
- careful retry logic only for retry-safe operations.

### Dependency hygiene

Prefer fewer dependencies. Every external library adds maintenance, supply-chain, and compatibility risk. Choose mature, well-scoped libraries and avoid unnecessary ecosystem sprawl.

## Testing doctrine

### Testability as a design requirement

Code should be structured so core logic can be tested independently from side effects. Tight coupling between logic and I/O should be treated as a design flaw.

### Pytest as default

Use `pytest` as the default testing framework unless a project already uses another established standard.

### Minimum test coverage intent

Tests should cover:

- expected successful behavior;
- invalid input;
- edge conditions;
- failure behavior;
- regression cases for known bugs.

### Behavior over internals

Tests should validate behavior and externally relevant contracts rather than internal implementation trivia.

### Determinism

Tests should avoid flakiness. Control time, randomness, filesystem state, and network effects through isolation, fixtures, mocks, or dependency injection where needed.

## Performance principles

### Correctness first

Never trade correctness for performance without a compelling reason.

### Measure before optimizing

Use profiling or measurement before introducing complexity for speed.

### Eliminate obvious waste

Avoid:

- repeated expensive work in loops;
- loading huge datasets unnecessarily;
- duplicate parsing;
- redundant file access;
- repeated network calls that can be safely consolidated.

### Use streaming when appropriate

For large files or datasets, prefer iteration, generators, or chunked processing when full in-memory loading is unnecessary.

## Concurrency and asynchrony

Use asynchronous or concurrent execution only when the workload benefits materially from it. Simpler synchronous code is preferred unless concurrency clearly improves throughput, responsiveness, or latency.

If asynchronous code is used:

- keep async boundaries explicit;
- use async-compatible libraries consistently;
- manage cancellation and timeouts deliberately;
- avoid mixing sync and async code chaotically.

## Refactoring standard

Refactoring must preserve behavior while improving structure. The preferred refactoring sequence is:

1. preserve or add tests;
2. isolate responsibilities;
3. rename for clarity;
4. remove duplication;
5. simplify control flow;
6. reduce function size;
7. delete dead code;
8. improve boundaries around I/O and dependencies.

Refactoring is not cosmetic. It is structural risk reduction.

## Code generation quality bar

Any generated Python code must be:

- syntactically valid;
- internally coherent;
- appropriately modular;
- aligned with the task’s likely runtime context;
- free from obvious dead code;
- free from obviously unused imports unless illustrative value requires them;
- explicit in failure handling where failure matters;
- stable enough for extension.

## Preferred implementation defaults

Unless the task strongly suggests otherwise, prefer:

- `pathlib` over stringly-typed path handling;
- `logging` over `print()` in non-trivial programs;
- `dataclass` for simple structured records;
- `httpx` or `requests` with timeouts for HTTP work;
- `pytest` for tests;
- standard library utilities before external packages;
- context managers for files, locks, and resource ownership;
- explicit encoding declarations for text file I/O.

## Anti-patterns

Avoid these patterns:

- giant all-purpose functions;
- hidden mutable global state;
- excessive inheritance;
- speculative abstraction;
- silent exception swallowing;
- magic constants with no naming;
- copy-paste duplication;
- overuse of utility modules as dumping grounds;
- mixed business logic and side effects in the same layer;
- permissive parsing that masks bad input;
- “clever” comprehensions that reduce readability;
- network calls or database access buried in unrelated helper functions.

## Autonomous execution principle

This skill assumes the agent is capable of independent execution once the task exists. Therefore the skill must not encode behavior such as:

- asking the user for clarification;
- requesting feedback;
- pausing for approval;
- proposing discussion loops;
- optimizing for conversational reassurance;
- emitting interpersonal process language.

The only concern of this skill is disciplined Python engineering.

## Final doctrine

The Python coder skill is a strict implementation standard for autonomous coding work. It should consistently produce Python solutions that are correct, explicit, testable, safe, and maintainable. It should reduce ambiguity through structure, reduce risk through validation and tests, and reduce long-term cost through clarity and sound boundaries.
