2.14 True/False Evaluations
Use the “implicit” false if at all possible.
This one is my personal bug-bear. I find this: if not users:
...
significantly worse than: if users == []:
...
The second is totally explicit, reminds the reader that users is (expected to be) a list and makes it totally clear that we can only enter the conditional block if users is an empty list.The first option: a) obfuscates the type of users on first reading b) evaluates to True if users is None (or LOADS of other things?!) which can lead to hard-to-find bugs. Granted, type-checking can help here but purely from a readability perspective the second option seems way more friendly and for almost no downside. The same holds true for all of the "False-y" objects: if users == {}:
if users == 0:
if users is None:
if users == ():
if users is False:
Why is the implicit: if not users:
an improvement in any of these cases? If you need to distinguish False from None then chain the expressions, such as if not x and x is not None:.
!!!Why not just: if x is False:
?
|
This goes for if you make a library as well, your library will be easier to use if you are less strict about the inputs you take, since that allows your user to work in a more naturally dynamic way. I love static types, but I have worked on making python libraries and there accepting a wide range of inputs is an important part of usability.