[New-bugs-announce] [issue17921] explicit empty check instead of implicit booleaness
lesmana
report at bugs.python.org
Tue May 7 04:18:17 CEST 2013
New submission from lesmana:
Python should have a builtin method `isempty()` which calls the special method name `__isempty__()` for explicit emptiness check.
The special method `__isempty__()` should return `True` if the object is "empty" and `False` if the object is "not empty".
Observe emptiness check using implicit booleaness:
if not somecollection:
foo()
Note that this code also handles `None`, `0` and `False` silently. If those are possible values then I have to test explicitly:
if somecollection is not None and not somecollection:
foo()
Also handling the `0` and `False` cases will make the code really really ugly.
Usually the `None`, `0` or `False` cases only happen in case of a programming error. But if I do not test for them explicitly then they will be handled silently and the error will occur somewhere else in the code.
Compare against explicit emptiness check:
if not isempty(somecollection):
foo()
This code will break immediately if somecollection does not have `__isempty__()`. If `None`, `0` or `False` are possible values they will not be handled silently, instead an error will be reported at `isempty()`.
Advantage of explicit emptiness check:
* More explicit and fluently readable code
* No silent implicit booleaness check when code should do emptiness check
* Clearer separation of meaning for the special methods `__len__()` and `__empty__()`
Possible use case for explicit emptiness check: a list with memory effect.
>>> ml = MemoryEffectList()
>>> ml.charge()
>>> ml.discharge()
>>> isempty(ml)
True
>>> len(ml) == 0
False
----------
components: Interpreter Core
messages: 188617
nosy: lesmana
priority: normal
severity: normal
status: open
title: explicit empty check instead of implicit booleaness
type: enhancement
_______________________________________
Python tracker <report at bugs.python.org>
<http://bugs.python.org/issue17921>
_______________________________________
More information about the New-bugs-announce
mailing list