python-best-practices-sh-kclhru
Installation
Review the source and dependencies with a prompt. A package is available to download.
Install with an AI assistant
Copy the prompt so your assistant can review the pinned revision and dependencies first.
View promptHide prompt
Check whether SkillPI Skill Finder is installed for your current agent. If it is missing, install and enable it using the official instructions at https://github.com/Findskills/skillpi. Then use Skill Finder to locate and install "python-best-practices-sh-kclhru" from this exact SkillPI detail page: https://skillpi.com/skills/deepskill-050dd7c1d02d718efc47ce536dd232f53a8e3c6c4d5a6f01a0893bd7ad5c7d64. Verify the upstream source and version against https://skillhub.cn/skills/user_3c6cb52e/python-best-practices-sh-kclhru before installing. If they do not match, stop and report the mismatch. Report the installed path and source version.
Source and setup
skillhub.cn
Setup guidance pending
See the original source for supported tools, dependencies, and permissions.
Installation test pending
Skill dedicated to Pythonbestpractices, designed to help AI Agents efficiently perform tasks related to Python best practices.
Introduction source: third_party · user_3c6cb52e · 1.0.0 Reference
SkillPi interpretation
- Tasks
- def firstT -> T: return items[0]
- Inputs and outputs
- Rule: Use dataclasses for domain models and internal structs. Use Pydantic for API boundaries, config files, and external data parsing.
- Testing
- Not tested
Browse files
Frontmatter
name: Pythonbestpractices
slug: python-best-practices
version: 1.0.0
displayName: Pythonbestpractices
description: >
Pythonbestpractices专用技能,帮助AI Agent高效完成相关任务。
Pythonbestpractices专用技能,帮助AI Agent高效完成相关任务。
summary: "Pythonbestpractices专用技能,帮助AI Agent高效完成相关任务。"
license: MIT
category: 开发者工具
framework:
- Claude Code
- Codex
- Hermes Agent
- OpenClaw
- QClaw
- WorkBuddy
platform: multi-platform
homepage: "https://github.com/1991513ccie-png"
repository: "https://github.com/1991513ccie-png"Python Best Practices
Type Hints (3.12+ Syntax)
# Use built-in generics (3.9+), no need for typing.List, typing.Dict
def process_items(items: list[str]) -> dict[str, int]:
return {item: len(item) for item in items}
# Union with | syntax (3.10+)
def find_user(user_id: int) -> User | None:
...
# Type parameter syntax (3.12+)
type Vector[T] = list[T]
type Matrix[T] = list[Vector[T]]
def first[T](items: list[T]) -> T:
return items[0]
# TypedDict for structured dicts
from typing import TypedDict
class UserResponse(TypedDict):
id: int
name: str
email: str
active: bool
Always type function signatures. Use mypy --strict or pyright in CI. Use type: ignore comments sparingly with justification.
Dataclasses vs Pydantic
Dataclasses (internal data, no validation needed)
from dataclasses import dataclass, field
@dataclass(frozen=True, slots=True)
class Point:
x: float
y: float
def distance_to(self, other: "Point") -> float:
return ((self.x - other.x) ** 2 + (self.y - other.y) ** 2) ** 0.5
@dataclass
class Config:
host: str = "localhost"
port: int = 8080
tags: list[str] = field(default_factory=list)
Use frozen=True for immutable value objects. Use slots=True for memory efficiency.
Pydantic (external input, validation required)
from pydantic import BaseModel, Field, field_validator
class CreateUserRequest(BaseModel):
model_config = {"strict": True}
email: str = Field(max_length=255)
name: str = Field(min_length=1, max_length=100)
age: int = Field(ge=13, le=150)
@field_validator("email")
@classmethod
def validate_email(cls, v: str) -> str:
if "@" not in v:
raise ValueError("Invalid email format")
return v.lower()
Rule: Use dataclasses for domain models and internal structs. Use Pydantic for API boundaries, config files, and external data parsing.
Async Patterns
import asyncio
import httpx
async def fetch_user(client: httpx.AsyncClient, user_id: int) -> User:
response = await client.get(f"/users/{user_id}")
response.raise_for_status()
return User(**response.json())
async def fetch_all_users(user_ids: list[int]) -> list[User]:
async with httpx.AsyncClient(base_url="https://api.example.com") as client:
tasks = [fetch_user(client, uid) for uid in user_ids]
return await asyncio.gather(*tasks)
async def process_with_semaphore(items: list[str], max_concurrent: int = 10):
semaphore = asyncio.Semaphore(max_concurrent)
async def bounded_process(item: str):
async with semaphore:
return await process_item(item)
return await asyncio.gather(*[bounded_process(i) for i in items])
Rules:
- Use
httpxinstead ofrequestsfor async HTTP - Use
asyncio.gatherfor concurrent tasks,asyncio.Semaphorefor rate limiting - Never call blocking I/O in async functions (use
asyncio.to_threadfor legacy code) - Use
async withfor resource management (connections, sessions)
Project Structure
my-project/
src/
my_project/
__init__.py
main.py
models.py
services/
__init__.py
user_service.py
api/
__init__.py
routes.py
tests/
conftest.py
test_models.py
test_services/
test_user_service.py
pyproject.toml
Use src layout to prevent accidental imports from the project root.
pyproject.toml
[build-system]
requires = ["hatchling"]
build-backend = "hatchling.build"
[project]
name = "my-project"
version = "1.0.0"
requires-python = ">=3.12"
dependencies = [
"httpx>=0.27",
"pydantic>=2.0",
]
[project.optional-dependencies]
dev = [
"pytest>=8.0",
"pytest-cov",
"pytest-asyncio",
"mypy",
"ruff",
]
[project.scripts]
my-project = "my_project.main:cli"
[tool.ruff]
line-length = 100
target-version = "py312"
[tool.ruff.lint]
select = ["E", "F", "I", "N", "UP", "B", "SIM", "RUF"]
[tool.mypy]
strict = true
[tool.pytest.ini_options]
asyncio_mode = "auto"
testpaths = ["tests"]
Use pyproject.toml for all tool configuration. Use Ruff instead of flake8 + isort + black (single tool, 10-100x faster).
Virtual Environments
# Use uv for fast dependency management
uv venv
uv pip install -e ".[dev]"
# Or standard venv
python -m venv .venv
source .venv/bin/activate
pip install -e ".[dev]"
Always use virtual environments. Never install packages globally. Pin exact versions in a lockfile (uv.lock or requirements.txt generated from pip freeze).
Testing with pytest
import pytest
from unittest.mock import AsyncMock, patch
@pytest.fixture
def user_service(db_session):
return UserService(session=db_session)
async def test_create_user_returns_user_with_hashed_password(user_service):
user = await user_service.create(email="test@example.com", password="secret")
assert user.email == "test@example.com"
assert user.password_hash != "secret"
async def test_create_user_rejects_duplicate_email(user_service):
await user_service.create(email="test@example.com", password="secret")
with pytest.raises(DuplicateEmailError):
await user_service.create(email="test@example.com", password="other")
@pytest.fixture
def mock_http_client():
client = AsyncMock(spec=httpx.AsyncClient)
client.get.return_value = httpx.Response(200, json={"id": 1, "name": "Alice"})
return client
async def test_fetch_user_parses_response(mock_http_client):
user = await fetch_user(mock_http_client, user_id=1)
assert user.name == "Alice"
mock_http_client.get.assert_called_once_with("/users/1")
Use conftest.py for shared fixtures. Use pytest.mark.parametrize for test variations. Use tmp_path fixture for file system tests.
Pythonic Idioms
# Unpacking
first, *rest = items
x, y = point
# Comprehensions over map/filter
squares = [x**2 for x in numbers if x > 0]
lookup = {u.id: u for u in users}
# Context managers for resource cleanup
with open(path) as f:
data = f.read()
# Walrus operator for assign-and-test
if (match := pattern.search(text)) is not None:
process(match.group(1))
# Structural pattern matching (3.10+)
match command:
case {"action": "move", "direction": d}:
move(d)
case {"action": "quit"}:
sys.exit(0)
case _:
raise ValueError(f"Unknown command: {command}")
Error Handling
class AppError(Exception):
def __init__(self, message: str, code: str):
super().__init__(message)
self.code = code
class NotFoundError(AppError):
def __init__(self, resource: str, id: str):
super().__init__(f"{resource} {id} not found", "NOT_FOUND")
# Specific exceptions, never bare except
try:
user = await get_user(user_id)
except NotFoundError:
return {"error": "User not found"}, 404
except DatabaseError as e:
logger.exception("Database error fetching user")
return {"error": "Internal error"}, 500
Never use bare except:. Catch the most specific exception. Use logger.exception() to include tracebacks. Define custom exception hierarchies for your application.
Current listing version
1.0.0
Safety and assessment details
Quality assessment
Out of 100 · Assessment report from SkillPi LAB.
Highlights
- 提供全面且实用的 Python 开发最佳实践指南
- 涵盖现代 Python 特性(3.10+ 类型语法、模式匹配等)
- 包含项目结构、测试、错误处理等工程化建议
Areas to improve
-
description写错位置 Reported severity: Minor
frontmatter 和 skill_body 中 description 字段内容重复且模糊,未明确说明具体触发场景或用户意图
Recommendation: 建议明确描述 Skill 的具体用途和触发条件,例如:'当用户需要 Python 代码规范建议、项目结构指导或最佳实践参考时触发'
Areas to improve
-
缺少When to Use章节 Reported severity: Minor
文档缺少明确的使用场景说明章节
Recommendation: 建议添加 'When to Use' 或 '适用场景' 章节,说明在什么情况下用户应该使用此 Skill
-
文档过长 Reported severity: Minor
skill_body 内容超过 500 行,影响阅读体验
Recommendation: 建议将部分内容拆分为多个子文档或通过链接引用,保持主文档简洁
Highlights
- 文档结构清晰,分章节组织内容
- 包含大量实用的代码示例
- frontmatter 元数据完整
Highlights
- 提供的最佳实践建议符合当前 Python 生态标准
- 推荐的工具链(uv、ruff、pytest等)是当前主流选择
- 代码示例语法正确,符合 Python 3.12+ 规范
The arithmetic mean of the first four original scores, rounded to a whole number.
Static text checks
100 / 100 · skillpi-20261123-no-r3-v1
No current rules matched the text.
This score reflects rule matches in the text and is provided for reference before use. It excludes attachments and runtime behavior.
Permissions and checks before use
Automatically summarized from this main document. Matches may be examples or defensive advice; they are not actual permission declarations. Attachments, external dependencies and runtime behavior are not covered.
-
Install or fetch external dependencies
Use official sources and pin versions. Check install scripts in an isolated environment. This document check does not cover code downloaded later.
Mentioned in main document · lines 207, 212
Domains or addresses referenced in the document
These addresses may be documentation links or examples, not an approved network allowlist. Verify actual destinations and outgoing data before use.
- api.example.com
- github.com
Security rating and access scope
safe · Static evidence review; not a runtime safety guarantee.
Before use, confirm and authorize actual file access, external services and network destinations in your host. This review grants no runtime permissions.
User discussion
No verified reviews yet.