Token导航 LogoToken导航TokenDH.com
研究检索只读github未标认证来源可访问clear审计未展示

pythonPython 开发

Agent Skill

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

总安装

449

周安装

18

GitHub Stars

公开资料未说明

下载量

145
CodexClaudeCursorGemini CLI

安装说明

本站只整理中文说明和来源信息,不托管安装包,也不代用户安装。

GitHub

来源数

2

许可证

MIT

最后核验

2026-05-01

来源状态

来源可访问

安装方式

通过对话安装

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

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

命令行安装

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

AgentSkills.tonpx skills
npx skills add observerw/python-skill --skill "python"

简介

用于辅助 Python 项目开发、测试和依赖管理。

  • 适合让 Agent 阅读代码、
  • 定位测试问题或生成运行脚本。适用宿主包括 Codex、Claude、Cursor、Gemini CLI,接入前应确认版本、权限和运行环境要求。
  • 使用时需确认虚拟环境、依赖版本和测试入口, 避免误改生产数据。python 属于研究检索类 Skill,可作为该场景下的辅助能力补充。

SKILL.md

Python Programming Guide

Toolchain

  • Type Checking: ty check <FILE_PATH> --output-format concise
  • Lint: ruff check --fix --unsafe-fixes <FILE_PATH>
  • Format: ruff format <FILE_PATH>
  • Run tests: uv run pytest
  • Sync deps: uv sync --upgrade
  • NEVER use python; use uv run instead

References

When deeply modifying code in these areas, you MUST read the corresponding document first:

  • references/async-programming.md - before modifying anyio/async code
  • references/type-hints-cheat-sheet.md - before modifying complex type annotations
  • references/exceptions.md - before modifying error handling
  • references/logging.md - before modifying logging

Code Standards

⚠️ You MUST fully understand and follow ALL rules demonstrated in the code example below BEFORE writing any code. Every RULE and ANTI-PATTERN shown is mandatory.

from __future__ import annotations

# RULE: Use relative imports for intra-package references, strictly limited to 2 levels (. or ..).
# RULE: Use absolute imports for references requiring 3 or more levels of nesting (...) to maintain readability.
from . import internal_module
from .. import parent_helper
from anyio import fail_after
# ANTI-PATTERN: from ...deep_parent import thing  # (Too many dots!)
# ANTI-PATTERN: from mypackage.module import thing  # (Use relative import for internal stuff)

import time
from collections.abc import Awaitable, Callable
from typing import Any, Protocol, TypedDict

import anyio
import attrs
from anyio import fail_after
from loguru import logger

class UserData(TypedDict):
    """
    RULE: Use TypedDict for complex return values instead of plain dict/tuple.

    ANTI-PATTERN: def get_user() -> dict[str, Any]: ...
    ANTI-PATTERN: def get_coords() -> tuple[float, float, str]: ...
    """

    user_id: str
    name: str
    email: str

# RULE: Use Python 3.12+ `type` statement for type aliases
# ANTI-PATTERN: JsonValue: TypeAlias = dict[str, Any] | list[Any] | str | int | float | bool | None
type JsonValue = dict[str, Any] | list[Any] | str | int | float | bool | None

class FetchResult(TypedDict):
    """RULE: Use TypedDict instead of tuple or dict for multi-value returns."""

    data: UserData | None
    error: str | None

class Validator(Protocol):
    """
    RULE: Use Protocol with __call__ for complex callable signatures.

    ANTI-PATTERN: Callable[[dict[str, Any], bool], bool]
    """

    def __call__(self, data: dict[str, Any], *, strict: bool = False) -> bool: ...

@attrs.define
class Config:
    """
    RULE: Use @attrs.define or @attrs.frozen for most classes, unless there is a specific need (e.g., Pydantic models, Exceptions, or TypedDict).

    ANTI-PATTERN: class Foo: def __init__(self, x): self.x = x
    """

    url: str
    timeout: float = 10.0
    headers: dict[str, str] = attrs.field(factory=dict)
    retry: int = attrs.field(default=3)

    @retry.validator
    def _check_retry(self, attribute: attrs.Attribute[int], value: int) -> None:
        """RULE: Use attrs validators for field validation."""
        if value < 0:
            msg = "retry must be >= 0"
            raise ValueError(msg)

@attrs.frozen
class DataSource:
    """
    RULE: Use @attrs.frozen for immutable objects. Prefer composition over inheritance.

    ANTI-PATTERN: class Base: def __getattr__(self, name): ...
    ANTI-PATTERN: class Child(Parent(GrandParent)): ...
    """

    name: str
    endpoint: str
    priority: int = 0

# --- Module: auth ---

class AuthError(Exception):
    """Base exception for the auth module."""

class InvalidTokenError(AuthError):
    pass

# --- Module: service ---

class ServiceError(Exception):
    """
    Base exception for the service module.

    RULE: Define a base exception for each module to isolate error handling.
    RULE: ServiceError and AuthError must be independent (no common base besides Exception).
    """

class NotFoundError(ServiceError):
    """RULE: Create specific exception types only when different handling is needed."""

def log_time[**P, R](func: Callable[P, Awaitable[R]]) -> Callable[P, Awaitable[R]]:
    """
    RULE: Use Python 3.12+ type parameter syntax [T], [**P, R].

    ANTI-PATTERN: T = TypeVar("T")
    ANTI-PATTERN: P = ParamSpec("P")
    ANTI-PATTERN: def func(x: T) -> T: ...
    """

    async def wrapper(*args: P.args, **kwargs: P.kwargs) -> R:
        start = time.perf_counter()
        result = await func(*args, **kwargs)
        print(f"{func.__name__}: {time.perf_counter() - start:.2f}s")
        return result

    return wrapper

@attrs.define
class ApiClient:
    """
    RULE: Use anyio for ALL async code.

    ANTI-PATTERN: asyncio.create_task(coro)
    ANTI-PATTERN: await asyncio.gather(*coros)
    """

    config: Config
    sources: list[DataSource] = attrs.field(factory=list)

    def __attrs_post_init__(self) -> None:
        """RULE: Use __attrs_post_init__ for complex initialization logic."""
        self.sources.sort(key=lambda s: s.priority, reverse=True)

    @log_time
    async def fetch(
        self,
        user_id: str,
        *,
        timeout: float | None = None,
    ) -> UserData:
        """
        RULE: Place parameters with defaults after * to force keyword-only usage.
        RULE: No meaningless return values - raise or return None instead.

        ANTI-PATTERN: return UserData(user_id="", name="", email="")
        """
        timeout = timeout or self.config.timeout
        errors: list[str] = []

        for source in self.sources:
            result = await self._try_fetch_from(source, user_id, timeout)
            if result["data"]:
                return result["data"]
            if result["error"]:
                errors.append(f"{source.name}: {result['error']}")

        msg = f"User {user_id} not found in any source. Errors: {errors}"
        raise NotFoundError(msg)

    async def _try_fetch_from(
        self, source: DataSource, user_id: str, timeout: float
    ) -> FetchResult:
        """
        RULE: No pointless exception wrapping - let unexpected exceptions propagate.

        ANTI-PATTERN: except Exception as e: raise FetchError(str(e)) from e
        """
        try:
            with fail_after(timeout):
                data = await self._fetch_from(source, user_id)
                return FetchResult(data=data, error=None)
        except TimeoutError as e:
            return FetchResult(data=None, error=f"timeout: {e}")
        except ConnectionError as e:
            return FetchResult(data=None, error=f"connection failed: {e}")

    def _safe_shutdown(self) -> None:
        """
        RULE: 'except Exception' is allowed ONLY if necessary (e.g., crash barriers).
        RULE: MUST use '# noqa' AND provide an explanation.

        ANTI-PATTERN:
            try: ...
            except Exception: pass
        """
        try:
            self.config = None
        except Exception:  # noqa: BLE001 to guarantees process exit
            logger.exception("Cleanup failed")

    async def _fetch_from(self, source: DataSource, user_id: str) -> UserData:
        """
        RULE: Use concrete types instead of Any when structure is known.

        ANTI-PATTERN: async def _fetch_from(self, source: Any, user_id: Any) -> Any: ...
        """
        await anyio.sleep(0.1)
        return UserData(
            user_id=user_id, name=f"User {user_id}", email="test@example.com"
        )

    async def fetch_multiple(self, user_ids: list[str]) -> list[UserData]:
        """
        RULE: Parallel tasks MUST use anyio.create_task_group().
        RULE: Handle exceptions with except* (Python 3.11+) or ExceptionGroup.
        """
        results: list[UserData] = []
        failed: list[str] = []

        async def fetch_and_collect(uid: str) -> None:
            try:
                data = await self.fetch(uid)
                results.append(data)
            except NotFoundError as e:
                failed.append(f"{uid}: {e}")

        try:
            async with anyio.create_task_group() as tg:
                for user_id in user_ids:
                    tg.start_soon(fetch_and_collect, user_id)
        except* TimeoutError as eg:
            for exc in eg.exceptions:
                print(f"Timeout in parallel fetch: {exc}")

        if failed:
            print(f"Failed to fetch: {failed}")

        return results

    async def process(self, response: dict[str, Any] | list[Any] | str) -> str:
        """
        RULE: Use match instead of chained if isinstance() checks.
        RULE: Use static attribute access instead of getattr/setattr/hasattr.

        ANTI-PATTERN: if isinstance(x, dict): ... elif isinstance(x, list): ...
        ANTI-PATTERN: value = getattr(obj, "field")
        """
        match response:
            case {"status": "ok", "data": data}:
                return f"Success: {data}"
            case {"error": msg}:
                return f"Error: {msg}"
            case list() as items:
                return f"Got {len(items)} items"
            case str() as message:
                return message
            case _:
                return "Unknown"

# ANTI-PATTERN: def create_wrong(**kwargs: Any) -> ApiClient: return ApiClient(config=Config(**kwargs))

async def create_correct(config: Config) -> ApiClient:
    """RULE: Accept constructed objects directly instead of **kwargs."""
    return ApiClient(config=config)

# ANTI-PATTERN: config_path = Path(__file__).parent / "data" / "config.json"

def load_config_correct() -> dict[str, Any]:
    """RULE: Use importlib.resources.files() instead of __file__ path concatenation."""
    import json
    from importlib.resources import files

    config_text = (files("mypackage") / "data" / "config.json").read_text()
    return json.loads(config_text)

def process_data_shallow(items: list[str]) -> None:
    """
    RULE: Keep indentation shallow (Linux kernel style). Max 3 levels.
    RULE: Use guard clauses (early return/continue) to flatten logic.

    ANTI-PATTERN:
        if items:
            for item in items:
                if item.startswith("valid"):
                    process(item)
    """
    if not items:
        return

    for item in items:
        if not item.startswith("valid"):
            continue

        # process(item)

class SafeResource:
    """
    RULE: APIs owning resources MUST be context managers.
    RULE: Do NOT expose manual open/close methods.

    ANTI-PATTERN:
        res = Resource()
        res.open()  # Don't make users do this
        res.close()
    """

    def __enter__(self) -> SafeResource:
        return self

    def __exit__(self, *args: object) -> None:
        self._cleanup()

    def _cleanup(self) -> None:
        pass

    def use_builtin_resource(self) -> None:
        """
        RULE: Never manually manage resources that support context managers.

        ANTI-PATTERN:
            f = open("file.txt")
            try:
                f.read()
            finally:
                f.close()
        """
        with open("file.txt") as f:
            _ = f.read()

@logger.catch(reraise=True)
async def main() -> None:
    """RULE: Use @logger.catch at entrypoints for automatic exception logging."""
    config = Config(url="https://api.example.com", timeout=5.0)
    sources = [
        DataSource(name="primary", endpoint="https://api1.com", priority=10),
        DataSource(name="backup", endpoint="https://api2.com", priority=5),
    ]
    client = ApiClient(config=config, sources=sources)

    user = await client.fetch("user123")
    logger.info("Fetched user: {}", user["name"])

    users = await client.fetch_multiple(["u1", "u2", "u3"])
    logger.info("Fetched {} users", len(users))

适合场景

01

用户想查找某类 Agent Skill 时

02

需要根据任务场景推荐可安装能力包时

03

需要对比不同来源的安装命令和来源信息时

04

需要参考平台分布和安装热度时

能力概览

能力 1

按任务关键词查找相关 Skills

能力 2

展示可复制的安装命令

能力 3

保留来源站点、仓库和原始说明,方便继续核验

能力 4

补充不同宿主或平台的使用分布数据

安装后应在对应宿主中按原始 README 的触发条件使用;具体调用方式请以来源页面和 README 为准。

平台分布

OpenCode

27.54%
按下载量换算40

Claude Code

23.05%
按下载量换算33

windsurf

16.38%
按下载量换算24

trae

10.57%
按下载量换算15

Codex

7.65%
按下载量换算11

Antigravity

3.15%
按下载量换算5

安全审计

暂无安全审计结果可展示。

权限和风险

只读

该 Skill 主要提供规则、说明或参考内容,本身偏只读;真正读写文件、联网或执行命令仍取决于宿主 Agent 的任务。

安装前确认

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

来源信息

继续浏览同类 Skills