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: …
This comment has been removed by the author.
ReplyDeleteThe confusion has probably roots in JavaScript where something like this:
ReplyDeleteif(obj['x']){doSomething();}
is a perfectly legit.
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