4 ms·
Not in python. if var: ... is better in some situations, but is objectively worse in many others. If you really do want anything that's "falsey" t
by jofer 13y ago
Not in python.
if var:
...
is better in some situations, but is objectively worse in many others. If you really do want anything that's "falsey" to fall into that conditional, then by all means, use it! Just be aware that `0`, `[]`, `None`, `0.0`, etc will all be treated the same.
However, it's harmful in one of its most common use cases: default values.
For example, let's say you're working with a function that takes an optional argument similar to:
def foo(x, values=None):
if values is None:
values = []
You shouldn't use a mutable default argument for several reasons, so instead you make the default "None" and set it to an empty sequence. The snippet above is the standard idiom.
Let's say a user mistakenly passes "values=0" instead of "values=[0]".
If you had done:
if not values:
values = []
Then the code will happily proceed with "values" being an empty list and _silently give incorrect output_ instead of raising an error a couple of lines later.
You can make the (very reasonable) argument that this is all the fault of dynamic typing, and if python was just a staticly typed language, the compiler would catch all of this, but that's beside the point.
Be aware of what you're testing if you choose "if var:" instead of "if var is not None:"
- tehwalrus 13y agodefault values is a special case (and one which I consider to be a bug in python, frankly, since it bites everyone who didn't read up on default arguments before the wrote some code - everyone uses [] as a default argument at some point and then spends an amount of time proportional to the complexity of their program debugging the insane behaviour before noticing. My program was quite long and complex, and I am still bitter.) I didn't argue, and certainly didn't mean to imply, that it is always better, but in the sort of case we're considering in this example, i.e. we expect a valid time value or None, It really is madness to imply a time value of midnight is "empty".
- couchand 13y agoNice job explaining away one language bug with another.