跳到内容

f-string-in-get-text-func-call (INT001)

源自 flake8-gettext 代码检查器。

作用

检查 gettext 函数调用中的 f-strings。

为什么这不好?

gettext API 中,gettext 函数(通常别名为 _)通过在翻译目录中查找其输入参数,返回其翻译。

使用 f-string 作为参数调用 gettext 可能会导致意外行为。由于 f-string 在函数调用之前被解析,翻译目录将查找格式化的字符串,而不是 f-string 模板。

相反,格式化函数调用返回的值,而不是它的参数。

示例

from gettext import gettext as _

name = "Maria"
_(f"Hello, {name}!")  # Looks for "Hello, Maria!".

建议改为

from gettext import gettext as _

name = "Maria"
_("Hello, %s!") % name  # Looks for "Hello, %s!".

参考