Why do we use underscore "_" in this python function using django?

Question:

_, filenames = default_storage.listdir("entries")
return list(sorted(re.sub(r".md$", "", filename)
        for filename in filenames if filename.endswith(".md")))

So here is a function that returns a list of names. I am trying to understand how this function works but I don’t understand what that underscore at the beginning is doing there. Thank you!

Asked By: skyIsBlue

||

Answers:

In the context of your example code, the underscore is simply used to denote a variable that is not used anywhere else in the code block.

For example instead of using an underscore you could use the variable var

var, filenames = default_storage.listdir("entries")
return list(sorted(re.sub(r".md$", "", filename)
        for filename in filenames if filename.endswith(".md")))

But then you have a variable named var that is never used anywhere else within the scope of the code block.

You could ignore the convention and your code would still function the same, the purpose is simply to help with readability and to avoid complaints from many of the commonly used linters.

Answered By: Alexander

This is a quote from the Django documentation:

listdir(path)[source] Lists the contents of the specified path,
returning a 2-tuple of lists; the first item being directories, the
second item being files.

It means that the underscore in your code is a list of directories in your entries folder, which you don’t need and so you just don’t use it

Answered By: karim