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. 

3 comments :

  1. Hi Salman,
    You raise a good point, but IMHO it depends on the context.

    Sometimes you wish to keep comparing only with None, for instance during initialization of optional function arguments.

    ```
    def func(par=None):
    if par is None: par = []
    ```

    What do you think?

    ReplyDelete
    Replies
    1. Hi Gianluca,
      Yes if you want to distinguish between `False` and `None` or want to compare with any particular object that can be considered as False in python then you should do that. But in general the second approach is recommend.
      Thank you :)

      Delete
    2. Hello, Gianluca !

      In your specific case, the code
      if not par: par = []

      will only incur in a minor overhead if "par" is already the empty list.

      Delete