The reason why there is no is Empty
is astoundingly simple once you understand what the is
operator does.
From the python manual:
The operators is
and is not
test for object identity: x is y
is true
if and only if x
and y
are the same object. x is not y
yields the
inverse truth value.
That means some_sequence is Empty
checks whether some_sequence
is the same object as Empty
. That cannot work the way you suggested.
Consider the following example:
>>> a = []
>>> b = {}
Now let's pretend there is this is Empty
construct in python:
>>> a is Empty
True
>>> b is Empty
True
But since the is
operator does identity check that means that a
and b
are identical to Empty
. That in turn must mean that a
and b
are identical, but they are not:
>>> a is b
False
So to answer your question "why is there no is Empty
in python?": because is
does identity check.
In order to have the is Empty
construct you must either hack the is
operator to mean something else or create some magical Empty
object which somehow detects empty collections and then be identical to them.
Rather than asking why there is no is Empty
you should ask why there is no builtin function isempty()
which calls the special method __isempty__()
.
So instead of using implicit booleaness:
if saved:
mess_up()
we have explicit empty check:
if not isempty(saved):
mess_up()
where the class of saved
has an __isempty__()
method implemented to some sane logic.
I find that far better than using implicit booleaness for emptyness check.
Of course you can easily define your own isempty()
function:
def isempty(collection):
try:
return collection.__isempty__()
except AttributeError:
# fall back to implicit booleaness but check for common pitfalls
if collection is None:
raise TypeError('None cannot be empty')
if collection is False:
raise TypeError('False cannot be empty')
if collection == 0:
raise TypeError('0 cannot be empty')
return bool(collection)
and then define an __isempty__()
method which returns a boolean for all your collection classes.