帮助你掌握 Pythonic 写法、类型标注与规范实践,写出更稳健易维护的 Python 代码。
复制安装指令,让 AI 自动完成配置 · 推荐新手
请帮我安装 askskill 上的 "python-patterns" 技能: 1. 下载 https://raw.githubusercontent.com/affaan-m/ECC/main/skills/python-patterns/SKILL.md 2. 保存为 ~/.claude/skills/python-patterns/SKILL.md 3. 装好后重载技能,告诉我可以用了
请把下面这段 Python 代码重构得更符合 Pythonic 风格,遵循 PEP 8,并说明你做了哪些改进: [粘贴代码]
返回更简洁、规范的 Python 代码,并附上逐项优化说明。
请为下面的 Python 函数补全类型标注,必要时调整函数签名,并指出哪些地方有潜在类型风险: [粘贴代码]
输出带完整类型标注的代码,以及类型安全改进建议。
请审查这段 Python 模块,从可读性、异常处理、性能、命名和可维护性几个方面给出改进建议,并提供修改后的版本: [粘贴代码]
给出结构化评审意见,并附上按最佳实践修改后的代码版本。
Idiomatic Python patterns and best practices for building robust, efficient, and maintainable applications.
Python prioritizes readability. Code should be obvious and easy to understand.
# Good: Clear and readable
def get_active_users(users: list[User]) -> list[User]:
"""Return only active users from the provided list."""
return [user for user in users if user.is_active]
# Bad: Clever but confusing
def get_active_users(u):
return [x for x in u if x.a]
Avoid magic; be clear about what your code does.
# Good: Explicit configuration
import logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
# Bad: Hidden side effects
import some_module
some_module.setup() # What does this do?
Python prefers exception handling over checking conditions.
# Good: EAFP style
def get_value(dictionary: dict, key: str, default_value: Any = None) -> Any:
try:
return dictionary[key]
except KeyError:
return default_value
# Bad: LBYL (Look Before You Leap) style
def get_value(dictionary: dict, key: str, default_value: Any = None) -> Any:
if key in dictionary:
return dictionary[key]
else:
return default_value
from typing import Optional, List, Dict, Any
def process_user(
user_id: str,
data: Dict[str, Any],
active: bool = True
) -> Optional[User]:
"""Process a user and return the updated User or None."""
if not active:
return None
return User(user_id, data)
# Python 3.9+ - Use built-in types
def process_items(items: list[str]) -> dict[str, int]:
return {item: len(item) for item in items}
# Python 3.8 and earlier - Use typing module
from typing import List, Dict
def process_items(items: List[str]) -> Dict[str, int]:
return {item: len(item) for item in items}
from typing import TypeVar, Union
# Type alias for complex types
JSON = Union[dict[str, Any], list[Any], str, int, float, bool, None]
def parse_json(data: str) -> JSON:
return json.loads(data)
# Generic types
T = TypeVar('T')
def first(items: list[T]) -> T | None:
"""Return the first item or None if list is empty."""
return items[0] if items else None
from typing import Protocol
class Renderable(Protocol):
def render(self) -> str:
"""Render the object to a string."""
def render_all(items: list[Renderable]) -> str:
"""Render all items that implement the Renderable protocol."""
return "\n".join(item.render() for item in items)
# Good: Catch specific exceptions
def load_config(path: str) -> Config:
try:
with open(path) as f:
return Config.from_json(f.read())
except FileNotFoundError as e:
raise ConfigError(f"Config file not found: {path}") from e
except json.JSONDecodeError as e:
raise ConfigError(f"Invalid JSON in config: {path}") from e
# Bad: Bare except
def load_config(path: str) -> Config:
try:
with open(path) as f:
return Config.from_json(f.read())
except:
return None # Silent failure!
def process_data(data: str) -> Result:
try:
parsed = json.loads(data)
except json.JSONDecodeError as e:
# Chain exceptions to preserve the traceback
raise ValueError(f"Failed to parse data: {data}") from e
…
通过逐步细化检索上下文,提升子代理任务理解与结果质量。
帮助你设计与优化 Spring Boot 后端架构、接口与服务实现。
基于多源网页检索与综合分析,生成带引用和来源标注的深度研究报告
用于管理 Uncloud 集群,完成部署、入口配置、扩缩容与运维排障。
为 orch 系列技能统一编排研发流程与人工审批关卡
帮助团队为医疗应用设计符合PHI/PII要求的数据安全与合规方案
提供地道 Go 语言模式与最佳实践,帮助构建健壮高效且易维护的应用
提供地道 Kotlin 模式与最佳实践,帮助构建健壮高效且易维护的应用。
帮助开发者掌握地道 Rust 模式、所有权、并发与错误处理实践
提供地道的 C# 与 .NET 架构模式、异步编程和依赖注入实践建议
提供现代 Perl 5.36+ 惯用法与最佳实践,帮助编写稳健且易维护的应用。
提供 PyTorch 深度学习模式与最佳实践,帮助构建高效可复现的训练流程。