Agent skill

Python Rules

by softspark in softspark/ai-toolkit

Python coding rules: style, patterns, security, testing. An agent skill from softspark/ai-toolkit.

Apache-2.0Auto-check passedBackend & APIs

Install Python Rules

skills CLI
$ npx skills add softspark/ai-toolkit --skill python-rules -a claude-code

Project install by default; add -g for ~/.claude/skills/.

GitHub CLI
$ gh skill install softspark/ai-toolkit python-rules --agent claude-code

Project scope by default; add --scope user for a personal install. Needs GitHub CLI 2.90.0 or later (public preview).

Manual copy
$ git clone --depth 1 https://github.com/softspark/ai-toolkit.git skills-src && mkdir -p .claude/skills && cp -r skills-src/app/skills/python-rules .claude/skills/python-rules && rm -rf skills-src

Use ~/.claude/skills/ instead of .claude/skills for a personal install. The folder must contain SKILL.md.

Claude Code skills documentation · loads skills from .claude/skills/

Facts

Skill name
python-rules
GitHub stars
179
Token cost
~2.9k tokens
SKILL.md length
1,314 words
Files
1
Skills in repo
112
Repo updated
First seen
Licence
Apache-2.0

At a glance

Python coding rules: style, patterns, security, testing. An agent skill from softspark/ai-toolkit.

  • Tasks that involve Backend development
  • SKILL.md covers Type Hints, Naming, Functions and Imports, plus 21 more sections
  • Calls ruff and mypy; needs SECRET_KEY
  • Tasks that involve Type safety

What it does

Python Rules is an agent skill from softspark/ai-toolkit. Python coding rules: style, patterns, security, testing. Triggers: .py, .pyi, pyproject.toml, requirements.txt, Pipfile, FastAPI, Django, Flask, pytest, SQLAlchemy, ruff, mypy.

Its SKILL.md is about 2.9k tokens, which your agent loads only when the skill is triggered. It is a single SKILL.md file with no bundled scripts.

It sits in Backend & APIs, covering Backend development, Type safety and ORMs and data access. It works with Python, Django, FastAPI and SQLAlchemy. The repository describes itself as: Professional-grade AI coding toolkit: 94 skills, 44 agents, multi-platform (Claude, Cursor, Windsurf, Copilot, Gemini, Cline, Roo Code, Aider, Augment, Antigravity, Codex CLI… The licence is Apache-2.0.

When your agent uses it

  • Tasks that involve Backend development
  • Tasks that involve Type safety
  • Tasks that involve ORMs and data access

Example prompts

  • “/python-rules”

Requirements

  • Python 3
  • A credential in SECRET_KEY
  • Pre-approved tools (allowed-tools): Read

What it can do on your machine

Read from SKILL.md and the folder at commit d64db2b. It shows what the files ask for, not the result of running them.

  • Tool permissions

    Pre-approves these tools, so the agent can use them without asking each time:

    • Read

    From allowed-tools in the SKILL.md frontmatter.

  • Runs code

    Shell commands in SKILL.md call:

    • ruff
    • mypy

    From the folder's file list and the shell code blocks in SKILL.md.

  • Network

    No URLs in SKILL.md.

    From URLs in SKILL.md, links to its own repository left out.

  • Credentials

    Names these keys or tokens, usually read from environment variables:

    • SECRET_KEY

    From names ending in _API_KEY, _TOKEN, _SECRET, _KEY or _PASSWORD in SKILL.md.

Context cost

Python Rules loads about 2.9k tokens when it runs. Until then it costs about 47 tokens; SKILL.md has 1,314 words of instructions outside code blocks.

Always · name and description, kept in context so the agent knows when to use it
~47
When it runs · the whole SKILL.md, loaded when a task matches
~2.9k

Estimates: characters ÷ 4, the usual rule of thumb; real counts depend on the model's tokenizer. Scripts and assets cost tokens only if the agent reads them.

Safety

Auto-check passed

The automated check found no risky patterns in SKILL.md.

Automated static check — not a guarantee. Review scripts before installing. It scans the text of SKILL.md for risky patterns (piping downloads into a shell, reading credential files, hidden Unicode, destructive commands); files beside SKILL.md are not scanned.

SKILL.md

The full file from softspark/ai-toolkit at commit d64db2b, republished under its Apache-2.0 licence (© softspark). 1,314 words, ~2,886 tokens.

Download SKILL.mdSave it as .claude/skills/python-rules/SKILL.md (or your agent's skills folder).
name
python-rules
description
Python coding rules: style, patterns, security, testing. Triggers: .py, .pyi, pyproject.toml, requirements.txt, Pipfile, FastAPI, Django, Flask, pytest, SQLAlchemy, ruff, mypy.
allowed-tools
Read
effort
medium
user-invocable
false

Python Rules

These rules come from app/rules/python/ in ai-toolkit. They cover the project's standards for coding style, frameworks, patterns, security, and testing in Python. Apply them when writing or reviewing Python code.

Python Coding Style

Type Hints

  • Type all public function signatures (parameters + return).
  • Use str | None (PEP 604) over Optional[str] on Python 3.10+.
  • Use from __future__ import annotations for forward references.
  • Use TypeAlias or type (3.12+) for complex type aliases.
  • Use Protocol for structural subtyping instead of ABCs where possible.

Naming

  • snake_case: variables, functions, methods, modules.
  • PascalCase: classes, type aliases, Protocols.
  • UPPER_SNAKE: module-level constants.
  • Prefix private: _internal_helper. No double underscore unless name mangling needed.
  • Prefix unused: _ for intentionally unused variables.

Functions

  • Prefer keyword arguments for functions with >2 params.
  • Use * to force keyword-only: def fetch(*, limit: int, offset: int).
  • Return early to reduce nesting. Avoid deep if/else chains.
  • Use @staticmethod only for pure utility. Prefer module-level functions.

Imports

  • Group: stdlib, third-party, local. Separated by blank lines.
  • Use absolute imports. Relative imports only within packages.
  • Never from module import *. Be explicit.
  • Use if TYPE_CHECKING: for import-only-for-types to avoid circular imports.

Data Structures

  • Use dataclasses for plain data containers.
  • Use Pydantic BaseModel for validated data / API schemas.
  • Use NamedTuple for lightweight immutable records.
  • Use Enum for fixed sets of values. Prefer StrEnum on 3.11+.
  • Prefer dict / list literals over dict() / list() constructors.

Modern Python

  • Use f-strings for formatting. Never .format() or % for new code.
  • Use pathlib.Path over os.path for file operations.
  • Use contextlib.suppress(KeyError) over bare try/except for simple cases.
  • Use walrus operator := when it genuinely improves readability.
  • Use match/case (3.10+) for complex conditionals on structured data.

Tooling

  • Formatter: ruff format or black. No manual formatting.
  • Linter: ruff check. Fix all errors before committing.
  • Type checker: mypy --strict or pyright in CI.

Python Frameworks

FastAPI

  • Use Pydantic v2 models for request/response schemas.
  • Use dependency injection (Depends()) for shared logic (auth, DB sessions).
  • Use APIRouter to organize routes by domain.
  • Return Pydantic models directly -- FastAPI handles serialization.
  • Use BackgroundTasks for non-critical async work (emails, logging).
  • Use lifespan context manager for startup/shutdown (not on_event).

Django

  • Use class-based views for CRUD, function-based for custom logic.
  • Use select_related and prefetch_related to prevent N+1 queries.
  • Use Django REST Framework serializers for API validation.
  • Use Django ORM migrations. Never modify database schema manually.
  • Use transaction.atomic() for multi-model operations.
  • Use signals sparingly: prefer explicit service calls.

SQLAlchemy 2.0

  • Use the 2.0-style with select() statements, not legacy query().
  • Use Mapped[type] annotations for typed column definitions.
  • Use sessionmaker with expire_on_commit=False for API responses.
  • Use async_sessionmaker with asyncpg for async applications.
  • Always use session.begin() context manager for transaction scope.

Pydantic v2

  • Use model_validator(mode="before") for cross-field validation.
  • Use field_validator for single-field validation.
  • Use model_config = ConfigDict(strict=True) for strict type coercion.
  • Use Annotated[str, Field(min_length=1)] for reusable constrained types.
  • Use model_dump(exclude_unset=True) for PATCH operations.

CLI (click / typer)

  • Use Typer for new CLI tools (type-hint-driven, less boilerplate).
  • Use click.group() for multi-command CLIs.
  • Use rich for formatted terminal output (tables, progress bars).

Task Queues

  • Use Celery with Redis/RabbitMQ for background job processing.
  • Use arq for lightweight async job queues.
  • Always set task timeouts. Never let tasks run indefinitely.
  • Use idempotent tasks: safe to retry on failure.

Package Management

  • Use uv for fast dependency resolution and virtual environments.
  • Use pyproject.toml for all project configuration (no setup.py/setup.cfg).
  • Pin dependencies with lockfile (uv.lock, poetry.lock).

Python Patterns

Error Handling

  • Catch specific exceptions, never bare except: or except Exception.
  • Use custom exception hierarchies: class AppError(Exception) as base.
  • Add context when re-raising: raise AppError("context") from original.
  • Use contextlib.suppress() for expected, ignorable exceptions.
  • Log exceptions with logger.exception("msg") to include traceback.

Context Managers

  • Use with for any resource that needs cleanup (files, connections, locks).
  • Create custom context managers with @contextmanager decorator.
  • Use contextlib.AsyncExitStack for dynamic async resource management.
  • Use atexit.register() for process-level cleanup only.

Async

  • Use asyncio for I/O-bound concurrency. Use multiprocessing for CPU-bound.
  • Use asyncio.gather() for concurrent independent operations.
  • Use asyncio.TaskGroup (3.11+) for structured concurrency.
  • Never mix asyncio.run() inside already-running event loops.
  • Use async for and async with for streaming and resource patterns.

Dataclass Patterns

  • Use frozen=True for immutable value objects.
  • Use field(default_factory=list) for mutable defaults, never field(default=[]).
  • Use __post_init__ for validation, not complex logic.
  • Use slots=True (3.10+) for memory efficiency in high-volume objects.

Functional Patterns

  • Use functools.lru_cache for pure function memoization.
  • Use itertools for efficient iteration (chain, islice, groupby).
  • Use generators (yield) for lazy sequences and large data processing.
  • Prefer comprehensions over map/filter with lambdas.
  • Use functools.partial to create specialized versions of functions.

Dependency Injection

  • Use constructor injection: pass dependencies as __init__ params.
  • Use Protocol classes to define dependency interfaces.
  • Use factory functions to wire dependencies at application startup.
  • Avoid global state and singletons. Use module-level instances if needed.

Anti-Patterns

  • Mutable default arguments: use None and create inside function.
  • Catching Exception broadly: masks bugs and interrupts.
  • Using type() for type checking: use isinstance().
  • Nested try/except: flatten with early returns or separate functions.
  • Using global keyword: pass state through parameters or classes.
Show full SKILL.md (507 more words)Show less

Python Security

Input Validation

  • Validate all input with Pydantic models at API boundaries.
  • Use constr, conint, conlist for constrained types.
  • Never use eval(), exec(), or compile() with user input.
  • Never use pickle.loads() on untrusted data (arbitrary code execution).

SQL Injection

  • Use ORM query builders (SQLAlchemy, Django ORM) for all queries.
  • For raw SQL, always use parameterized queries: cursor.execute("SELECT * FROM users WHERE id = %s", (user_id,)).
  • Never use f-strings or .format() to build SQL queries.
  • Use text() with :param syntax in SQLAlchemy raw queries.

SSTI (Server-Side Template Injection)

  • Use Jinja2 with autoescaping enabled: Environment(autoescape=True).
  • Never render user input as a template string.
  • Use markupsafe.Markup only for trusted HTML content.

Command Injection

  • Never use os.system() or subprocess.run(shell=True) with user input.
  • Use subprocess.run() with list arguments: subprocess.run(["ls", "-la", path]).
  • Use shlex.quote() if shell=True is absolutely necessary.

Path Traversal

  • Use pathlib.Path.resolve() and verify the result is within allowed directory.
  • Never concatenate user input into file paths without validation.
  • Use os.path.commonpath() to verify path containment.

Secrets

  • Use secrets module for tokens: secrets.token_urlsafe(32).
  • Use hashlib.scrypt or bcrypt for password hashing.
  • Use hmac.compare_digest() for constant-time secret comparison.
  • Load secrets from environment: os.environ["SECRET_KEY"], never hardcode.

Dependencies

  • Run pip-audit or safety check in CI.
  • Use uv or pip-compile for reproducible dependency resolution.
  • Avoid installing packages with native extensions from untrusted sources.
  • Pin all dependency versions. Review dependency updates carefully.

Deserialization

  • Never deserialize untrusted data with pickle, yaml.load(), or marshal.
  • Use yaml.safe_load() instead of yaml.load().
  • Use json.loads() for untrusted data (safe by default).
  • Validate deserialized data with Pydantic before use.

Django-Specific

  • Set DEBUG = False in production. Never expose debug pages.
  • Use django.utils.html.escape() for manual HTML escaping.
  • Use CSRF_COOKIE_HTTPONLY = True and SESSION_COOKIE_SECURE = True.
  • Keep SECRET_KEY unique per environment and out of version control.

Python Testing

Framework

  • Use pytest as the default test framework. No unittest for new code.
  • Use pytest-asyncio for async test functions.
  • Use pytest-cov for coverage measurement.
  • Use hypothesis for property-based testing on parsing/validation logic.

File Naming

  • Test files: test_*.py in tests/ directory.
  • Conftest: conftest.py at each test directory level for shared fixtures.
  • Mirror source: src/auth/service.py -> tests/auth/test_service.py.

Fixtures

  • Use @pytest.fixture for setup. Prefer fixtures over setup/teardown methods.
  • Scope fixtures appropriately: function (default), module, session.
  • Use yield fixtures for setup + teardown: yield resource; cleanup().
  • Use tmp_path fixture for temporary files, not manual tempfile.
  • Use monkeypatch for patching env vars, attributes, and dict items.

Parametrize

  • Use @pytest.mark.parametrize for testing multiple inputs/outputs.
  • Use pytest.param(..., id="descriptive_name") for readable test IDs.
  • Combine parametrize decorators for cross-product testing.

Mocking

  • Use unittest.mock.patch or monkeypatch for dependency replacement.
  • Mock at the import location: patch("myapp.service.http_client").
  • Use MagicMock(spec=ClassName) to get attribute checking.
  • Use AsyncMock for async functions.
  • Prefer dependency injection over patching when possible.

Markers

  • Use @pytest.mark.slow for tests >1s. Exclude from default runs.
  • Use @pytest.mark.integration for tests requiring external services.
  • Register all custom markers in pyproject.toml to avoid warnings.

Async Testing

  • Use @pytest.mark.anyio or @pytest.mark.asyncio for async tests.
  • Use httpx.AsyncClient for testing FastAPI/Starlette apps.
  • Use aiosqlite or test containers for async database tests.

Configuration

  • Configure pytest in pyproject.toml under [tool.pytest.ini_options].
  • Set addopts = "--strict-markers -ra" for strict mode.
  • Set testpaths = ["tests"] to avoid scanning the entire repo.

© softspark, Apache-2.0. Rendered from Markdown: HTML in the file is shown as text, images as links, and headings moved down two levels. Raw file

Files

Just SKILL.md in app/skills/python-rules of softspark/ai-toolkit.

Open the folder on GitHubat commit d64db2b

Compare with similar skills

Python Rules next to the 5 skills that share the most tags, products or categories with it. Stars are the repository's; “used in” counts other GitHub owners with a copy.

Python Rules compared with similar skills
SkillStarsUsed inTokensAuto-checkLicenceRepo updated
Python Rules this skillsoftspark/ai-toolkit179—~2.9kAutomated safety check: PassApache-2.0
Pythonericrisco/rsc-harness156—~3.8kAutomated safety check: PassMIT
Mastering Python SkillSpillwaveSolutions/agent-brain120—~1.4kAutomated safety check: NotesMIT
Run And Verifyaropan/clist439—~461Automated safety check: PassApache-2.0
PythonMadAppGang/claude-code283—~2.8kAutomated safety check: NotesMIT
Django Idiomsirahardianto/awesome-agv157—~786Automated safety check: PassMIT

Similar skills

  • Python

    ericrisco/rsc-harness

    A skill your agent uses when the task is Python itself, in any framework or none: PEP 695 generics, mypy --strict typing, dataclass/Protocol/TypedDict/Enum choices, asyncio.TaskGroup, stdlib idioms…

    156 GitHub stars~3.8k tokensUpdated today
    Backend & APIsAuto-check passed
  • Mastering Python Skill

    SpillwaveSolutions/agent-brain

    Modern Python coaching covering language foundations through advanced production patterns.

    120 GitHub stars~1.4k tokensUpdated 18 days ago
    DevelopmentAuto-check: notes
  • Run And Verify

    aropan/clist

    Choose and run focused checks after changing CLIST Python code: Django tests, standalone pytest tests, offline parser fixtures, Ruff, or a relevant management-command check.

    439 GitHub stars~461 tokensUpdated 3 days ago
    Backend & APIsAuto-check passed
  • Python

    MadAppGang/claude-code

    A skill your agent uses when building FastAPI applications, implementing async endpoints, setting up Pydantic schemas, working with SQLAlchemy, or writing pytest tests for Python backend services.

    283 GitHub stars~2.8k tokensUpdated 6 mo ago
    Backend & APIsAuto-check: notes
  • Django Idioms

    irahardianto/awesome-agv

    Django and Django REST Framework (DRF) patterns: ORM queries, model managers, class-based views, serializers, migrations, and pytest-django testing.

    157 GitHub stars~786 tokensUpdated 2 days ago
    Backend & APIsAuto-check passed
  • FastAPI Expert

    Jeffallan/claude-skills

    Builds async Python APIs with FastAPI and Pydantic V2, covering endpoints, JWT authentication, async SQLAlchemy, WebSockets and pytest checks against the OpenAPI docs.

    12k GitHub stars~1.8k tokensUpdated 4 days ago
    Backend & APIsAuto-check passed

More from softspark/ai-toolkit

All 112 skills in this repo
  • Prepare Test Env

    softspark/ai-toolkit

    Prepare or verify a project QA environment with source identity, readiness, browser access, evidence paths and owned cleanup.

    179 GitHub stars~1.8k tokensUpdated today
    Auto-check: notes
  • A11y Validate

    softspark/ai-toolkit

    Accessibility validator: WCAG 2.1 AA, EN 301 549, EAA. An agent skill from softspark/ai-toolkit.

    179 GitHub stars~3.8k tokensUpdated today
    Auto-check: notes
  • Analyze

    softspark/ai-toolkit

    Analyzes code quality, complexity, patterns across codebase.

    179 GitHub stars~1k tokensUpdated today
    Auto-check passed
  • Autonomous Dev

    softspark/ai-toolkit

    Drives a brief, specification, issue or existing PR through implementation, review, tests and QA to a ready PR.

    179 GitHub stars~2.6k tokensUpdated today
    Auto-check: notes
  • Brand Voice

    softspark/ai-toolkit

    Direct technical voice for docs, README, user-facing text. An agent skill from softspark/ai-toolkit.

    179 GitHub stars~2.1k tokensUpdated today
    Auto-check passed
  • CI

    softspark/ai-toolkit

    Detect/generate/debug CI pipeline config (GitHub Actions, GitLab CI).

    179 GitHub stars~1.1k tokensUpdated today
    Auto-check: notes

Categories

Questions about Python Rules

What does Python Rules do?

Python coding rules: style, patterns, security, testing. An agent skill from softspark/ai-toolkit. Python Rules is an agent skill from softspark/ai-toolkit. Python coding rules: style, patterns, security, testing.

When should I use Python Rules?

Python Rules fits situations like: tasks that involve Backend development; tasks that involve Type safety; tasks that involve ORMs and data access.

How do I install Python Rules in Claude Code?

Run `npx skills add softspark/ai-toolkit --skill python-rules -a claude-code`. Or copy the skill folder (app/skills/python-rules in softspark/ai-toolkit) into .claude/skills/python-rules in your project. Claude Code loads it when a task matches its description.

How do I install Python Rules in Codex?

Run `npx skills add softspark/ai-toolkit --skill python-rules -a codex`. Or copy the skill folder (app/skills/python-rules in softspark/ai-toolkit) into .agents/skills/python-rules in your project. Codex loads it when a task matches its description.

Can I use Python Rules in Cursor, Gemini CLI or GitHub Copilot?

Cursor, Gemini CLI, GitHub Copilot and OpenCode also load SKILL.md folders. With the skills CLI, run `npx skills add softspark/ai-toolkit --skill python-rules -a cursor` (or -a gemini-cli, github-copilot or opencode for the others). To copy it by hand, put the folder in .cursor/skills/python-rules, .gemini/skills/python-rules, .github/skills/python-rules and .opencode/skills/python-rules in your project.

What does Python Rules need to run?

Going by SKILL.md and its folder, Python Rules needs the command-line tools its instructions call (ruff and mypy) and credentials named SECRET_KEY. Our summary lists: Python 3; A credential in SECRET_KEY. Its frontmatter pre-approves these tools: Read.

Does Python Rules access the network?

SKILL.md contains no URLs. Any network use would come from the scripts or tools the agent runs. This is read from the text; nothing was executed.

Is Python Rules safe to install?

Our automated static check of SKILL.md found no risky patterns, such as piping downloads into a shell, reading credential files or hidden Unicode. It is not a guarantee. Review the folder before installing.

What licence does Python Rules use?

Python Rules is published under the Apache-2.0 licence (the repository's licence). It allows redistribution, so the full SKILL.md is shown on this page.

How many tokens does Python Rules use?

About 2.9k tokens (SKILL.md is roughly 12k characters). Agents keep only the skill's name and description in context until a task matches; then they load SKILL.md in full.

What are the alternatives to Python Rules?

Skills that share tags, products or a category with Python Rules: Python (ericrisco/rsc-harness, 156 stars), Mastering Python Skill (SpillwaveSolutions/agent-brain, 120 stars), Run And Verify (aropan/clist, 439 stars) and Python (MadAppGang/claude-code, 283 stars). The comparison table on this page puts their stars, adoption, token cost, safety result and licence side by side.

Who maintains Python Rules?

softspark (a GitHub user) maintains it in softspark/ai-toolkit, which has 179 GitHub stars. The repository holds 112 skills in this directory. The repository was last updated on October 7, 2026.

Source: softspark/ai-toolkit on GitHub. Facts on this page come from the repository at the commit we read; the author's words are quoted as theirs.