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.

Monday 2 January 2017

Avoiding direct comparison with None or True, False

Comparing Bool type objects or None

Consider the following snippets:
snippet 1
if doc is None:
    doc = {"key": "value"}

snippet 2
if not doc:
    doc = {"key": "value"}


I have seen both types of code several times. Now the obvious question is which one is more "pythonic" and why.

Here the second approach is the "pythonic" way to do it. We know that the is keyword determines if the comparing objects are actually same objects or not. So if the doc is any other objects that are considered False in python then the code will not work as it was supposed to. But the second code will perform for any thing that is considered False in python.

Things that are considered False in python are:

  • False
  • None
  • 0 (Numeric)
  • [] (empty list)
  • {} (empty dictionary)
  • if  __len__() or __nonzero__() return False or 0
So unless it is necessary to compare directly with any of these objects, snippet 2 type of approach should be followed.