Using the built-in assert
statement, is there a good, Pythonic way of checking emptiness in an iterable? I have seen:
- One-liner to check whether an iterator yields at least one element?;
- Is there any way to check with Python unittest assert if an iterable is not empty?; and
- Best way to check if a list is empty;
but I'm looking for a solution using assertions. The following looks to work, but I am unsure whether I'm missing some important possible exception:
a = [1, 2, 3]
b = []
assert a, 'a is empty'
assert b, 'b is empty'
Which raises this AssertionError
:
Traceback (most recent call last):
File "<ipython-input-9-185714f6eb3c>", line 5, in <module>
assert b, 'b is empty'
AssertionError: b is empty
Remember not to confuse a
container
(think lists, sets, tuples, dictionaries, whatever) with aniterable
(anything that can come up with a new state). The only way to check whether aniterable
is "empty" is to try to iterate over it and find out if it does not produce at least one new state. You are free to interpret that as theiterable
being "empty".Something like this
Also remember that an
iterable
is technically never truly "empty". It is allowed, though discouraged, for aniterable
to throw aStopIteration
sometimes and all of the sudden start producing new elements if tried again.Therefore there is no way to
assert
this. You have to try and see if you fail. If you do fail, the only true knowledge is that theiterable
did not produce a new state right now (for whatever reason). If you get an item back, theiterable
just produced a unique, precious snowflake that may never be reproducable again (think reading from network socket somewhere down the stack).