python-guidelines
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseAdd type hints wherever you can. Think more like static typing, avoid changing the type of the same variable.
Define complex (nested) types separately if they are used in more than one place in the code.
Omit type hints when the type is obvious from the context (e.g., ).
x = 1Write clean, human-readable code. Avoid spaghetti code; keep it structured.
Refactor the code as a separate step before making further changes whenever it would become too nested.
Too much nesting means more than 2 levels inside functions and methods.
Avoid adding too many parameters to functions and methods. In such cases introduce a data model class to store
that information, especially if they are used together more than once. The same applies to return values.
Prefer using data model classes to dictionaries, Pydantic is good, but can also use a dataclass if you have to.
For converting between naming schemes, always use explicit and methods instead of
hardcoding the external names of fields everywhere in the code. It typically happens while loading/saving data
from/to JSON with a different naming convention than the fields of the corresponding Pydantic model class.
from_somethingto_somethingDo not use catch-all exception handling (), except to cover retryable processing,
like request handlers or batch data processing. In all other cases use explicit exception handling
wherever required. Disable catch-all error handling in development, especially if a debugger is connected.
Never use exception handling for logic, except if there is no other alternative.
except ExceptionDo not combine multiple context managers into a single context manager just to save nesting on
statements at the top level of the application. It is better to write them out explicitly, even if the
nesting level increases.
withDo not use excessive nested iteration. While it needs less code, it also makes error handling and debugging
at a per-item level much harder when exceptions happen anywhere inside the generator functions.
Do not introduce abstractions prematurely. Do not add abstract base classes, unless there are multiple
subclasses or there will be multiple soon according to the current plans.
Do not write comments unless they are absolutely necessary to explain why the code is written the way it is.
Do not add a description of the method or function arguments if they are obvious from their names or types.
Prefer writing single-line docstrings that explain what the function or method does.
Define any duration in seconds (floating point), unless instructed otherwise.
Prefer test-driven development whenever it is practical.
Use only absolute imports, because relative imports will fail when you run a file directly, as Python loses
the context of the project's package structure.
Follow these guidelines from the Zen of Python:
- Explicit is better than implicit. Simple is better than complex. Complex is better than complicated.
- Flat is better than nested. Sparse is better than dense, readability counts.
- Special cases aren't special enough to break the rules, although practicality beats purity.
- Errors should never pass silently, unless explicitly silenced.
- If the implementation is hard to explain, it's a bad idea.
- In the face of ambiguity, refuse the temptation to guess.
尽可能添加类型提示(type hints)。多从静态类型的角度思考,避免修改同一变量的类型。
如果复杂(嵌套)类型在代码中多处使用,请单独定义。
如果类型从上下文可明显看出(例如:),可省略类型提示。
x = 1编写整洁、易读的代码。避免面条式代码(spaghetti code);保持代码结构化。
每当代码嵌套过深时,在进行进一步修改前先单独重构代码。
嵌套过深指函数和方法内部嵌套层级超过2层。
避免给函数和方法添加过多参数。这种情况下,引入数据模型类来存储相关信息,尤其是当这些参数需要多次一起使用时。返回值也适用此原则。
优先使用数据模型类而非字典,Pydantic是不错的选择,如果必要也可以使用dataclass。
在不同命名规范间转换时,始终使用显式的和方法,而非在代码各处硬编码字段的外部名称。这种情况通常出现在与JSON加载/保存数据时,JSON的命名规范与对应Pydantic模型类的字段命名规范不同的场景。
from_somethingto_something不要使用万能异常捕获(),除非是为了覆盖可重试的处理流程,比如请求处理或批量数据处理。在其他所有情况下,按需使用显式异常捕获。在开发环境中禁用万能异常捕获,尤其是在连接调试器时。
除非没有其他替代方案,否则不要使用异常处理来实现逻辑。
except Exception不要为了减少顶层语句的嵌套而将多个上下文管理器合并为一个。最好显式写出每个上下文管理器,即使嵌套层级会增加。
with不要使用过度嵌套的迭代。虽然这样代码量更少,但当生成器函数内部任意位置发生异常时,逐项进行错误处理和调试会变得困难得多。
不要过早引入抽象。除非有多个子类,或者根据当前计划很快会有多个子类,否则不要添加抽象基类。
除非绝对需要解释代码为什么要这么写,否则不要写注释。如果方法或函数的参数从名称或类型可明显看出含义,不要添加参数描述。优先使用单行文档字符串来说明函数或方法的功能。
除非另有指示,否则所有时长都以秒(浮点数)为单位定义。
只要可行,优先采用测试驱动开发(test-driven development)。
仅使用绝对导入,因为当你直接运行文件时,相对导入会失败,因为Python会丢失项目包结构的上下文。
遵循《Python之禅》中的以下准则:
- 显式优于隐式。简单优于复杂。复杂优于晦涩。
- 扁平优于嵌套。稀疏优于紧凑,可读性很重要。
- 特例不足以打破规则,但实用性优于纯粹性。
- 错误绝不能静默忽略,除非显式选择忽略。
- 如果实现难以解释,那它就是个坏主意。
- 面对歧义,拒绝猜测的诱惑。