Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why implicitly check for emptiness in Python? [closed]

Tags:

python

idioms

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?

like image 925
GNUnit Avatar asked Jun 23 '11 19:06

GNUnit


3 Answers

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)

like image 152
Yuval Adam Avatar answered Sep 20 '22 11:09

Yuval Adam


Possibly trumped by the first and third items:

  • Beautiful is better than ugly.
  • Simple is better than complex.
like image 39
Mark Ransom Avatar answered Sep 22 '22 11:09

Mark Ransom


"Simple is better than complex."

"Readability counts."

Take for example if users -- it is more readable that if len(users) == 0

like image 30
Gabi Purcaru Avatar answered Sep 18 '22 11:09

Gabi Purcaru