dignified-python-313 by c00ldudenoonan/economic-data-project
npx skills add https://github.com/c00ldudenoonan/economic-data-project --skill dignified-python-313编写明确、可预测的代码,使其在恰当的边界处快速失败。
| 如果你打算写... | 检查此规则 |
|---|---|
try: 或 except: | → 异常处理 - 默认:让异常向上冒泡 |
from __future__ import annotations | → 禁止 - Python 3.13+ 不需要它 |
List[...], Dict[...], Union[...] |
广告位招租
在这里展示您的产品或服务
触达数万 AI 开发者,精准高效
→ 使用 list[...], dict[...], `X |
dict[key] 而不检查 | → 使用 if key in dict: 或 .get() |
path.resolve() 或 path.is_relative_to() | → 先检查 path.exists() |
typing.Protocol | → 使用 abc.ABC 代替 |
from .module import | → 仅使用绝对导入 |
__all__ = ["..."] 在 __init__.py 中 | → 参见 references/core-standards.md#code-in-init py-and-all -exports |
print(...) 在 CLI 代码中 | → 使用 click.echo() |
subprocess.run(...) | → 添加 check=True |
@property 包含 I/O 或昂贵计算 | → 参见 references/core-standards.md#performance-expectations |
| 具有许多可选参数的函数 | → 参见 references/code-smells-dagster.md |
使用 repr() 进行排序或哈希 | → 参见 references/code-smells-dagster.md |
| 到处传递的上下文对象 | → 参见 references/code-smells-dagster.md |
| 具有 10+ 个局部变量的函数 | → 参见 references/code-smells-dagster.md |
| 具有 50+ 个方法的类 | → 参见 references/code-smells-dagster.md |
始终使用 LBYL(三思而后行),绝不使用 EAFP
# ✅ 正确:行动前检查
if key in mapping:
value = mapping[key]
else:
handle_missing_key()
# ❌ 错误:使用异常进行控制流
try:
value = mapping[key]
except KeyError:
handle_missing_key()
详情 : 完整模式请参见 references/core-standards.md#exception-handling
禁止 : from __future__ import annotations
# ✅ 正确:现代 Python 3.13+ 语法
def process(items: list[str]) -> dict[str, int]: ...
def find_user(id: int) -> User | None: ...
# ❌ 错误:旧语法
from typing import List, Dict, Optional
def process(items: List[str]) -> Dict[str, int]: ...
详情 : 所有模式请参见 references/core-standards.md#type-annotations
# ✅ 正确:先检查存在性
if path.exists():
resolved = path.resolve()
# ❌ 错误:使用异常
try:
resolved = path.resolve()
except OSError:
pass
详情 : 参见 references/core-standards.md#path-operations
# ✅ 正确:使用 ABC
from abc import ABC, abstractmethod
class MyOps(ABC):
@abstractmethod
def operation(self) -> None: ...
# ❌ 错误:使用 Protocol
from typing import Protocol
详情 : 参见 references/core-standards.md#dependency-injection
所有导入必须位于模块级别,除非是为了防止循环导入
# ✅ 正确:模块级别,绝对导入
from erk.config import load_config
from pathlib import Path
import click
# ❌ 错误:行内导入(除非为防止循环导入)
def my_function():
from erk.config import load_config # 错误,除非是循环导入
return load_config()
# ❌ 错误:相对导入
from .config import load_config
例外 : 行内导入仅在防止循环导入时可接受。必须说明原因:
def create_context():
# 行内导入以避免与测试的循环依赖
from tests.fakes.gitops import FakeGitOps
return FakeGitOps()
详情 : 参见 references/core-standards.md#imports
# ❌ 错误:静默回退
try:
result = primary_method()
except:
result = fallback_method() # 未经测试,脆弱
# ✅ 正确:让错误向上冒泡
result = primary_method()
详情 : 参见 references/core-standards.md#anti-patterns
references/core-standards.md:@property 或 __len__ 时(性能预期)references/code-smells-dagster.md:repr() 时(字符串表示滥用)references/patterns-reference.md:本技能使用三级加载系统:
Claude 仅根据当前任务需要加载参考文件。参考文件包含:
core-standards.md : 来自本技能的基础 Python 模式code-smells-dagster.md : 来自 Dagster Labs 的经过生产测试的反模式patterns-reference.md : 常见的实现模式和示例编写庄重的 Python 代码,使其:
默认立场:
即将编写 Python 代码?
try/except? * 你能改用 LBYL 吗? → 那样做
* 这是错误边界吗? → 可以处理
* 否则 → 让它冒泡
2. 使用类型提示?
* 使用 `list[str]`, `str | None`,而非 `List`, `Optional`
* **不要** `from __future__ import annotations`
3. 处理路径?
* 在 `.resolve()` 前检查 `.exists()`
* 使用 `pathlib.Path`,而非 `os.path`
4. 编写 CLI 代码?
* 使用 `click.echo()`,而非 `print()`
* 使用 `raise SystemExit(1)` 退出
5. 参数太多?
* 参见 `references/code-smells-dagster.md#parameter-anxiety`
6. 类变得太大?
* 参见 `references/code-smells-dagster.md#god-classes`
编写 try/except 前:
使用类型提示前:
list, dict, |)typing 导入?路径操作前:
.resolve() 前检查了 .exists() 吗?pathlib.Path 吗?encoding="utf-8" 吗?添加向后兼容性前:
| 场景 | 首选方法 | 避免 |
|---|---|---|
| 字典访问 | if key in dict: 或 .get(key, default) | try: dict[key] except KeyError: |
| 文件存在性 | if path.exists(): | try: open(path) except FileNotFoundError: |
| 类型检查 | if isinstance(obj, Type): | try: obj.method() except AttributeError: |
| 值验证 | if is_valid(value): | try: process(value) except ValueError: |
| 路径解析 | if path.exists(): path.resolve() | try: path.resolve() except OSError: |
references/core-standards.md - 详细的 LBYL 模式,类型注解,导入references/code-smells-dagster.md - 经过生产测试的反模式references/patterns-reference.md - CLI,文件 I/O,数据类每周安装数
1
仓库
GitHub 星标数
38
首次出现
今天
安全审计
安装于
zencoder1
amp1
cline1
openclaw1
opencode1
cursor1
Write explicit, predictable code that fails fast at proper boundaries.
| If you're about to write... | Check this rule |
|---|---|
try: or except: | → Exception Handling - Default: let exceptions bubble |
from __future__ import annotations | → FORBIDDEN - Python 3.13+ doesn't need it |
List[...], Dict[...], Union[...] | → Use list[...], dict[...], `X |
dict[key] without checking | → Use if key in dict: or .get() |
path.resolve() or path.is_relative_to() | → Check path.exists() first |
typing.Protocol | → Use abc.ABC instead |
from .module import | → Use absolute imports only |
__all__ = ["..."] in __init__.py | → See references/core-standards.md#code-in-init py-and-all -exports |
print(...) in CLI code | → Use click.echo() |
subprocess.run(...) | → Add check=True |
@property with I/O or expensive computation | → See references/core-standards.md#performance-expectations |
| Function with many optional parameters | → See references/code-smells-dagster.md |
repr() for sorting or hashing | → See references/code-smells-dagster.md |
| Context object passed everywhere | → See references/code-smells-dagster.md |
| Function with 10+ local variables | → See references/code-smells-dagster.md |
| Class with 50+ methods | → See references/code-smells-dagster.md |
ALWAYS use LBYL (Look Before You Leap), NEVER EAFP
# ✅ CORRECT: Check before acting
if key in mapping:
value = mapping[key]
else:
handle_missing_key()
# ❌ WRONG: Using exceptions for control flow
try:
value = mapping[key]
except KeyError:
handle_missing_key()
Details : See references/core-standards.md#exception-handling for complete patterns
FORBIDDEN : from __future__ import annotations
# ✅ CORRECT: Modern Python 3.13+ syntax
def process(items: list[str]) -> dict[str, int]: ...
def find_user(id: int) -> User | None: ...
# ❌ WRONG: Legacy syntax
from typing import List, Dict, Optional
def process(items: List[str]) -> Dict[str, int]: ...
Details : See references/core-standards.md#type-annotations for all patterns
# ✅ CORRECT: Check exists first
if path.exists():
resolved = path.resolve()
# ❌ WRONG: Using exceptions
try:
resolved = path.resolve()
except OSError:
pass
Details : See references/core-standards.md#path-operations
# ✅ CORRECT: Use ABC
from abc import ABC, abstractmethod
class MyOps(ABC):
@abstractmethod
def operation(self) -> None: ...
# ❌ WRONG: Using Protocol
from typing import Protocol
Details : See references/core-standards.md#dependency-injection
ALL imports must be at module level unless preventing circular imports
# ✅ CORRECT: Module-level, absolute imports
from erk.config import load_config
from pathlib import Path
import click
# ❌ WRONG: Inline imports (unless for circular import prevention)
def my_function():
from erk.config import load_config # WRONG unless circular import
return load_config()
# ❌ WRONG: Relative imports
from .config import load_config
Exception : Inline imports are ONLY acceptable when preventing circular imports. Always document why:
def create_context():
# Inline import to avoid circular dependency with tests
from tests.fakes.gitops import FakeGitOps
return FakeGitOps()
Details : See references/core-standards.md#imports
# ❌ WRONG: Silent fallback
try:
result = primary_method()
except:
result = fallback_method() # Untested, brittle
# ✅ CORRECT: Let error bubble up
result = primary_method()
Details : See references/core-standards.md#anti-patterns
references/core-standards.md when:@property or __len__ (performance expectations)references/code-smells-dagster.md when:repr() programmatically (string representation abuse)references/patterns-reference.md when:This skill uses a three-level loading system:
Claude loads reference files only when needed based on the current task. The reference files contain:
core-standards.md : Foundational Python patterns from this skillcode-smells-dagster.md : Production-tested anti-patterns from Dagster Labspatterns-reference.md : Common implementation patterns and examplesWrite dignified Python code that:
Default stances:
About to write Python code?
Usingtry/except?
Using type hints?
list[str], str | None, not List, Optionalfrom __future__ import annotationsWorking with paths?
.exists() before .resolve()Before writing try/except:
Before using type hints:
list, dict, |)typing imports except essentials?Before path operations:
.exists() before .resolve()?pathlib.Path?encoding="utf-8"?Before adding backwards compatibility:
| Scenario | Preferred Approach | Avoid |
|---|---|---|
| Dictionary access | if key in dict: or .get(key, default) | try: dict[key] except KeyError: |
| File existence | if path.exists(): | try: open(path) except FileNotFoundError: |
| Type checking | if isinstance(obj, Type): |
references/core-standards.md - Detailed LBYL patterns, type annotations, importsreferences/code-smells-dagster.md - Production-tested anti-patternsreferences/patterns-reference.md - CLI, file I/O, dataclassesWeekly Installs
1
Repository
GitHub Stars
38
First Seen
Today
Security Audits
Gen Agent Trust HubPassSocketPassSnykPass
Installed on
zencoder1
amp1
cline1
openclaw1
opencode1
cursor1
agent-browser 浏览器自动化工具 - Vercel Labs 命令行网页操作与测试
147,400 周安装
pathlib.Path, not os.pathWriting CLI code?
click.echo(), not print()raise SystemExit(1)Too many parameters?
references/code-smells-dagster.md#parameter-anxietyClass getting large?
references/code-smells-dagster.md#god-classestry: obj.method() except AttributeError: |
| Value validation | if is_valid(value): | try: process(value) except ValueError: |
| Path resolution | if path.exists(): path.resolve() | try: path.resolve() except OSError: |