How to find missing _/gettext import statements

For a project, I'm internationalizing a django project. This means adding lots of _ or gettext function calls around all my strings.

Sometimes I forget to add the the import statement at the top and then you get loads of errors like this: NameError: name '_' is not defined

pylint is a great tool to statically analyze python source code (ubuntu install link), and is a great way to find errors like this in python code. However if you run pylint on all your code, you'll get this errors on every usage of _, even if you have imported gettext:

E: 9:ObjectName: _ is not callable

This _ is not callable message is E1102, the pylint documentation tells us that is used when Used when an object being called has been inferred to a non callable object. pylint is thinking that _ is not a function.

If we disable this message, then it will give us an error for _() if it's not defined, which is what we want

I use this bash command line to find the places where I forgot to do add a from django.utils.translation import ugettext as _ find -type f -name '*.py' -exec pylint --output=parseable -E --disable=E1102 '{}' ';' | grep "'_'"

This entry is tagged: