提供符合 Pythonic 风格与最佳实践的代码指导,帮助构建健壮易维护的 Python 应用。
复制安装指令,让 AI 自动完成配置 · 推荐新手
请帮我安装 askskill 上的 "python-patterns" 技能: 1. 下载 https://raw.githubusercontent.com/affaan-m/ECC/main/docs/ja-JP/skills/python-patterns/SKILL.md 2. 保存为 ~/.claude/skills/python-patterns/SKILL.md 3. 装好后重载技能,告诉我可以用了
请将这段 Python 代码重构为更 Pythonic 的写法,遵循 PEP 8,补充类型提示,并说明你做了哪些改进:[粘贴代码]
返回重构后的代码、类型标注,以及按最佳实践给出的修改说明。
请检查下面的 Python 函数,找出潜在异常、边界条件和可维护性问题,并给出更稳健的实现版本:[粘贴函数]
输出问题清单、风险说明,以及更安全可靠的改进代码。
基于 PEP 8、类型提示和常见 Python 最佳实践,为这个模块提出代码规范改进建议,并给出示例修改:[粘贴模块代码]
给出规范化建议、可执行的修改示例,以及提升可读性与可维护性的说明。
堅牢で効率的かつ保守可能なアプリケーションを構築するための慣用的なPythonパターンとベストプラクティス。
Pythonは可読性を優先します。コードは明白で理解しやすいものであるべきです。
# 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]
魔法を避け、コードが何をしているかを明確にしましょう。
# 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は条件チェックよりも例外処理を好みます。
# 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
class AppError(Exception):
"""Base exception for all application errors."""
pass
class ValidationError(AppError):
"""Raised when input validation fails."""
pass
class NotFoundError(AppError):
"""Raised when a requested resource is not found."""
pass
# Usage
def get_user(user_id: str) -> User:
…
提供地道 Go 设计模式与最佳实践,帮助编写健壮高效且易维护的应用