python-rules

Python 编码规范合集,涵盖代码风格、常用模式、安全性检查与测试实践。触发条件包括 .py/.pyi 文件、pyproject.toml、requirements.txt、Pipfile、FastAPI、Django、Flask、pytest、SQLAlchemy、ruff 或 mypy 相关配置或代码。

仓库最近推送
GitHub Stars
180
Forks
21
Issues / PRs
0

安装方式

先用 Prompt 核对来源与依赖。也可下载安装包。

用 AI 助手安装

复制提示词,让助手先核对固定版本和依赖。

查看 Prompt收起 Prompt
先检查当前 Agent 是否已安装 SkillPI Skill Finder。如果尚未安装,请按官方仓库的说明安装并启用:https://github.com/Findskills/skillpi。然后使用 Skill Finder 打开此 SkillPI 详情页并定位 "python-rules":https://skillpi.com/zh/skills/deepskill-79c0a2352816c57fb47d1c0d933dbc31b24241edc04742ec75d61058f56580c6。安装前核对上游来源和版本:https://github.com/softspark/ai-toolkit。来源不一致时停止并说明差异。核对通过后,用 Skill Finder 安装目标 Skill,并报告安装路径和来源版本。

来源与配置

github.com

配置方式待核实

请查看原始来源中的适用工具、依赖和权限要求。

安装实测待补充

Python 编码规范合集,涵盖代码风格、常用模式、安全性检查与测试实践。触发条件包括 .py/.pyi 文件、pyproject.toml、requirements.txt、Pipfile、FastAPI、Django、Flask、pytest、SQLAlchemy、ruff 或 mypy 相关配置或代码。

0 下载

介绍来源: third_party · softspark · 0.0.1 参考来源

SkillPi 解读

能完成的任务
翻译待完成,请参阅来源文档。
输入和输出
翻译待完成,请参阅来源文档。
实测状态
未测试

文件浏览

在原站浏览文件 ↗

原始 SKILL.md

打开原文 ↗
Frontmatter
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."
effort: medium
user-invocable: false
allowed-tools: Read

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.

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.

版本历史

  1. v6.2.0 GitHub ↗
    原版更新说明

    **Full Changelog**: https://github.com/softspark/ai-toolkit/compare/v6.1.0...v6.2.0

  2. v6.1.0 GitHub ↗
    原版更新说明

    **Full Changelog**: https://github.com/softspark/ai-toolkit/compare/v6.0.0...v6.1.0

  3. v6.0.0 GitHub ↗
    原版更新说明

    ## What's Changed * chore: bump softprops/action-gh-release from 3.0.3 to 3.0.4 by @dependabot[bot] in https://github.com/softspark/ai-toolkit/pull/45 * fix: handle Windows status output and clarify Antigravity workflow support by @softspark in https://github.com/softspark/ai-toolkit/pull/46 **Full Changelog**: https://github.com/softspark/ai-toolkit/compare/v5.5.0...v6.0.0

  4. v5.5.0 GitHub ↗
    原版更新说明

    ### Ecosystem - **OpenCode V2 and V1 compatibility:** `scripts/generate_opencode_plugin.py` emits the documented `id/setup/server` contract for V2 and V1 **1.18.29+**. Upgrade older V1 clients before using this plugin, then run `ai-toolkit update` to regenerate managed copies. `doctor` warns about obsolete V1-only exports. Scoped global/project IDs avoid native collisions; advisory work has one owner per location, while safety guards execute in every registered layer. The current V2 package is `@opencode/cli`; `opencode-ai` still publishes V1. - **Claude guard failure policy:** destructive-command, home-path and configuration guards use `onFailure: block` on Claude Code **2.1.295+**. Legacy entries migrate without duplication; hooks owned by other plugins survive. Older clients do not have this infrastructure-failure guarantee. - **Codex, Gemini and Devin:** Codex refresh accepts the two diagnostic model-request events. Gemini advisory hooks return native JSON and save native completion responses; Devin prompt/edit hooks emit event-labelled context. - **All 13 integrations reviewed:** refresh release metadata and the ecosystem snapshot, distinguish stable/preview channels, and pin Auggie's stable v0 references. User model, effort and approval selections remain unchanged. ### Fixed - **One Claude Stop checker:** remove the duplicate advisory handler from the global and app manifests. `quality-gate.sh` keeps PHPStan advisory through `quality-check.sh --php-only`, preserving checker precedence and Makefile settings. PHPStan now runs synchronously on Stop and TaskCompleted (#43). - **OpenCode guard execution:** replace the unsupported Bun stdin path with real subprocess execution in both APIs. Denial, missing guards, crashes and timeouts block tools. Transactional generation refuses user-owned collisions and symlinked destinations; lifecycle cleanup releases advisory ownership. - **Isolated release smoke:** `scripts/release.sh` installs the packed artifact in a disposable, network-disabled container with no mounts and the OS user's default home. Host settings are not used as a smoke sandbox. ### Changed - Hook entries: 29 to 28 across the same 14 Claude events. Skills remain 116 and agents remain 44. Bats coverage grows from 2012 to 2037 tests. - Refresh compatibility documentation and remove stale inventory counts from the backward-compatibility policy. All protected public surfaces remain. - Skill body budget is unchanged: the largest body remains `design-engineering` at 17,197 bytes, less than 2,000 bytes below the 18,000-byte warning threshold, so the release ratchet does not apply. **Included pull request:** [#43: run the project checker once on Claude Code Stop](https://github.com/softspark/ai-toolkit/pull/43), contributed by @jacekprzybyl. **Full changelog:** https://github.com/softspark/ai-toolkit/compare/v5.4.2...v5.5.0

  5. v5.4.2 GitHub ↗
    原版更新说明

    ## What's Changed * fix(install): read state.json on native Windows by @jacekprzybyl in https://github.com/softspark/ai-toolkit/pull/39 * test: isolate USERPROFILE together with HOME on Windows by @jacekprzybyl in https://github.com/softspark/ai-toolkit/pull/41 **Full Changelog**: https://github.com/softspark/ai-toolkit/compare/v5.4.1...v5.4.2

此处仅展示最近 5 个版本。 在原站查看完整版本历史 ↗

当前收录版本

0.0.1

核对来源版本 ↗

质量评测

满分100 · 来自 SkillPi LAB 实验室的评测报告。

场景价值92/100

亮点

  • 提供全面的 Python 编码规范,涵盖风格、框架、安全、测试等核心领域
  • 面向 Python 开发者高频刚需,显著提升代码质量和团队协作效率
触发精准95/100

亮点

  • 触发词完整覆盖 Python 开发全链路文件类型和主流框架
  • 边界清晰,无歧义,精准匹配目标用户场景
结构规范85/100

待提升项

  • 缺少 When to Use 和示例章节 原报告严重程度:轻微

    规范文档缺少使用场景说明和具体示例

    改进建议:补充 When to Use 章节说明适用场景,增加代码示例增强可读性

  • description 写错位置 原报告严重程度:轻微

    顶层 frontmatter 和 skill_body 内部均包含 description

    改进建议:保留一处 description,避免重复

亮点

  • 结构清晰,分五大模块层次分明
  • frontmatter 完整,单文件长度合理
执行可靠90/100

亮点

  • 工具来源明确,参数建议正确
  • 覆盖主要异常场景,无执行风险
证据可验 (前四项均值)91/100

取前四项原始分值的算术平均,四舍五入取整。可通过收录报告核对各项评分与说明,运行记录需单独查证。

正文静态检测

100 / 100 · skillpi-20261123-no-r3-v1

正文未命中当前规则。

分数仅反映正文中的规则命中,供使用前参考。附件与运行行为不在此评分范围内。

权限与使用前检查

根据当前主文档自动整理,命中内容可能是示例或防护说明;不是实际权限声明,也未覆盖附件、外部依赖或运行行为。

本站展示提示不会授予权限。涉及文件改动、密钥、外部发送或费用时,仍由你使用的工具按需确认。

安全评级与访问范围

safe · 静态证据核验,不代表运行安全保证。

使用前请由宿主核对并授权实际文件读写、外部服务和联网目的地;本站的核验不会授予任何运行权限。