On 21.08.2021 23:33, Tim Hoffmann via Python-ideas wrote:
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".
I assume your function would first check that the argument is a sequence and then check its length to determine emptiness. That doesn't strike me as more explicit. It's just shorter than first doing the type check and then testing the length. For the method case, it's completely up to the object to define what "empty" means, e.g. could be a car object which is fully fueled but doesn't have passengers. That's very flexible, but also requires all sequences to play along, which is hard. When you write "if not seq: ..." in a Python application, you already assume that seq is a sequence, so the type check is implicit (you can make it explicit by adding a type annotation and applying a type checked; either static or dynamic) and you can assume that seq is empty if the boolean test returns False. Now, you can easily add a helper function which implements your notion of "emptiness" to your applications. The question is: would it make sense to add this as a builtin. My take on this is: not really, since it just adds a type check and not much else. This is not enough to warrant the added complexity for people learning Python. You may want to propose adding a new operator.is_empty() function which does this, though. -- Marc-Andre Lemburg eGenix.com Professional Python Services directly from the Experts (#1, Aug 24 2021)
Python Projects, Coaching and Support ... https://www.egenix.com/ Python Product Development ... https://consulting.egenix.com/
::: We implement business ideas - efficiently in both time and costs ::: eGenix.com Software, Skills and Services GmbH Pastor-Loeh-Str.48 D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg Registered at Amtsgericht Duesseldorf: HRB 46611 https://www.egenix.com/company/contact/ https://www.malemburg.com/