Token导航 LogoToken导航TokenDH.com
研究检索需要联网github未标认证来源可访问许可证需确认审计通过

python-guidePython 指南

Agent Skill

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

总安装

275

周安装

11

GitHub Stars

8

下载量

89
CodexClaudeCursorGemini CLI

安装说明

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

GitHub

来源数

2

许可证

unknown

最后核验

2026-05-01

来源状态

来源可访问

安装方式

通过对话安装

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

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

命令行安装

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

skills.shnpx skills
npx skills add https://github.com/ar4mirez/samuel --skill python-guide

简介

作为 Python 开发者的综合参考手册。

  • 覆盖标准库使用、第三方包选型与生态概览。
  • 按应用场景分类整理工具推荐清单。python-guide 属于研究检索类 Skill,可作为该场景下的辅助能力补充。
  • 定期更新以反映最新库版本与社区趋势。适用宿主包括 Codex、Claude、Cursor、Gemini CLI,接入前应确认版本、权限和运行环境要求。
  • 复杂问题优先查阅官方文档再寻求外部帮助。

SKILL.md

Python Guide

Applies to: Python 3.11+, APIs, CLIs, Data Pipelines, Automation

Core Principles

  1. Type Hints Everywhere: All function signatures, class attributes, and module-level variables must have type annotations
  2. Explicit Over Implicit: No * imports, no mutable default arguments, no implicit type coercions
  3. Virtual Environments Always: Never install into system Python; use venv, uv, or poetry
  4. Pytest Over unittest: Use pytest for all testing; fixtures and parametrize over setUp/tearDown
  5. PEP 8 + Ruff: Enforce style mechanically; never rely on manual formatting

Guardrails

Python Version

  • Target Python 3.11+ (use match statements, ExceptionGroup, tomllib)
  • Set requires-python = ">=3.11" in pyproject.toml
  • Use from __future__ import annotations for forward references in 3.11
  • Never use features removed in 3.12+ (distutils, imp, legacy typing aliases)

Code Style

  • Run ruff check and ruff format before every commit
  • Max line length: 88 characters (Black default)
  • Imports: stdlib, blank line, third-party, blank line, local (enforced by isort/ruff)
  • Naming: snake_case for functions/variables, PascalCase for classes, UPPER_SNAKE for constants
  • No bare except: — always catch specific exceptions
  • No mutable default arguments (def f(items=None): not def f(items=[]):)
  • Prefer f-strings over .format() or % formatting
  • Use pathlib.Path instead of os.path for all file operations

Type Hints

  • All public functions MUST have full type annotations (params + return)
  • Use collections.abc types: Sequence, Mapping, Iterable (not List, Dict)
  • Use X | None union syntax (not Optional[X])
  • Use TypeAlias for complex types: UserMap: TypeAlias = dict[str, User]
  • Use Protocol for structural subtyping (duck typing with safety)
  • Use @overload for functions returning different types based on input
  • Run mypy --strict in CI (no type: ignore without explanation)
from collections.abc import Sequence

def find_users(
    ids: Sequence[str],
    *,
    active_only: bool = True,
) -> list[User]:
    """Fetch users by ID list, optionally filtering inactive."""
    ...

Error Handling

  • Never use bare except: or except Exception: without re-raising
  • Create domain-specific exception hierarchies rooted in a base class
  • Use raise... from err to preserve exception chains
  • Log at the boundary, raise in the interior (don't log-and-raise)
  • Use contextlib.suppress() instead of empty except blocks
  • Always close resources with with statements or contextlib.closing

Dependencies

  • Define all deps in pyproject.toml (not setup.py or bare requirements.txt)
  • Pin exact versions in lock files (uv.lock, poetry.lock, pip-compile output)
  • Keep requirements.txt only as a generated artifact, never hand-edited
  • Separate [project.optional-dependencies] for dev, test, docs
  • Audit with pip-audit or safety before adding new packages
  • Prefer stdlib solutions: tomllib, pathlib, dataclasses, enum, logging

Project Structure

myproject/
├── src/
│   └── myproject/          # Importable package (src layout)
│       ├── __init__.py
│       ├── py.typed         # PEP 561 marker for type stubs
│       ├── domain/          # Business logic, entities
│       │   ├── __init__.py
│       │   ├── models.py
│       │   └── exceptions.py
│       ├── service/         # Application services
│       │   └── __init__.py
│       ├── repository/      # Data access layer
│       │   └── __init__.py
│       └── api/             # HTTP/CLI interface
│           └── __init__.py
├── tests/
│   ├── conftest.py          # Shared fixtures
│   ├── unit/
│   └── integration/
├── pyproject.toml           # Single source of truth for config
├── uv.lock                  # Or poetry.lock
└── README.md
  • Use src layout (src/myproject/) to prevent accidental local imports
  • Keep conftest.py at test root for shared fixtures; nest for scope
  • Include py.typed marker for downstream type checking
  • No __init__.py in tests/ (pytest discovers without it)
  • One module = one responsibility; split at ~200 lines

Error Handling Patterns

Exception Hierarchy

class AppError(Exception):
    """Base exception for the application."""

    def __init__(self, message: str, *, code: str = "UNKNOWN") -> None:
        super().__init__(message)
        self.code = code

class NotFoundError(AppError):
    """Raised when a requested resource does not exist."""

    def __init__(self, resource: str, identifier: str) -> None:
        super().__init__(
            f"{resource} with id '{identifier}' not found",
            code="NOT_FOUND",
        )
        self.resource = resource
        self.identifier = identifier

class ValidationError(AppError):
    """Raised when input data fails validation."""

    def __init__(self, field: str, reason: str) -> None:
        super().__init__(
            f"Validation failed for '{field}': {reason}",
            code="VALIDATION_ERROR",
        )

Context Managers for Cleanup

from contextlib import contextmanager
from collections.abc import Generator

@contextmanager
def managed_connection(url: str) -> Generator[Connection, None, None]:
    conn = Connection(url)
    try:
        conn.open()
        yield conn
    except ConnectionError as err:
        raise AppError("Database unavailable") from err
    finally:
        conn.close()

Error Chaining

def get_user(user_id: str) -> User:
    try:
        row = db.fetch_one("SELECT * FROM users WHERE id = %s", (user_id,))
    except DatabaseError as err:
        raise AppError(f"Failed to fetch user {user_id}") from err
    if row is None:
        raise NotFoundError("User", user_id)
    return User.from_row(row)

Testing

Standards

  • Test files: test_*.py (same name as module: models.py -> test_models.py)
  • Test functions: test_<unit>_<scenario>_<expected> (e.g., test_get_user_not_found_raises)
  • Use conftest.py for fixtures shared across a directory
  • Coverage target: >80% for business logic, >60% overall
  • Mark slow tests: @pytest.mark.slow and exclude from default runs
  • No unittest.TestCase — use plain functions with pytest assertions
  • Use tmp_path fixture for file operations (auto-cleanup)

Fixtures and Parametrize

import pytest
from myproject.domain.models import User

@pytest.fixture
def sample_user() -> User:
    return User(id="u-123", name="Ada Lovelace", email="ada@example.com")

@pytest.mark.parametrize(
    ("email", "is_valid"),
    [
        ("user@example.com", True),
        ("user@.com", False),
        ("", False),
        ("user@domain", False),
    ],
)
def test_validate_email(email: str, is_valid: bool) -> None:
    assert validate_email(email) == is_valid

def test_get_user_returns_user(sample_user: User) -> None:
    repo = InMemoryUserRepo(users=[sample_user])
    result = repo.get("u-123")
    assert result == sample_user

def test_get_user_not_found_raises() -> None:
    repo = InMemoryUserRepo(users=[])
    with pytest.raises(NotFoundError, match="User.*not found"):
        repo.get("nonexistent")

Mocking External Dependencies

from unittest.mock import AsyncMock, patch

async def test_send_notification_retries_on_failure() -> None:
    mock_client = AsyncMock()
    mock_client.post.side_effect = [ConnectionError, None]

    with patch("myproject.service.notify.http_client", mock_client):
        await send_notification(user_id="u-123", message="hello")

    assert mock_client.post.call_count == 2

Tooling

pyproject.toml Configuration

[project]
name = "myproject"
requires-python = ">=3.11"

[project.optional-dependencies]
dev = ["ruff", "mypy", "pytest", "pytest-cov", "pytest-asyncio"]

[tool.ruff]
target-version = "py311"
line-length = 88

[tool.ruff.lint]
select = [
    "E",    # pycodestyle errors
    "W",    # pycodestyle warnings
    "F",    # pyflakes
    "I",    # isort
    "N",    # pep8-naming
    "UP",   # pyupgrade
    "B",    # flake8-bugbear
    "S",    # flake8-bandit (security)
    "A",    # flake8-builtins
    "C4",   # flake8-comprehensions
    "SIM",  # flake8-simplify
    "RUF",  # ruff-specific rules
]

[tool.mypy]
strict = true
warn_return_any = true
disallow_untyped_defs = true

[tool.pytest.ini_options]
testpaths = ["tests"]
markers = ["slow: marks tests as slow (deselect with '-m \"not slow\"')"]
asyncio_mode = "auto"

[tool.coverage.run]
source = ["src/myproject"]
branch = true

[tool.coverage.report]
fail_under = 60
show_missing = true
exclude_lines = ["if TYPE_CHECKING:", "pragma: no cover"]

Essential Commands

ruff check .                 # Lint (replaces flake8, isort, pyupgrade)
ruff format .                # Format (replaces black)
mypy .                       # Type check (strict mode)
pytest                       # Run all tests
pytest --cov=src -q          # Coverage summary
pytest -m "not slow"         # Skip slow tests
pip-audit                    # Check dependencies for vulnerabilities
python -m build              # Build sdist + wheel

Advanced Topics

For detailed patterns and examples, see:

External References

适合场景

01

用户想查找某类 Agent Skill 时

02

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

03

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

能力概览

能力 1

按任务关键词查找相关 Skills

能力 2

展示可复制的安装命令

能力 3

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

能力 4

展示第三方安全扫描或审计结果

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

平台分布

Codex

36.04%
按下载量换算32

Claude

27.69%
按下载量换算25

Cursor

18.66%
按下载量换算17

Gemini CLI

9.49%
按下载量换算8

安全审计

Gen Agent Trust Hub

通过

Socket

通过

Snyk

通过

权限和风险

需要联网

该 Skill 可能需要联网访问来源站点、仓库或外部 API;具体网络访问范围需要结合源码和 README 复核。

安装前确认

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

来源信息

继续浏览同类 Skills