Hi all,

The Programming Recommendations section in PEP-8 states

"For sequences, (strings, lists, tuples), use the fact that empty sequences are 
false:"

  # Correct:
  if not seq:
  if seq:

  # Wrong:
  if len(seq):
  if not len(seq):

In the talk "When Python Practices Go Wrong" Brandon Rhodes makes a good point 
against this practice based on "explicit is better than implicit" 
(https://youtu.be/S0No2zSJmks?t=873). He advertizes using

  if len(seq):

While that is as explicit as one can get within the current language, it could 
still be more explicit: Semantically, we're not interested in the (zero) length 
of the sequence, but want to know if it is empty.


**Proposal**

Therefore, I propose syntax for an explicit empty check

  if isempty(seq):   (i)

or

  if seq.is_empty()  (ii)

This proposal is mainly motivated by the Zen verses "Explicit is better than 
implicit" and "Readability counts".

The two variants have slightly different advantages and disadvantages:

(i) would add an __isempty__ protocol and a corresponding isempty() builtin 
function.
One could argue that this is somewhat redundant with __len__. However, this is 
a typical pattern in collection.abc abstract base classes: There are only a few 
abstract methods and futher concepts are added as mixin methods (which are by 
default implemented using the abstract methods).
https://docs.python.org/3/library/collections.abc.html#collections-abstract-base-classes

(ii) would alternatively only implement a method on the collection. There's 
also precedence for predefined methods on collections, e.g. Sequence.index().

Advantages over the protocol approach are:
- It's a smaller language change than adding a protocol and a builtin function
- The order seq.is_empty() matches the order used in spoken english ("if the 
sequence is empty") which is more readable than isempty(seq).
- It's tab-completable (-> usability)
Disadvantages:
- Emptiness is similar to length, and people might be used to the 
builtin-method concept for such things.
- A protocol is more powerful than a method: One can support isempty() via 
len() even for objects that do not implement __isempty__. However, this more a 
theoretical advantage. I assume that in practice all collections derive from 
the collection.abc classes, so if the is_empty() method is implemented there, 
all typical use cases should be covered.


I'm looking forward to your feedback!
Tim
_______________________________________________
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at 
https://mail.python.org/archives/list/python-ideas@python.org/message/PBRSOAFHNT5YWKDPJKSS6SW4JA62CARC/
Code of Conduct: http://python.org/psf/codeofconduct/

Reply via email to