No, those are not necessarily equivalent unless the type of name is known.
If name is a number, it will be falsey iff it is zero (None is not a number but a singleton instance of NoneType, which is always falsey). If name is a string, it is falsey iff it is empty. "0" is truthy because it is nonempty. "0" and 0 are very different things, and Python generally won't coerce between them unless you explicitly call int() or str(). Moving on, if name is a container type of some kind, generally speaking it is falsey iff it is empty (has a len() of zero). The empty string being falsey is a special case of this rule.
For user-defined types, you're on your own. By default they're all truthy, but you can't rely on that since someone might subclass you and implement non-default boolean semantics.
If you want to check whether something is None, the only bulletproof syntax for doing so is if foo is None or if foo is not None. if foo should only be used if foo has a non-default boolean behavior (i.e. foo is a container, number, string, or user-defined class which overrides bool()). Using if foo with classes which do not provide useful boolean behavior (such as datetime objects) is at best poor style and at worst a violation of substitutability since it would interfere with subclassing.
For user-defined types, you're on your own. By default they're all truthy, but you can't rely on that since someone might subclass you and implement non-default boolean semantics.
Using if foo with classes which do not provide useful boolean behavior (such as datetime objects) is at best poor style and at worst a violation of substitutability since it would interfere with subclassing.
When I write Python, my attitude to this is "their fault, then". If someone subclasses my stuff and adds a nonsensical __nonzero__/__bool__, their code would not work and it would be their own fault.
Of course when I want to test if something is None in particular (because, for instance, I said so in my function specification), I don't take the shortcut. But when I want to test "truthiness" I do just that too, and expect the caller to give me an object that implements that properly, if it does implement it.
The problem with datetime is that it accidentally provides a wrong boolean behaviour (and it's our problem because it's in the standard library).
When I write Python, my attitude to this is "their fault, then". If someone subclasses my stuff and adds a nonsensical __nonzero__/__bool__, their code would not work and it would be their own fault.
This is ridiculous. You can't possibly know that no subclass will ever need boolean behavior.
What if they add a perfectly sensible __bool__ that nonetheless is incorrect in the context you wrote if foo? For instance, one that makes the class truthy or falsey based solely on data which was not part of the original class.
17
u/MisterSnuggles Mar 26 '14
While not JavaScript, we must not forget about Python's False Midnight.
tl;dr:
Prints "f".
Prints "t".