AgentSkillsCN

python-patterns

此技能适用于 Python 的惯用语法、类型注解、async/await 异步编程、pytest 测试框架、Django 框架、Flask 框架、FastAPI 框架等 Python Web 框架,以及 pandas 数据处理工具。

SKILL.md
--- frontmatter
name: python-patterns
description: This skill should be used for Python idioms, type hints, async/await, pytest, Django, Flask, FastAPI, Python web frameworks, pandas, data processing
whenToUse: Python code, type hints, async, pytest, .py files, Django, Flask, FastAPI, Python web, Python backend, pandas, data scripts
whenNotToUse: Non-Python code, Jupyter-specific (use nbformat docs)
seeAlso:
  - skill: testing-strategies
    when: pytest architecture
  - skill: api-design
    when: FastAPI/Flask endpoints
  - skill: database-patterns
    when: SQLAlchemy models

Python Patterns

Idiomatic Python patterns for Python 3.10+.

Type Hints

python
def process(data: list[str]) -> dict[str, int]:
    return {item: len(item) for item in data}

Dataclasses

python
from dataclasses import dataclass

@dataclass
class User:
    name: str
    email: str
    active: bool = True

Context Managers

python
with open("file.txt") as f:
    content = f.read()

Pytest

python
import pytest

def test_add():
    assert add(2, 3) == 5

@pytest.fixture
def user():
    return User(name="test")

Async/Await

python
async def fetch_data(url: str) -> dict:
    async with aiohttp.ClientSession() as session:
        async with session.get(url) as response:
            return await response.json()

Error Handling

python
try:
    result = risky_operation()
except ValueError as e:
    logger.error(f"Invalid value: {e}")
    raise