Tuesday 17 January 2017

Using _ (underscore) as a placeholder or temporary variable name

The underscore character is often been used as a placeholder or throwaway variable in python. Like the following snippet:

for _ in range(10):
    print("Hello World")

Here, as we do not use the variable needed for iterating range,it's replaced with the `_` (underscore)  character.

In python there are three main usage of  `_` (underscore) character. (Taking reference from a well viewed Stack Overflow answer)
  • To hold the result of the last executed statement in an interactive interpreter session. In the following snippet we did not assign the return value of the split()method. But we can access the value using the `_` character.
In [1]: "Hello World".split()
Out[1]: ['Hello', 'World']

In [2]: _
Out[2]: ['Hello', 'World']
  • For translation lookup in i18n. Like the following often seen python web based projects.
forms.ValidationError(_("Please enter a correct username"))
  • As a general purpose "throwaway" variable name to indicate that part of a function result is being deliberately ignored. Here get_product will returns 3 value but we are only interested in the first two.
product_name, product_code, _ = get_product(product_id)


If we need a throwaway or placeholder variable, it's always a good practice to use the underscore character. Using a named variable in such case can create confusion. Using the `_` (underscore) characters in these circumstance will tell the reader that the data is unnecessary.

No comments :

Post a Comment