如何避免使用flake8的"F821未定义名称'_'" gettext已安装_的时间? [英] How to avoid flake8's "F821 undefined name '_'" when _ has been installed by gettext?

查看:355
本文介绍了如何避免使用flake8的"F821未定义名称'_'" gettext已安装_的时间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在项目的主脚本中,gettext安装用于其他模块的翻译功能(如print(_('Something to translate'))中的)_().

In my project's main script, gettext installs the function _() that is used in other modules for translations (like in print(_('Something to translate'))).

文档所述:

_()函数安装在Python的内建名称空间中,因此可以在应用程序的所有模块中轻松访问.

the _() function [is] installed in Python’s builtins namespace, so it is easily accessible in all modules of your application.

所以,一切正常.

唯一的问题:flake8显示错误(由PyFlakes实际返回):

Only problem: flake8 shows errors (actually returned by PyFlakes):

$ flake8 *.py
lib.py:2:12: F821 undefined name '_'
main_script.py:8:7: F821 undefined name '_'

这是正常现象,因为_确实未在main_script.py或lib.py中定义.

This is normal, as _ is indeed not defined in main_script.py nor lib.py.

.
├── lib.py
├── locale
│   └── de
│       └── LC_MESSAGES
│           ├── myapp.mo
│           └── myapp.po
└── main_script.py

lib.py包含以下内容:

Where lib.py contains this:

def fct(sentence):
    return _(sentence)

和main_script.py此:

and main_script.py this:

#!/usr/bin/env python3

import gettext

import lib

gettext.translation('myapp', 'locale', ['de']).install()
print(_('A sentence'))
print(lib.fct('A sentence'))

和myapp.po包含:

and myapp.po contains:

msgid ""
msgstr ""
"Project-Id-Version: myapp\n"

msgid "A sentence"
msgstr "Ein Satz"

(由poedit编译以生成mo文件).

(was compiled by poedit to produce the mo file).

如上所述,主要脚本确实有效:

As stated above, the main script does work:

$ ./main_script.py 
Ein Satz
Ein Satz

重要说明:我正在寻找一种解决方案,该解决方案既可以将gettext.install()称为的脚本,又可以将不需要调用的所有其他模块 > gettext.install().否则,结构可能会更简单,因为从main_script.py调用_()足以触发F821.

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.

  • 使用_()
  • 在每行末尾添加# noqa注释
  • --ignore F821(不想这样做,因为这在其他情况下很有用)
  • 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)

推荐答案

您可以指定--builtins="_",它比--ignore F821更具体.

You could specify the --builtins="_" which is more specific than --ignore F821.

如果您不喜欢命令行参数,那么您也应该能够在配置文件中指定它.

You should be able to specify this in a configuration file as well if you don't like command line arguments.

这篇关于如何避免使用flake8的"F821未定义名称'_'" gettext已安装_的时间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆