帮助你掌握 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
…
帮助你掌握地道 Rust 模式、所有权与并发实践,编写安全高性能应用。