python-dev

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Python Development

Python 开发

Quick Reference

快速参考

CategoryRuleHow to Apply
SafetyNever use mutable default argumentsUse
None
as default; initialise inside the function body
Always use context managers
with
for files, DB connections, locks — no manual
close()
No bare
except:
Catch specific exceptions; bare
except
swallows
KeyboardInterrupt
Never
eval()
/
exec()
on input
Code injection; use
ast.literal_eval
or structured parsers
pathlib.Path
over
os.path
Cross-platform, composable, readable
Type SafetyType-hint all function signaturesEnables mypy, IDE completion, and self-documenting APIs
Optional[X]
/
X | None
for nullable
Caller must handle
None
; don't let it drift silently
Avoid
Any
Use
Union
,
TypeVar
, or
Protocol
to preserve type information
mypy --strict
in CI
Strict mode catches implicit
Any
, missing return types, untyped imports
@dataclass
/
TypedDict
for structured data
Named fields, type-checked, no raw
dict
guessing
Async PatternsAlways
await
coroutines
Unawaited coroutines are silent no-ops — no error, no execution
asyncio.gather()
for parallel work
Sequential
await
in a loop forfeits all concurrency benefits
Never block the event loopUse
run_in_executor
for CPU or blocking I/O
async with
for async context managers
Ensures
__aexit__
runs even on exceptions
asyncio.TaskGroup
(3.11+)
Structured concurrency; cancels siblings on first failure
Testingpytest fixtures over
unittest
classes
Composable, reusable, cleaner setup/teardown
@pytest.mark.parametrize
for cases
Table-driven tests — less boilerplate, clearer intent
Real implementations over mocksMocks drift from production; use them only for external I/O
tmp_path
fixture for file tests
Isolated temp directory per test; never hardcoded paths
Code Quality
f-strings
over
.format()
/
%
Readable inline, evaluated eagerly, not a template injection risk
typing.Final
for constants
Communicates intent; mypy rejects reassignment
__slots__
in hot classes
Reduces per-instance memory; prevents accidental attribute creation
dataclasses.dataclass
over manual
__init__
Auto-generates
__repr__
,
__eq__
, optional
__hash__
类别规则应用方式
安全性禁止使用可变默认参数使用
None
作为默认值;在函数体内初始化
始终使用上下文管理器对文件、数据库连接和锁使用
with
——不要手动调用
close()
禁止使用裸
except:
捕获特定异常;裸
except
会吞掉
KeyboardInterrupt
禁止对输入使用
eval()
/
exec()
可能导致代码注入;使用
ast.literal_eval
或结构化解析器
优先使用
pathlib.Path
,而非
os.path
跨平台、可组合、易读
类型安全为所有函数签名添加类型提示支持 mypy、IDE 自动补全和自文档化 API
对可空值使用
Optional[X]
/
X | None
调用方必须处理
None
;不要让可空性在类型系统中悄然漂移
避免使用
Any
使用
Union
、
TypeVar
或
Protocol
保留类型信息
在 CI 中运行
mypy --strict
严格模式可捕获隐式
Any
、缺失返回类型和未类型化导入
对结构化数据使用
@dataclass
/
TypedDict
命名字段、经过类型检查,无需猜测原始
dict
的结构
异步模式始终
await
协程
未
await
的协程会静默空操作——既不报错,也不会执行
使用
asyncio.gather()
执行并行任务
在循环中顺序
await
会丧失所有并发优势
绝不阻塞事件循环对 CPU 密集型任务或阻塞式 I/O 使用
run_in_executor
对异步上下文管理器使用
async with
确保即使发生异常也会执行
__aexit__
使用
asyncio.TaskGroup
(3.11+)
结构化并发;首个失败时取消同级任务
测试优先使用 pytest fixtures,而非
unittest
类
可组合、可复用,setup/teardown 更简洁
使用
@pytest.mark.parametrize
覆盖不同用例
表驱动测试——样板代码更少,意图更清晰
优先使用真实实现,而非 mockmock 会与生产实现逐渐偏离;仅对外部 I/O 使用 mock
文件测试使用
tmp_path
fixture
每个测试使用隔离的临时目录;绝不硬编码路径
代码质量优先使用
f-strings
,而非
.format()
/
%
内嵌可读、立即求值,且不存在模板注入风险
常量使用
typing.Final
明确表达意图;mypy 会拒绝重新赋值
热点类中使用
__slots__
减少每个实例的内存占用;防止意外创建属性
优先使用
dataclasses.dataclass
,而非手动编写
__init__
自动生成
__repr__
、
__eq__
和可选的
__hash__

Rule Priority Decision Flow

规则优先级决策流程

mermaid
flowchart TD
    Writing_code((Writing code))
    Safety_violation_{Safety violation?}
    Apply_Safety_rules[Apply Safety rules]
    Type_safety_violation_{Type safety violation?}
    Apply_Type_Safety_rules[Apply Type Safety rules]
    Async_issue_{Async correctness issue?}
    Apply_Async_rules[Apply Async rules]
    Apply_Code_Quality_rules[Apply Code Quality rules]
    Code_complete((Code complete))
    Writing_code --> Safety_violation_
    Safety_violation_ -->|"yes (NEVER compromise)"| Apply_Safety_rules
    Safety_violation_ -->|no| Type_safety_violation_
    Apply_Safety_rules --> Code_complete
    Type_safety_violation_ -->|"yes (fix before proceeding)"| Apply_Type_Safety_rules
    Type_safety_violation_ -->|no| Async_issue_
    Apply_Type_Safety_rules --> Code_complete
    Async_issue_ -->|"yes (silent no-op or race)"| Apply_Async_rules
    Async_issue_ -->|no| Apply_Code_Quality_rules
    Apply_Async_rules --> Code_complete
    Apply_Code_Quality_rules --> Code_complete
Priority order: Safety > Type Safety > Async Correctness > Code Quality
mermaid
flowchart TD
    Writing_code((Writing code))
    Safety_violation_{Safety violation?}
    Apply_Safety_rules[Apply Safety rules]
    Type_safety_violation_{Type safety violation?}
    Apply_Type_Safety_rules[Apply Type Safety rules]
    Async_issue_{Async correctness issue?}
    Apply_Async_rules[Apply Async rules]
    Apply_Code_Quality_rules[Apply Code Quality rules]
    Code_complete((Code complete))
    Writing_code --> Safety_violation_
    Safety_violation_ -->|"yes (NEVER compromise)"| Apply_Safety_rules
    Safety_violation_ -->|no| Type_safety_violation_
    Apply_Safety_rules --> Code_complete
    Type_safety_violation_ -->|"yes (fix before proceeding)"| Apply_Type_Safety_rules
    Type_safety_violation_ -->|no| Async_issue_
    Apply_Type_Safety_rules --> Code_complete
    Async_issue_ -->|"yes (silent no-op or race)"| Apply_Async_rules
    Async_issue_ -->|no| Apply_Code_Quality_rules
    Apply_Async_rules --> Code_complete
    Apply_Code_Quality_rules --> Code_complete
优先级顺序: 安全性 > 类型安全 > 异步正确性 > 代码质量

Safety

安全性

Python's dynamism makes safety issues silent — there's no compiler to catch them. These rules prevent the most common runtime surprises.
Never use mutable default arguments — they are shared across all calls:
python
undefined
Python 的动态特性会让安全问题悄无声息地出现——编译器无法捕获这些问题。以下规则用于防止最常见的运行时意外。
禁止使用可变默认参数——它们会在所有调用之间共享:
python
undefined

❌ BAD: The list is created once and shared; tags accumulate across calls

❌ BAD: The list is created once and shared; tags accumulate across calls

def add_tag(tag: str, tags: list[str] = []) -> list[str]: tags.append(tag) return tags
add_tag("a") # ["a"] add_tag("b") # ["a", "b"] — not ["b"]!
def add_tag(tag: str, tags: list[str] = []) -> list[str]: tags.append(tag) return tags
add_tag("a") # ["a"] add_tag("b") # ["a", "b"] — not ["b"]!

✅ GOOD: None sentinel; fresh list on every call

✅ GOOD: None sentinel; fresh list on every call

def add_tag(tag: str, tags: list[str] | None = None) -> list[str]: if tags is None: tags = [] tags.append(tag) return tags

The same applies to `dict`, `set`, and any other mutable type as a default argument.

**Always use context managers for resources:**

```python
def add_tag(tag: str, tags: list[str] | None = None) -> list[str]: if tags is None: tags = [] tags.append(tag) return tags

`dict`、`set` 以及其他任何作为默认参数的可变类型也同样适用这一规则。

**始终使用上下文管理器管理资源:**

```python

❌ BAD: File not closed if an exception occurs between open() and close()

❌ BAD: File not closed if an exception occurs between open() and close()

f = open("data.json") data = json.load(f) f.close()
f = open("data.json") data = json.load(f) f.close()

✅ GOOD: exit always runs, even on exception

✅ GOOD: exit always runs, even on exception

with open("data.json") as f: data = json.load(f)

Context managers apply equally to database connections, network sockets, threading locks, and any resource with an `__enter__`/`__exit__` pair.

**Never catch bare `except:` — catch specific exceptions:**

```python
with open("data.json") as f: data = json.load(f)

上下文管理器同样适用于数据库连接、网络套接字、线程锁,以及任何具有 `__enter__`/`__exit__` 配对方法的资源。

**禁止捕获裸 `except:`——应捕获特定异常:**

```python

❌ BAD: Catches KeyboardInterrupt, SystemExit, GeneratorExit — blocks Ctrl-C

❌ BAD: Catches KeyboardInterrupt, SystemExit, GeneratorExit — blocks Ctrl-C

try: result = risky_operation() except: logger.error("Something went wrong")
try: result = risky_operation() except: logger.error("Something went wrong")

✅ GOOD: Catch only what you can handle

✅ GOOD: Catch only what you can handle

try: result = risky_operation() except (ValueError, IOError) as exc: logger.error("Operation failed: %s", exc) raise

Minimum acceptable: `except Exception:`. But name the exceptions you expect.

**Never `eval()` or `exec()` on untrusted input:**

```python
try: result = risky_operation() except (ValueError, IOError) as exc: logger.error("Operation failed: %s", exc) raise

最低可接受的是 `except Exception:`。但仍应明确写出预期捕获的异常。

**禁止对不可信输入使用 `eval()` 或 `exec()`:**

```python

❌ BAD: Executes arbitrary code from the request

❌ BAD: Executes arbitrary code from the request

user_filter = request.args.get("filter") result = eval(user_filter) # Code injection
user_filter = request.args.get("filter") result = eval(user_filter) # Code injection

✅ GOOD: Parse structured input explicitly

✅ GOOD: Parse structured input explicitly

allowed_filters = {"active", "inactive", "pending"} user_filter = request.args.get("filter") if user_filter not in allowed_filters: raise ValueError(f"Invalid filter: {user_filter!r}")

For trusted config files with simple literals, use `ast.literal_eval` — it evaluates only Python literals, not arbitrary expressions.

**Use `pathlib.Path` instead of string concatenation for paths:**

```python
allowed_filters = {"active", "inactive", "pending"} user_filter = request.args.get("filter") if user_filter not in allowed_filters: raise ValueError(f"Invalid filter: {user_filter!r}")

对于仅包含简单字面量的可信配置文件,使用 `ast.literal_eval`——它只对 Python 字面量求值,而不会对任意表达式求值。

**路径处理应使用 `pathlib.Path`,而不是字符串拼接:**

```python

❌ BAD: String join breaks on Windows; hard to read

❌ BAD: String join breaks on Windows; hard to read

config_path = base_dir + "/config/" + env + ".yaml"
config_path = base_dir + "/config/" + env + ".yaml"

✅ GOOD: Composable, OS-aware, readable

✅ GOOD: Composable, OS-aware, readable

config_path = Path(base_dir) / "config" / f"{env}.yaml"
undefined
config_path = Path(base_dir) / "config" / f"{env}.yaml"
undefined

Type Safety

类型安全

Python's type system is optional, which is exactly why you must opt into it deliberately. Untyped code is correct until it isn't — and the failure surfaces at runtime in production.
Always add type hints to function signatures:
python
undefined
Python 的类型系统并非强制启用,因此你必须有意识地选择使用它。未类型化的代码在暴露问题前看似正确——而故障会在生产环境的运行时才显现。
始终为函数签名添加类型提示:
python
undefined

❌ BAD: Caller has no idea what types are expected or returned

❌ BAD: Caller has no idea what types are expected or returned

def process_user(user, flags): ...
def process_user(user, flags): ...

✅ GOOD: Contract is explicit; mypy can verify callers

✅ GOOD: Contract is explicit; mypy can verify callers

def process_user(user: User, flags: set[str]) -> ProcessResult: ...

**Use `Optional[X]` or `X | None` for nullable values (Python 3.10+: prefer `X | None`):**

```python
def process_user(user: User, flags: set[str]) -> ProcessResult: ...

**对可空值使用 `Optional[X]` 或 `X | None`(Python 3.10+:优先使用 `X | None`):**

```python

❌ BAD: Caller doesn't know None is possible; AttributeError at runtime

❌ BAD: Caller doesn't know None is possible; AttributeError at runtime

def find_user(user_id: str) -> User: return db.get(user_id) # Returns None if not found
def find_user(user_id: str) -> User: return db.get(user_id) # Returns None if not found

✅ GOOD: None is part of the contract; mypy enforces null checks on callers

✅ GOOD: None is part of the contract; mypy enforces null checks on callers

def find_user(user_id: str) -> User | None: return db.get(user_id)

**Avoid `Any` — preserve type information with `Union`, `TypeVar`, or `Protocol`:**

```python
def find_user(user_id: str) -> User | None: return db.get(user_id)

**避免使用 `Any`——使用 `Union`、`TypeVar` 或 `Protocol` 保留类型信息:**

```python

❌ BAD: Any propagates — typed code calling this function loses its types

❌ BAD: Any propagates — typed code calling this function loses its types

def deserialise(data: Any) -> Any: ...
def deserialise(data: Any) -> Any: ...

✅ GOOD: TypeVar preserves the relationship between input and output

✅ GOOD: TypeVar preserves the relationship between input and output

T = TypeVar("T") def deserialise(data: bytes, model: type[T]) -> T: ...

**Run `mypy --strict` in CI.** This enables `--disallow-untyped-defs`, `--warn-return-any`, `--no-implicit-optional`, and related checks. A codebase without strict mypy is typed in name only.

**Use `@dataclass` or `TypedDict` for structured data instead of plain dicts:**

```python
T = TypeVar("T") def deserialise(data: bytes, model: type[T]) -> T: ...

**在 CI 中运行 `mypy --strict`。** 这会启用 `--disallow-untyped-defs`、`--warn-return-any`、`--no-implicit-optional` 等检查。未使用 strict mypy 的代码库只是名义上具备类型安全。

**对结构化数据使用 `@dataclass` 或 `TypedDict`,而非普通字典:**

```python

❌ BAD: No type checking; typos in key names silently produce None

❌ BAD: No type checking; typos in key names silently produce None

user = {"user_id": "abc", "emal": "x@y.com"} # Typo — undetected send_confirmation(user["email"]) # KeyError at runtime
user = {"user_id": "abc", "emal": "x@y.com"} # Typo — undetected send_confirmation(user["email"]) # KeyError at runtime

✅ GOOD: Named fields, type-checked, IDE-autocompleted

✅ GOOD: Named fields, type-checked, IDE-autocompleted

@dataclass class User: user_id: str email: str
user = User(user_id="abc", email="x@y.com") send_confirmation(user.email) # Typo → AttributeError caught by mypy
undefined
@dataclass class User: user_id: str email: str
user = User(user_id="abc", email="x@y.com") send_confirmation(user.email) # Typo → AttributeError caught by mypy
undefined

Async Patterns

异步模式

Async bugs are among the hardest to reproduce — they often only surface under load or specific timing windows. Python's asyncio is strict: unawaited coroutines do nothing and emit only a
RuntimeWarning
that is easy to miss in logs.
Always
await
coroutines — unawaited coroutines are silent no-ops:
python
undefined
异步 Bug 是最难复现的问题之一——通常只有在负载较高或特定时间窗口下才会出现。Python 的 asyncio 规则十分严格:未
await
的协程不会执行任何操作,仅发出容易在日志中被忽略的
RuntimeWarning
。
始终
await
协程——未
await
的协程会静默空操作:
python
undefined

❌ BAD: save_order returns a coroutine object — it never runs

❌ BAD: save_order returns a coroutine object — it never runs

async def handle_request(order: Order) -> None: save_order(order) # No await — silently does nothing send_confirmation(order) # Also no await
async def handle_request(order: Order) -> None: save_order(order) # No await — silently does nothing send_confirmation(order) # Also no await

✅ GOOD: Explicit await — execution is guaranteed, errors propagate

✅ GOOD: Explicit await — execution is guaranteed, errors propagate

async def handle_request(order: Order) -> None: await save_order(order) await notify(order)

**Use `asyncio.gather()` for parallel work, not sequential awaits in a loop:**

```python
async def handle_request(order: Order) -> None: await save_order(order) await notify(order)

**使用 `asyncio.gather()` 执行并行任务,而非在循环中顺序 `await`:**

```python

❌ BAD: Each fetch waits for the previous to complete — O(N) latency

❌ BAD: Each fetch waits for the previous to complete — O(N) latency

async def load_all(ids: list[str]) -> list[Record]: results = [] for record_id in ids: record = await fetch_record(record_id) results.append(record) return results
async def load_all(ids: list[str]) -> list[Record]: results = [] for record_id in ids: record = await fetch_record(record_id) results.append(record) return results

✅ GOOD: All fetches in flight simultaneously — O(1) latency

✅ GOOD: All fetches in flight simultaneously — O(1) latency

async def load_all(ids: list[str]) -> list[Record]: return await asyncio.gather(*[fetch_record(i) for i in ids])

Use `asyncio.gather(*coros, return_exceptions=True)` when one failure should not abort the others.

**Never block the event loop — use `run_in_executor` for CPU or blocking I/O:**

```python
async def load_all(ids: list[str]) -> list[Record]: return await asyncio.gather(*[fetch_record(i) for i in ids])

当某个失败不应中止其他任务时,使用 `asyncio.gather(*coros, return_exceptions=True)`。

**绝不阻塞事件循环——对 CPU 密集型任务或阻塞式 I/O 使用 `run_in_executor`:**

```python

❌ BAD: time.sleep blocks the event loop; all other coroutines are frozen

❌ BAD: time.sleep blocks the event loop; all other coroutines are frozen

async def poll() -> None: time.sleep(1) # Blocks entire thread result = do_cpu_work() # Same problem
async def poll() -> None: time.sleep(1) # Blocks entire thread result = do_cpu_work() # Same problem

✅ GOOD: Async sleep yields; executor runs blocking code in a thread pool

✅ GOOD: Async sleep yields; executor runs blocking code in a thread pool

async def poll() -> None: await asyncio.sleep(1) loop = asyncio.get_running_loop() result = await loop.run_in_executor(None, do_cpu_work)

**Use `asyncio.TaskGroup` (Python 3.11+) over manual task management:**

```python
async def poll() -> None: await asyncio.sleep(1) loop = asyncio.get_running_loop() result = await loop.run_in_executor(None, do_cpu_work)

**使用 `asyncio.TaskGroup`(Python 3.11+),而非手动管理任务:**

```python

❌ BAD: Manual task tracking; exceptions may go unobserved

❌ BAD: Manual task tracking; exceptions may go unobserved

tasks = [asyncio.create_task(fetch(i)) for i in ids] results = await asyncio.gather(*tasks)
tasks = [asyncio.create_task(fetch(i)) for i in ids] results = await asyncio.gather(*tasks)

✅ GOOD: TaskGroup cancels all siblings on first exception; cleaner lifecycle

✅ GOOD: TaskGroup cancels all siblings on first exception; cleaner lifecycle

async with asyncio.TaskGroup() as tg: tasks = [tg.create_task(fetch(i)) for i in ids] results = [t.result() for t in tasks]
undefined
async with asyncio.TaskGroup() as tg: tasks = [tg.create_task(fetch(i)) for i in ids] results = [t.result() for t in tasks]
undefined

Testing

测试

pytest with fixtures over
unittest
classes:
python
undefined
优先使用带 fixtures 的 pytest,而非
unittest
类:
python
undefined

❌ BAD: setUp/tearDown are rigid; test methods share namespace

❌ BAD: setUp/tearDown are rigid; test methods share namespace

class TestUserService(unittest.TestCase): def setUp(self): self.service = UserService(FakeRepo())
class TestUserService(unittest.TestCase): def setUp(self): self.service = UserService(FakeRepo())

✅ GOOD: Fixtures are composable and reusable across modules

✅ GOOD: Fixtures are composable and reusable across modules

@pytest.fixture def user_service() -> UserService: return UserService(InMemoryUserRepo())
def test_creates_user(user_service: UserService) -> None: user = user_service.create(name="Alice", email="alice@example.com") assert user.name == "Alice"

**Use `@pytest.mark.parametrize` for table-driven tests:**

```python
@pytest.fixture def user_service() -> UserService: return UserService(InMemoryUserRepo())
def test_creates_user(user_service: UserService) -> None: user = user_service.create(name="Alice", email="alice@example.com") assert user.name == "Alice"

**使用 `@pytest.mark.parametrize` 编写表驱动测试:**

```python

❌ BAD: One test per case — repetitive, hard to extend

❌ BAD: One test per case — repetitive, hard to extend

def test_valid_email_foo(): assert is_valid_email("foo@example.com")
def test_valid_email_bar(): assert is_valid_email("bar@example.com")
def test_valid_email_foo(): assert is_valid_email("foo@example.com")
def test_valid_email_bar(): assert is_valid_email("bar@example.com")

✅ GOOD: All cases in one declaration; failure output shows the failing input

✅ GOOD: All cases in one declaration; failure output shows the failing input

@pytest.mark.parametrize("email,expected", [ ("foo@example.com", True), ("not-an-email", False), ("", False), ("a@b.c", True), ]) def test_email_validation(email: str, expected: bool) -> None: assert is_valid_email(email) == expected

**Prefer real implementations over mocks; mock only external I/O:**

```python
@pytest.mark.parametrize("email,expected", [ ("foo@example.com", True), ("not-an-email", False), ("", False), ("a@b.c", True), ]) def test_email_validation(email: str, expected: bool) -> None: assert is_valid_email(email) == expected

**优先使用真实实现,而非 mock;仅对外部 I/O 使用 mock:**

```python

❌ BAD: Mock diverges from the real repository contract over time

❌ BAD: Mock diverges from the real repository contract over time

mock_repo = MagicMock(spec=UserRepository) mock_repo.find_by_id.return_value = User(id="1", email="a@b.com")
mock_repo = MagicMock(spec=UserRepository) mock_repo.find_by_id.return_value = User(id="1", email="a@b.com")

✅ GOOD: In-memory implementation honours the real interface

✅ GOOD: In-memory implementation honours the real interface

class InMemoryUserRepo: def init(self) -> None: self._store: dict[str, User] = {}
def save(self, user: User) -> None:
    self._store[user.id] = user

def find_by_id(self, user_id: str) -> User | None:
    return self._store.get(user_id)

**Use the `tmp_path` fixture for file tests — never hardcoded paths:**

```python
class InMemoryUserRepo: def init(self) -> None: self._store: dict[str, User] = {}
def save(self, user: User) -> None:
    self._store[user.id] = user

def find_by_id(self, user_id: str) -> User | None:
    return self._store.get(user_id)

**文件测试使用 `tmp_path` fixture——绝不硬编码路径:**

```python

❌ BAD: Leaves state on disk; breaks in parallel test runs

❌ BAD: Leaves state on disk; breaks in parallel test runs

def test_writes_config(): write_config("/tmp/config.yaml", {"key": "value"}) assert Path("/tmp/config.yaml").exists()
def test_writes_config(): write_config("/tmp/config.yaml", {"key": "value"}) assert Path("/tmp/config.yaml").exists()

✅ GOOD: Isolated per-test temp directory; cleaned up automatically

✅ GOOD: Isolated per-test temp directory; cleaned up automatically

def test_writes_config(tmp_path: Path) -> None: config_file = tmp_path / "config.yaml" write_config(config_file, {"key": "value"}) assert config_file.exists()

**Type-check tests too — don't exempt test files from mypy.** Test code calls the same public API as production code. Exempt test files miss type errors on public API changes.
def test_writes_config(tmp_path: Path) -> None: config_file = tmp_path / "config.yaml" write_config(config_file, {"key": "value"}) assert config_file.exists()

**测试代码也要进行类型检查——不要将测试文件排除在 mypy 之外。** 测试代码与生产代码调用同一套公共 API。排除测试文件会遗漏公共 API 变更导致的类型错误。

⛔ Bug Fix Workflow — Mandatory

⛔ Bug 修复工作流——强制执行

When investigating a bug:
  1. Write a failing test first. Before touching the fix, write a test that reproduces the problem. Run it and confirm it fails for the right reason.
  2. Apply the fix. Only after seeing the test fail.
  3. Verify the test passes. Run the test again. It must go green.
  4. Verify no regressions. Run the full test suite.
  5. Report back to the user only after step 4 passes. Never claim a fix is complete until the tests confirm it.
A test written after the fix can pass for the wrong reasons. The failing test is the evidence that the fix addresses the actual bug, not a coincidental symptom.
调查 Bug 时:
  1. 先编写失败的测试。 在动手修复前,编写一个能够 复现问题的测试。运行它,并确认它因正确的原因而失败。
  2. 实施修复。 只有看到测试失败后再进行修复。
  3. 验证测试通过。 再次运行测试。测试必须变为绿色。
  4. 验证没有回归。 运行完整的测试套件。
  5. 只有在第 4 步通过后才向用户报告。 在测试确认之前, 绝不能声称修复已完成。
在修复之后编写的测试可能因错误原因而通过。失败的测试是证据,证明修复解决了实际问题,而不是碰巧出现的症状。

Code Quality

代码质量

Use
typing.Final
for constants — communicates intent, mypy rejects reassignment:
python
undefined
常量使用
typing.Final
——明确表达意图,mypy 会拒绝重新赋值:
python
undefined

❌ BAD: Any code can reassign MAX_RETRIES inadvertently

❌ BAD: Any code can reassign MAX_RETRIES inadvertently

MAX_RETRIES = 3
MAX_RETRIES = 3

✅ GOOD: Final signals to humans and tools that this value is invariant

✅ GOOD: Final signals to humans and tools that this value is invariant

from typing import Final MAX_RETRIES: Final = 3

**Use `__slots__` in performance-critical classes:**

```python
from typing import Final MAX_RETRIES: Final = 3

**在性能关键类中使用 `__slots__`:**

```python

❌ BAD: Each instance carries a full dict — O(N) memory overhead

❌ BAD: Each instance carries a full dict — O(N) memory overhead

class Point: def init(self, x: float, y: float) -> None: self.x = x self.y = y
class Point: def init(self, x: float, y: float) -> None: self.x = x self.y = y

✅ GOOD: Fixed attribute layout — less memory, faster attribute access

✅ GOOD: Fixed attribute layout — less memory, faster attribute access

class Point: slots = ("x", "y")
def __init__(self, x: float, y: float) -> None:
    self.x = x
    self.y = y

**Prefer `dataclasses.dataclass` over manual `__init__`:**

```python
class Point: slots = ("x", "y")
def __init__(self, x: float, y: float) -> None:
    self.x = x
    self.y = y

**优先使用 `dataclasses.dataclass`,而非手动编写 `__init__`:**

```python

❌ BAD: Manual init, repr, eq — repetitive boilerplate

❌ BAD: Manual init, repr, eq — repetitive boilerplate

class Config: def init(self, host: str, port: int, debug: bool = False): self.host = host self.port = port self.debug = debug
class Config: def init(self, host: str, port: int, debug: bool = False): self.host = host self.port = port self.debug = debug

✅ GOOD: Generated init, repr, eq; frozen=True makes it immutable

✅ GOOD: Generated init, repr, eq; frozen=True makes it immutable

@dataclass(frozen=True) class Config: host: str port: int debug: bool = False

**f-strings over `.format()` or `%`:**

```python
@dataclass(frozen=True) class Config: host: str port: int debug: bool = False

**优先使用 `f-strings`,而非 `.format()` 或 `%`:**

```python

❌ BAD: Format strings break on rename; % format is error-prone with tuples

❌ BAD: Format strings break on rename; % format is error-prone with tuples

msg = "User %s logged in from %s" % (user.name, ip_address) msg = "User {} logged in from {}".format(user.name, ip_address)
msg = "User %s logged in from %s" % (user.name, ip_address) msg = "User {} logged in from {}".format(user.name, ip_address)

✅ GOOD: Inline, readable, no positional index drift

✅ GOOD: Inline, readable, no positional index drift

msg = f"User {user.name} logged in from {ip_address}"
undefined
msg = f"User {user.name} logged in from {ip_address}"
undefined

Common Pitfalls — These Thoughts Mean STOP

常见误区——出现这些想法时立即停止

If you catch yourself thinking any of these, STOP and apply the correct approach:
RationalizationProblemImpactFix
"I tested it manually"Manual testing leaves no regression safety netNext refactor breaks it silentlyWrite a pytest test that covers the case
"A global variable is convenient"Untestable; mutated across test runs; thread-unsafeTests interfere; concurrent writes corrupt statePass dependencies explicitly or use a DI pattern
"The f-string expression is complex but readable"Complex expressions in f-strings are hard to testFormatting logic is invisible to unit testsExtract to a variable or function first
"Catch
Exception
broadly and log it"
Swallows unexpected bugs as mere log linesReal bugs hidden; system in unknown stateLog AND rethrow; let unexpected exceptions propagate
如果你发现自己在想以下任何一点,请立即停止并采用正确做法:
想法问题影响修复方式
“我手动测试过了”手动测试无法提供防止回归的安全网下一次重构可能会悄无声息地破坏它编写覆盖该场景的 pytest 测试
“全局变量很方便”难以测试;会在多次测试运行间被修改;线程不安全测试相互干扰;并发写入会破坏状态显式传递依赖,或使用 DI 模式
“f-string 中的表达式虽然复杂,但仍然容易理解”f-string 中复杂的表达式难以测试格式化逻辑对单元测试不可见先提取到变量或函数中
“广泛捕获
Exception
并记录日志即可”
将意外 Bug 仅作为日志行吞掉掩盖真正的 Bug;使系统处于未知状态记录并重新抛出;让意外异常继续向上传播