by shadowmint · 12y ago · 0 comments
It's very common for libraries to make values evaluate to False, and very easy to get bugs if you just lazily test with 'if x'.
Sqlalchemy springs to mind immediately as one of the common ones where using any() and if x: is a reeeeeallly bad idea; there are plenty of others.
I'm pretty skpetical about modifying your coding behavior based on what libraries you happen to be currently using.
'If x' isn't your friend.
(bool(datetime.time(0)), bool(datetime.time(1))) == (False, True)
I always consider `if x:` a bug, unless x can only be a boolean. Furthermore, it seriously hinders readability and clarity of the code.I got bit by this once, and it's certainly... strange (it's also surprising). It's considered "behavior consistent with the rest of Python" [1] (which I can agree with) even if it makes little sense in terms of immediate readability to someone who hasn't previously encountered it. Fortunately, the workaround is easy, and it is documented.
There's at least a couple of spats on the mailing list regarding this feature that are of interest to the curious or at least those who are interested in the history of such behavior.
Oh, like this? ;)
var eventA = new Date(), eventB = new Date();
if (!parseInt((eventA - eventB) / 1000)) {
console.log("these events occurred simultaneously");
} else {
// troll harder with confusing use of 'asynchronous'
console.log("these events occurred asynchronously");
} "Explicit is better than implicit."
If you mean is not None, you should say is not None.It's fast and readable and there are no "just be aware that" disclaimers to tack on afterwards.
If you're checking to see if that value is None, then yes - you should check that.
If you're merely checking if the value is truthy, then using "if x:" is completely legitimate.