fix-types
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseYour task
你的任务
To fix types, do the following.
- First run the type checker to see what the issues are:
uv run mypy . - Group the errors you find in to logical buckets.
- For each bucket of errors, go through the errors one at a time, tell me the fix you want to apply, and then ask if I have any questions or suggestions before proceeding.
- Only once I approve, apply the fix and move onto the next error in the bucket.
- Once you've completed a bucket, ask me if I'd like to move on to the next bucket.
要修复类型问题,请执行以下步骤:
- 首先运行类型检查器查看问题:
uv run mypy . - 将发现的错误按逻辑分组。
- 对于每组错误,逐一处理,告诉我你想应用的修复方案,然后在执行前询问我是否有任何问题或建议。
- 只有在我批准后,再应用修复并处理该组中的下一个错误。
- 完成一组错误后,询问我是否要继续处理下一组。
Prefer cast()
over type: ignore
cast()type: ignore优先使用cast()
而非type: ignore
cast()type: ignoreWhen mypy can't infer the correct type, prefer using over :
cast()# type: ignorepython
undefined当mypy无法推断正确类型时,优先使用而非:
cast()# type: ignorepython
undefinedPreferred - documents the expected type
推荐 - 记录预期类型
choices = cast(list[tuple[str, str]], field.choices)
choices = cast(list[tuple[str, str]], field.choices)
Avoid when cast is possible - just silences the error
可能时避免使用 - 仅掩盖错误
choices = list(field.choices) # type: ignore[arg-type]
**Why:** `cast()` explicitly documents what type you expect, making the code more readable and maintainable. It also doesn't silence other potential errors on the same line.choices = list(field.choices) # type: ignore[arg-type]
**原因**:`cast()`会明确记录你期望的类型,让代码更具可读性和可维护性。它也不会掩盖同一行上的其他潜在错误。Prefer proper errors over assertions for null checks
空值检查优先使用恰当的错误而非断言
When adding null checks to satisfy mypy, prefer raising proper exceptions over using :
assertpython
undefined当添加空值检查以满足mypy要求时,优先抛出恰当的异常而非使用:
assertpython
undefinedPreferred - proper error handling
推荐 - 恰当的错误处理
if obj.related_field is None:
raise ValueError("Object must have a related field")
result = obj.related_field.some_method()
if obj.related_field is None:
raise ValueError("对象必须包含关联字段")
result = obj.related_field.some_method()
Avoid - assertions can be disabled with -O flag
避免使用 - 断言可通过-O标志禁用
assert obj.related_field is not None
result = obj.related_field.some_method()
**Why:** Assertions can be disabled in production with `python -O`, making them unreliable for runtime validation. Proper exceptions ensure the check always runs and provides better error handling.assert obj.related_field is not None
result = obj.related_field.some_method()
**原因**:断言可以通过`python -O`在生产环境中禁用,因此对于运行时验证来说并不可靠。恰当的异常能确保检查始终执行,并提供更好的错误处理。When using type: ignore
, add a comment
type: ignore当使用type: ignore
时,添加注释
type: ignoreIf is necessary (e.g., mypy limitation with valid code), always add a short explanation:
type: ignorepython
undefined如果必须使用(例如mypy对有效代码存在限制),务必添加简短说明:
type: ignorepython
undefinedGood - explains why the ignore is needed
规范 - 解释忽略原因
self.tier = tier # type: ignore[misc] # mypy can't handle Enum tuple values with custom init
self.tier = tier # type: ignore[misc] # mypy无法处理带有自定义__init__的Enum元组值
Bad - no explanation
不规范 - 无解释
self.tier = tier # type: ignore[misc]
undefinedself.tier = tier # type: ignore[misc]
undefinedType Hints for Django Lazy Translation Strings
Django延迟翻译字符串的类型提示
When using type hints with Django's lazy translation strings (), use the following pattern to avoid mypy errors while keeping the code working in production (where is not installed):
gettext_lazydjango-stubs-extpython
from __future__ import annotations # Must be the first import
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from django_stubs_ext import StrOrPromise在对Django的延迟翻译字符串()使用类型提示时,使用以下模式避免mypy错误,同时保持代码在生产环境(未安装)中正常运行:
gettext_lazydjango-stubs-extpython
from __future__ import annotations # 必须是第一个导入语句
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from django_stubs_ext import StrOrPromiseThen use StrOrPromise in type hints
然后在类型提示中使用StrOrPromise
def my_function(name: StrOrPromise) -> StrOrPromise:
...
class MyData:
title: StrOrPromise
description: StrOrPromise
**Why this pattern:**
- `from __future__ import annotations` makes type annotations strings at runtime (not evaluated)
- `if TYPE_CHECKING:` ensures the import only happens during type checking, not at runtime
- `django-stubs-ext` is a dev dependency and won't be available in production
- This pattern allows both regular strings and lazy translation strings to be accepteddef my_function(name: StrOrPromise) -> StrOrPromise:
...
class MyData:
title: StrOrPromise
description: StrOrPromise
**为什么使用此模式**:
- `from __future__ import annotations`使类型注解在运行时以字符串形式存在(不被求值)
- `if TYPE_CHECKING:`确保仅在类型检查时导入,而非运行时
- `django-stubs-ext`是开发依赖,在生产环境中不可用
- 此模式允许同时接受常规字符串和延迟翻译字符串