pythonvariablesunderscores

Does underscore (_) have any special functionality in Python, or is it just a convention?


freq, bin, _ = plt.hist(income, bins = 10, range = (0, 15), rwidth = 0.95)

I understand that _ is just a variable name like any other and that using _ for ignored values is merely a convention.

However, my question is: does python internally treat _ differently from other variables? Or is this usage purely a tradition with no intrinsic effect on memory management or execution?

For example, instead of using _, I could simply return the ignored value to a regular variable, and everything still OK.

freq, bin, _ = plt.hist(income, bins = 10, range = (0, 15), rwidth = 0.95)

I've searched for official documentation on this, but i haven't found anything that explicitly states whether has internal functionality beyond being a naming convention. An answer that cites any available documentation would be greatly appreciated.


Solution

  • No, Python itself (excluding REPL-centric special cases and match statements introduced in Python 3.10) does not treat _ differently from any other variable in script execution. There's no documentation other than pattern matching in switch case statements.

    However, there's still practical value to following the convention even without runtime enforcement (and even if we discard the practical benefits of making your code easier for other developers to understand), because static-checking tools (pyright, pyflakes, etc) do use that convention in determining when to warn the user about unused variables.