Many functions of a library I use return generators instead of lists when the result is some collection.
Sometimes I just want to check if the result is empty of not, and of course I can’t write something like:
result = return_generator()
if result:
print 'Yes, the generator did generate something!'
Now I come up with a one-liner that solve this problem without consuming the generator:
result = return_generator()
if zip("_", result):
print 'Yes, the generator did generate something!'
I wonder if there are cleaner ways to solve this problem in one line?
This
zipstuff eats the first item yielded, so it is not a good idea as well.You can only detect if a generator has an item yielding by getting and keeping it until needed. The following class will help you to do so.
If needed, it gets an item from the iterator and keeps it.
If asked for emptyness (
if myiterwatch: ...), it tries to get and returns if it could get one.If asked for the next item, it will return the retrieved one or a new one.
This solves the problem in a very generic way. If you have an iterator which you just want to test, you can use
next(a, b)returnsbif iteratorais exhausted. So if it returns the guard in our case, it didn’t generate something, otherwise it did.But your
zip()approach is perfectly valid as well…