Python, what does an underscore before parenthesis do

The _ is the name of a callable (function, callable object). It’s usually used for the gettext function, for example in Django:

 from django.utils.translation import gettext as _
 print _("Hello!")  # Will print Hello! if the current language is English
                    # "Bonjour !" in French
                    # ¡Holà! in Spanish, etc.

As the doc says:

Python’s standard library gettext module installs _() into the global namespace, as an alias for gettext(). In Django, we have chosen not to follow this practice, for a couple of reasons:

[…]

The underscore character (_) is used to represent “the previous result” in Python’s interactive shell and doctest tests. Installing a global _() function causes interference. Explicitly importing gettext() as _() avoids this problem.

Even if it’s a convention, it may not be the case in your code. But be reassured, 99.9% of the time _ is an alias for gettext 🙂

Leave a Comment