The Zen of Python says that explicit is better than implicit.
Yet the Pythonic way of checking a collection c for emptiness is:
if not c:
# ...
and checking if a collection is not empty is done like:
if c:
# ...
ditto for anything that can have "zeroness" or "emptiness" (tuples, integers, strings, None, etc)
What is the purpose of this? Will my code be buggier if I don't do this? Or does it enable more use cases (i.e: some kind of polymorphism) since people can override these boolean coercions?
This best practice is not without reason.
When testing if object:
you are basically calling the objects __bool__
method, which can be overridden and implemented according to object behavior.
For example, the __bool__
method on collections (__nonzero__
in Python 2) will return a boolean value based on whether the collection is empty or not.
(Reference: http://docs.python.org/reference/datamodel.html)
Possibly trumped by the first and third items:
"Simple is better than complex."
"Readability counts."
Take for example if users
-- it is more readable that if len(users) == 0
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With