How to avoid flake8 "F821 undefined name '_'" when _ gettext was installed?

Problem Overview:

In my main script project, gettext sets the _() function, which is used in other modules for translations (for example, print(_('Something to translate')) ).

As indicated by the document :

the _ () function is installed in the namespace of Pythons built-in functions, so it is easily accessible in all modules of your application.

So everything is working fine.

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 '_' 

This is normal since _ really not defined in main_script.py and lib.py.

A simple structure that reproduces the problem:

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

Where lib.py contains this:

 def fct(sentence): return _(sentence) 

and main_script.py is:

 #!/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:

 msgid "" msgstr "" "Project-Id-Version: myapp\n" msgid "A sentence" msgstr "Ein Satz" 

(poedit was compiled to create the mo file).

As stated above, the main script works:

 $ ./main_script.py Ein Satz Ein Satz 

Important Note. I am looking for a solution that works for both a script where gettext.install() is called, and all other modules that do not need to call gettext.install() . Otherwise, the structure may be even simpler, because calling _() from main_script.py is enough to run F821.

Solutions for solving a situation that looks bad (or worse):

  • add # noqa at the end of each line using _()
  • --ignore F821 (do not want to do this because it is useful in other situations)
+5
source share
1 answer

You can specify --builtins="_" , which is more specific than --ignore F821 .

You can also specify this in the configuration file if you do not like the command line arguments.

+13
source

All Articles