Title: explicit empty check instead of implicit booleaness
Type: enhancement Stage: resolved
Components: Interpreter Core Versions:
Status: closed Resolution: rejected
Dependencies: Superseder:
Assigned To: Nosy List: barry, lesmana, r.david.murray
Priority: normal Keywords:

Created on 2013-05-07 02:18 by lesmana, last changed 2013-05-08 15:46 by barry. This issue is now closed.

Messages (3)
msg188617 - (view) Author: lesmana (lesmana) Date: 2013-05-07 02:18
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:

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:

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):

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)
    >>> len(ml) == 0
msg188618 - (view) Author: R. David Murray (r.david.murray) * (Python committer) Date: 2013-05-07 02:23
Just use len.
msg188619 - (view) Author: R. David Murray (r.david.murray) * (Python committer) Date: 2013-05-07 02:26
Or, to be more helpful than that short answer: if you think there is something that isempty can do that len can't that makes it worth adding complexity to the language, please discuss it on the python-ideas mailing list first.  That's the best place to get feedback for ideas like this.
Date User Action Args
2013-05-08 15:46:25barrysetnosy: + barry
2013-05-07 02:26:34r.david.murraysetmessages: + msg188619
2013-05-07 02:23:32r.david.murraysetstatus: open -> closed

nosy: + r.david.murray
messages: + msg188618

resolution: rejected
stage: resolved
2013-05-07 02:18:17lesmanacreate