Friday, November 8, 2013

Be specific with your python conditionals

Here’s a mistake in Python that I saw getting done time and again:
some_val = some_dict.get(some_key, None)  # the None is optional in this case
if some_val: do_something(some_val)
What’s wrong?
Usually, the person who writes such code wants do_something to run whenever some_value is not None, yet if some_val is an empty list, empty dict or even the number 0 - do_something will not run! The right way to do it is:
if some_val is not None: do_something(some_val)
alternatively, one can check
if some_key in some_dict: …
Both options are more verbose and will get the job done.

3 comments:

  1. This comment has been removed by the author.

    ReplyDelete
  2. The confusion has probably roots in JavaScript where something like this:
    if(obj['x']){doSomething();}
    is a perfectly legit.

    ReplyDelete
  3. Right, even though in JavaScript the example you've given "doSomething" won't get called both when obj['x'] is undefined as well as when it is false. Come to thing about it, this proves that this issue exists in other languages as well.

    ReplyDelete