Batman
Batman

Reputation: 8927

Can You Assign Variables to Underscore In Django

It's always struck me a weird that Django uses the underscore as an operator, given that the underscore is normally used to for assignment to variables that you don't want to reference later. E.g.

_, file_name = os.path.split(file_path)

Does this mean that you can't assign a unwanted variable to _ in the same namespace as you want to use the _("column_name") notation?

Upvotes: 0

Views: 229

Answers (2)

Subhajeet Dey
Subhajeet Dey

Reputation: 100

I think you are confusing a _ variable with Django's from django.utils.translation import gettext as _, the first _ as used by you is a throwaway variable which is commonly used as convention. Django also commonly imports gettext as _ to display translated text, for eg:

from django.http import HttpResponse
from django.utils.translation import gettext as _

def my_view(request):
    output = _("Welcome to my site.")
    return HttpResponse(output)

Also 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.

Upvotes: 0

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798744

_ is just another name, perfectly valid even though it looks strange. And just like any other name, rebinding it will make the old reference unavailable.

Upvotes: 3

Related Questions