Token导航 LogoToken导航

Agent Skill · 开发

writing-python-code(writing Python 代码)

用于辅助 Python 项目开发、测试、依赖管理和常见框架工作流。它适合让 Agent 阅读 Python 代码、定位测试问题、整理运行命令、生成脚本或分析数据处理逻辑。使用时需要确认项目虚拟环境、依赖版本和测试入口;涉及执行脚本、读写文件、访问数据库或调用外部 API 时,应先明确运行目录和输入输出范围,避免误改生产数据。

writing-python-code 是开发类 Agent Skill,可用宿主为 Codex、Claude、Cursor、Gemini CLI,通过GitHub 仓库获取,权限为执行命令;许可证信息还不明确,第三方扫描已通过,按安装量在开发类的 21,746 个 Skill 里排第 15,487。

总安装 588周安装 24GitHub Stars 公开资料未说明下载 190核验 2026-05-01

安装说明

本站只整理中文说明,不托管安装包,也不代用户安装。
GitHub
许可证
unknown

安装方式

通过对话安装

复制提示词发给支持本地命令或 Skills 的 AI 助手,先确认命令和权限,再让它执行。

请帮我安装这个 Agent Skill:writing-python-code(writing Python 代码)
来源仓库:https://github.com/quick-brown-foxxx/coding_rules_python
仓库路径:skills/writing-python-code
安装命令:
npx skills add https://github.com/quick-brown-foxxx/coding_rules_python --skill writing-python-code
安装前请先检查当前环境是否支持对应 CLI,并向我确认将要执行的命令、安装目录、联网范围和文件读写权限;确认后再执行。

命令行安装

复制命令到本机终端执行。该命令会通过 npx skills 从第三方来源获取 Skill;本站只展示命令,不托管安装包,也不自动执行。

skills.shnpx skills
npx skills add https://github.com/quick-brown-foxxx/coding_rules_python --skill writing-python-code

这个 Skill 是做什么的

开发类 Skill 面向写代码、改代码和排查问题,一般会读写仓库文件,部分还会执行构建或测试命令。

用于辅助 Python 项目开发、测试和依赖管理。适合阅读代码、定位问题和生成脚本。使用时需确认虚拟环境和依赖版本。writing-python-code 属于开发类 Skill,可作为该场景下的辅助能力补充。涉及文件操作或 API 调用时应明确运行目录。安装方式:通过 npx 从 GitHub 仓库添加技能。

来源仓库内路径:skills/writing-python-code

上手步骤

4 步
  1. 1

    确认自己的宿主工具

    公开资料标注支持 Codex、Claude、Cursor、Gemini CLI;先确认自己用的是其中之一,再按对应工具的 Skills 目录放置。

  2. 2

    拿到安装命令

    可以直接复制的命令是 npx skills add https://github.com/quick-brown-foxxx/coding_rules_python --skill…;命令里的占位符换成自己的路径或密钥再执行。

  3. 3

    安装后重启宿主

    命令执行完要完全退出宿主工具再打开,让新装的 Skill 被重新扫描到,否则列表里可能看不到。

  4. 4

    按最小权限试用

    它需要执行命令,先在测试目录或测试账号里跑,确认没问题再放到正式项目。

常见问题

6 条

writing-python-code 怎么安装?

在终端执行 npx skills add https://github.com/quick-brown-foxxx/coding_rules_python --skill writing-py…。装完完全退出宿主工具再打开,让它重新扫描本地 Skill。

writing-python-code 支持哪些 AI 工具?

公开资料标注支持 Codex、Claude、Cursor、Gemini CLI。其他工具只要能读取本地 Skill 目录,一般也能手动放进去,但要自己确认触发方式是否一致。

writing-python-code 需要什么权限?

权限级别是执行命令。安装流程涉及命令执行,可能通过 npx skills add https://github.com/quick-brown-foxxx/coding_rules_python --skill writing-python-code 联网下载 Skill 或依赖。用户安装前应确认命令来源、仓库内容和执行环境。

writing-python-code 是免费的吗?

公开资料没有标注明确许可证,收费和商用限制都无法确认。正式使用前请到来源仓库核对授权说明。

writing-python-code 用的人多吗?

公开数据是累计安装 588 次,近一周安装 24 次,下载 190 次。这些数字来自第三方目录统计,只能当作热度参考,不代表质量或安全性。

writing-python-code 安全吗?

第三方扫描结果为通过,但这只覆盖已知的静态检查项,不能替代自己读一遍源码和安装命令。

值得选的地方和要先想清楚的地方

值得选的地方

  • 同时适配 4 种工具,换客户端不用重新找替代品。
  • 第三方扫描已通过,常见的高风险行为没有命中。

先想清楚的地方

  • 需要执行命令,装到常用环境前要先评估影响面。
  • 许可证没有明确标注,能不能商用、能不能再分发都不确定。
  • 第三方目录整理,版本更新和行为细节以来源仓库为准。

适不适合你

更适合

  • 已经在用 Codex,想直接扩展它能力的人。
  • 需要处理开发类任务、又不想每次都手写提示词的人。

不太适合

  • 不能接受 Skill 在你机器上执行命令的人。
  • 需要明确授权才能用到公司项目里的场景。
  • 需要厂商级技术支持和 SLA 的生产系统。

开发类 Skill 对比

6 个同类
Skill总安装GitHub 星权限许可证扫描
skill-vetter

技能审查员 · OpenClaw

8,779,018986操作浏览器MIT-0通过
ontology

本体论 · OpenClaw

6,636,960576只读MIT-0通过
entra-app-registration

内部应用程序注册 · Codex、Claude

6,631,872764接触敏感数据未明确通过
entra-app-registration

内部应用程序注册 · Codex、Claude

3,757,680201接触敏感数据未明确通过
nano-banana-pro

纳米香蕉专业版 · OpenClaw

3,526,898364接触敏感数据MIT-0有提醒
writing-python-code

writing Python 代码 · 本页

588—执行命令未明确通过

按安装量取同分类前几名;数字来自第三方目录统计,只作热度参考,不代表质量结论。

SKILL.md 原文

Writing Python Code

All Python code follows the pit-of-success philosophy: strict types, Result-based error handling, modern tooling.


Type System

basedpyright Configuration

[tool.basedpyright]
pythonVersion = "3.14"
typeCheckingMode = "strict"
reportAny = "error"
reportImportCycles = "error"
reportImplicitStringConcatenation = "none"
reportUnusedCallResult = "none"
reportUnnecessaryIsInstance = "none"

Additional strict options (for medium-big projects):

reportExplicitAny = "error"
reportUnnecessaryTypeIgnoreComment = "error"
reportMissingModuleSource = "error"
reportPrivateUsage = "error"
reportOptionalMemberAccess = "error"
reportOptionalCall = "error"
reportAttributeAccessIssue = "error"

Banned Patterns

BannedUse Instead
AnyBanned entirely — define the actual type
object (unrestricted)Restricted to boundary positions only (see below)
typing.cast()isinstance, TypeIs, pattern matching
# type: ignore without rationale# type: ignore[specific-code] # rationale: <reason>
Raw dict in business logicmsgspec.Struct, dataclass, or TypedDict
Implicit return typesExplicit annotation on every function

object is allowed only in: TypeIs/TypeGuard params, *args: object, Coroutine[object, None, T], PySide6 Signal(object). Everywhere else, use Protocol, TypeVar, union types, or typed structures.

Type Patterns

External data → msgspec.Struct:

import msgspec

class UserConfig(msgspec.Struct):
    name: str
    port: int
    debug: bool = False

# JSON → typed object (validates at decode time)
config = msgspec.json.decode(raw_bytes, type=UserConfig)

# Dict/YAML → typed object
config = msgspec.convert(raw_dict, type=UserConfig)

TypedDict is still valid when dict compatibility is needed (e.g., **unpacking, APIs expecting dicts).

Domain objects → dataclass:

@dataclass(frozen=True, slots=True)
class Profile:
    name: str
    version: str
    active: bool = True

Duck typing → Protocol:

class Renderable(Protocol):
    def render(self) -> str: ...

Constants → Final:

MAX_RETRIES: Final = 3
CONFIG_PATH: Final[Path] = Path("~/.config/app").expanduser()

Handling Any at Library Boundaries

0. Typed deserialization (for external data):

msgspec.json.decode(data, type=MyStruct) eliminates Any for JSON/API responses — the return type is MyStruct, not Any. Use this before reaching for wrappers when the boundary is data deserialization.

1. Typed wrappers (preferred for library APIs):

class WhisperModelWrapper:
    def __init__(self, model_size: str, device: str = "auto") -> None:
        from faster_whisper import WhisperModel as _WhisperModel
        self._model = _WhisperModel(model_size, device=device)

    def transcribe(self, audio: np.ndarray, language: str | None = None) -> TranscriptionResult:
        segments_gen, info = self._model.transcribe(audio, language=language)
        return TranscriptionResult(
            text="".join(s.text for s in segments_gen),
            language=str(info.language),
        )

Enforce wrapper usage via ruff:

[tool.ruff.lint.flake8-tidy-imports.banned-api]
"faster_whisper" = { msg = "Use src/wrappers/whisper_wrapper instead" }

2. Type stubs in src/stubs/:

# src/stubs/some_library.pyi
def some_function(arg: str) -> list[int]: ...

Configure: stubPath = "src/stubs" in basedpyright config.

3. Inline type narrowing for one-off cases:

raw_value = untyped_lib.get_value()  # returns Any
assert isinstance(raw_value, str)    # narrows to str

TypeIs Guards

Note: TypeIs guards are unnecessary for msgspec-decoded data (already fully typed). Use them for narrowing in-memory objects of unknown type.
from typing import TypeIs, TypedDict, Required

class ValidResponse(TypedDict):
    status: Required[str]
    data: Required[dict[str, str | int | bool | list[str]]]

def is_valid_response(obj: object) -> TypeIs[ValidResponse]:
    return (
        isinstance(obj, dict)
        and isinstance(obj.get("status"), str)
        and isinstance(obj.get("data"), dict)
    )

def process(response: object) -> Result[str, str]:
    if not is_valid_response(response):
        return Err("Invalid response format")
    return Ok(response["data"]["key"])  # type-safe access

Pattern Matching for Type Safety

@dataclass
class Success:
    value: str

@dataclass
class Failure:
    error: str
    code: int

type Outcome = Success | Failure

def handle(outcome: Outcome) -> str:
    match outcome:
        case Success(value=v):
            return f"OK: {v}"
        case Failure(error=e, code=c):
            return f"Error {c}: {e}"

# type: ignore Policy

Every # type: ignore must have a specific error code and rationale:

# BAD
result = some_call()  # type: ignore

# GOOD
result = some_call()  # type: ignore[no-any-return]  # rationale: lib returns Any, validated below
assert isinstance(result, ExpectedType)

TYPE_CHECKING Guard

For imports that cause circular dependencies or are only needed for annotations:

from __future__ import annotations
from typing import TYPE_CHECKING

if TYPE_CHECKING:
    from src.managers.audio_manager import AudioManager

class TranscriptionService:
    def __init__(self, audio: "AudioManager") -> None: ...
Note: TYPE_CHECKING is for forward references within the same layer. If two modules import each other, that's a circular dependency — fix the architecture (extract a Protocol, move types to a common module), don't hide the cycle with TYPE_CHECKING.

Error Handling

Errors are values, not exceptions. Use Result[T, E] from rusty-results for expected failures.

Decision Table

SituationUse
File not found, network error, invalid inputResult[T, E]
User provided bad dataResult[T, E]
Third-party library raisedCatch at boundary → Result[T, E]
Invariant violated (should never happen)raise exception
Invalid program state (bug)raise exception

Pattern

from rusty_results import Result, Ok, Err

def load_config(path: Path) -> Result[Config, str]:
    if not path.exists():
        return Err(f"Config not found: {path}")
    try:
        data = json.loads(path.read_text())
        return Ok(Config(**data))
    except (json.JSONDecodeError, OSError) as e:
        return Err(f"Failed to load: {e}")

Rules

  1. Early returns — handle error first, keep success path linear: result = load_data(path) if result.is_err: return Err(f"Cannot proceed: {result.unwrap_err()}") data = result.unwrap()
  2. Three error boundaries:

- Library: catch third-party exceptions → Result - Component: each subsystem returns Result to caller - Global: UI/CLI top-level catches everything, shows user message

  1. Never swallow errors — no except: pass, no ignored Results. Every Result[T, E] must be checked — at minimum log the error + show toast/alert in GUI or print to CLI.
  2. Cleanup on failure — if multi-step operation fails midway, clean up partial state
  3. Custom error types for complex domains: @dataclass class ConfigError: path: Path reason: str line: int | None = None
  4. Handle received error values gracefully: show UI warning, or log, or do early return or propagate with context

Async Task Boundaries

Any coroutine launched via asyncio.ensure_future() or create_task() is a fire-and-forget boundary. If an exception escapes, nobody retrieves it and the UI gets stuck in an intermediate state (e.g. "processing" forever).

Mandatory pattern: wrap the entire coroutine body in try/except Exception as a safety net:

async def _do_work(self, path: Path) -> None:
    try:
        await self._do_work_inner(path)
    except Exception as exc:
        logger.exception("Unexpected error for %s", path)
        self._set_error_state(path, f"Unexpected error: {exc}")

The inner method handles expected errors (Result checks, specific exceptions). The outer method guarantees the UI always transitions to a terminal state.

CLI Error Boundary

def main() -> int:
    result = run_app()
    if result.is_err:
        typer.echo(f"Error: {result.unwrap_err()}", err=True)
        return 1
    return 0

Async Patterns

When to Use

Use asyncDon't use async
File I/OPure data transformations
Network requestsSimple calculations
Subprocess executionIn-memory operations
Operations >100msQuick lookups
Parallel I/O operationsSequential pure logic

HTTP Requests

async def fetch_data(url: str) -> Result[bytes, str]:
    try:
        async with httpx.AsyncClient() as client:
            resp = await client.get(url, timeout=30.0)
            resp.raise_for_status()
            return Ok(resp.content)
    except httpx.HTTPError as e:
        return Err(f"HTTP error: {e}")

Subprocess Execution

async def run_command(args: list[str]) -> Result[str, str]:
    try:
        process = await asyncio.create_subprocess_exec(
            *args,
            stdout=asyncio.subprocess.PIPE,
            stderr=asyncio.subprocess.PIPE,
        )
        stdout, stderr = await process.communicate()
        if process.returncode != 0:
            return Err(f"Command failed: {stderr.decode()}")
        return Ok(stdout.decode())
    except FileNotFoundError:
        return Err(f"Command not found: {args[0]}")

Concurrent Operations

async def fetch_all(urls: list[str]) -> list[Result[bytes, str]]:
    return await asyncio.gather(*(fetch_data(url) for url in urls))

Timeouts

async def fetch_with_timeout(url: str) -> Result[bytes, str]:
    try:
        async with asyncio.timeout(10):
            return await fetch_data(url)
    except TimeoutError:
        return Err(f"Timeout fetching {url}")

Async Rules

  1. Never call subprocess.run(), time.sleep(), or synchronous HTTP in async context
  2. Never use shell=True in subprocess calls
  3. Always use asyncio.create_subprocess_exec() for subprocesses
  4. Always use async with for resource management (HTTP clients, file handles)
  5. Never mix sync and async in the same call chain
  6. Always handle TimeoutError for operations that may hang

Code Style

RuleValue
Line length120
Indentation4 spaces
QuotesDouble quotes (single only to avoid escaping)
Import orderstdlib → third-party → local (auto-sorted by ruff)

Naming

ElementConventionExample
Modules, functions, variablessnake_caseload_config, user_name
Classes, TypedDictsPascalCaseProfileManager, UserConfig
ConstantsUPPER_SNAKEMAX_RETRIES, DEFAULT_PORT
Private_prefix_internal_state

Documentation

Google-style docstrings on public APIs. Comments explain why, not what.


Preconditions & Validation

Validate at subsystem entry points. Fail fast. Check permissions, external deps, config validity, complex input arguments or other data or value ranges before proceeding with business logic.


Architecture

Presentation (Qt GUI / CLI / API)
        |
        v
Domain (Managers, Models, Business Rules)
        |
        v
Utilities (Helpers, Wrappers, Common)
  • Dependencies flow downward only
  • UI is a plugin — adding CLI, GUI, or API should not change business logic
  • Domain never imports from presentation

Security

  • No shell=True in subprocess calls
  • Validate paths (symlink-aware): def is_safe_path(path: Path, base: Path) -> bool: try: resolved = path.resolve(strict=True) return resolved.is_relative_to(base.resolve(strict=True)) except (OSError, ValueError): return False
  • No hardcoded secrets — use environment variables or dotenv
  • Input validation at system boundaries
  • Never interpolate user input into subprocess commands
  • Cleanup on failure — if multi-step operation fails midway, clean up partial state

Performance

  • Clear code first, optimize only with profiling data
  • __slots__ on frequently instantiated dataclasses
  • Batch I/O operations (don't read files one by one in a loop)
  • Lazy loading for expensive resources (load on first use, not import time)
  • Concurrent I/O with asyncio.gather()

Logging

import colorlog

def get_logger(name: str) -> logging.Logger:
    handler = colorlog.StreamHandler()
    handler.setFormatter(colorlog.ColoredFormatter(
        "%(log_color)s%(levelname)-8s%(reset)s %(name)s: %(message)s"
    ))
    logger = logging.getLogger(name)
    logger.addHandler(handler)
    logger.setLevel(logging.INFO)
    return logger

Usage: logger = get_logger(__name__)


Jinja2 Templating

Use when generating text output (HTML, configs, reports, markdown):


Tooling

ToolPurpose
uvPackage management, script execution
basedpyrightType checking (strict)
ruffLint + format
pytestTesting
rusty-resultsResult[T, E] pattern
typerCLI framework (preferred) — always configure -h support (see below)
argparseCLI only for stdlib-only scripts
PySide6GUI (no system deps)
httpxHTTP (async)
msgspecExternal data validation + parsing
Jinja2Text output generation

Always enable -h for help — typer only supports --help by default:

app = typer.Typer(context_settings={"help_option_names": ["-h", "--help"]})

Run uv run poe lint_full continuously, not just at the end.


Git Conventions

Commit format: <type>(<scope>): <subject>

Types: feat, fix, docs, style, refactor, perf, test, chore

Pre-commit: uv run poe lint_full passes, tests pass, public APIs have docstrings.

平台分布

Codex

34.41%
按下载量换算65

Claude

29.65%
按下载量换算56

Cursor

19.36%
按下载量换算37

Gemini CLI

9.87%
按下载量换算19

安全审计

Gen Agent Trust Hub

通过

Socket

通过

Snyk

通过

权限和风险

执行命令

安装流程涉及命令执行,可能通过 npx skills add https://github.com/quick-brown-foxxx/coding_rules_python --skill writing-python-code 联网下载 Skill 或依赖。用户安装前应确认命令来源、仓库内容和执行环境。

安装前确认

本站仅展示第三方公开信息,不托管安装包,不提供自动安装或运行环境。安装前应自行审查源码、依赖和命令行为。目前只有一个公开来源,建议同时核对源仓库。

继续浏览同类 Skills