Problem overview:
In my project's main script, gettext
installs the function _()
that is used in other modules for translations (like in print(_('Something to translate'))
).
在我的项目的主脚本中,gettext安装了在其他模块中用于翻译的函数_()(例如print(_('Something to translate')))。
As stated by the doc:
正如文件所述:
the _() function [is] installed in Python’s builtins namespace, so it is easily accessible in all modules of your application.
_()函数[是]安装在Python的内置命名空间中,因此可以在应用程序的所有模块中轻松访问它。
So, everything runs fine.
所以,一切都运行良好。
Only problem: flake8
shows errors (actually returned by PyFlakes):
唯一的问题:flake8显示错误(实际上由PyFlakes返回):
$ flake8 *.py
lib.py:2:12: F821 undefined name '_'
main_script.py:8:7: F821 undefined name '_'
This is normal, as _
is indeed not defined in main_script.py nor lib.py.
这是正常的,因为_确实没有在main_script.py和lib.py中定义。
Simple structure that reproduces the problem:
.
├── lib.py
├── locale
│ └── de
│ └── LC_MESSAGES
│ ├── myapp.mo
│ └── myapp.po
└── main_script.py
Where lib.py contains this:
lib.py包含这个:
def fct(sentence):
return _(sentence)
and main_script.py this:
和main_script.py这个:
#!/usr/bin/env python3
import gettext
import lib
gettext.translation('myapp', 'locale', ['de']).install()
print(_('A sentence'))
print(lib.fct('A sentence'))
and myapp.po contains:
和myapp.po包含:
msgid ""
msgstr ""
"Project-Id-Version: myapp\n"
msgid "A sentence"
msgstr "Ein Satz"
(was compiled by poedit to produce the mo file).
(由poedit编译以生成mo文件)。
As stated above, the main script does work:
如上所述,主脚本确实有效:
$ ./main_script.py
Ein Satz
Ein Satz
Important note: I'm looking for a solution working both for the script where gettext.install()
is called and all other modules that do not need to call gettext.install()
. Otherwise, the structure could be even more simple, because calling _()
from main_script.py is enough to trigger F821.
重要说明:我正在寻找一个解决方案,它既适用于调用gettext.install()的脚本,也适用于不需要调用gettext.install()的所有其他模块。否则,结构可能更简单,因为从main_script.py调用_()足以触发F821。
Solutions to solve the situation that look bad (or worse):
- add a
# noqa
comment at the end of each line using_()
-
--ignore
F821 (don't want to do that because this is useful in other situations)
使用_()在每行末尾添加#noqa注释
--ignore F821(不想这样做,因为这在其他情况下很有用)
1 个解决方案
#1
16
You could specify the --builtins="_"
which is more specific than --ignore F821
.
您可以指定--builtins =“_”,它比--ignore F821更具体。
You should be able to specify this in a configuration file as well if you don't like command line arguments.
如果您不喜欢命令行参数,也应该能够在配置文件中指定它。
#1
16
You could specify the --builtins="_"
which is more specific than --ignore F821
.
您可以指定--builtins =“_”,它比--ignore F821更具体。
You should be able to specify this in a configuration file as well if you don't like command line arguments.
如果您不喜欢命令行参数,也应该能够在配置文件中指定它。