473,404 Members | 2,213 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,404 software developers and data experts.

Testing for empty iterators?

In the old days, if I wanted to return a sequence of items, I'd return a
list, and loop over it like this:

for thing in getListOfThings ():
do something

With iterators, I'm doing:

for thing in getThingIterator ():
do something.

Now I need to test to see if the iterator is empty. Actually, it's a
unit test where I want to assert that it is empty. In the old days, I
would have done:

assertEquals (getListOfThings (), [])

but I don't see any clean way to do this with an iterator. The best I
can come up with is something like:

flag = False
for thing in getThingIterator ():
flag = True
break
assertEquals (flag, False)

Is that really the only way to do it?
Jul 18 '05 #1
7 11308
I wrote:
flag = False
for thing in getThingIterator ():
flag = True
break
assertEquals (flag, False)

Is that really the only way to do it?


Oh, never mind, I got it...

assertEquals (list (getThingIterator ()), [])
Jul 18 '05 #2
"Roy Smith" <ro*@panix.com> wrote in message
news:ro***********************@reader2.panix.com.. .
I wrote:
flag = False
for thing in getThingIterator ():
flag = True
break
assertEquals (flag, False)

Is that really the only way to do it?


Oh, never mind, I got it...

assertEquals (list (getThingIterator ()), [])


In general, I'd say your first approach was better, or something like:

try:
getThingIterator.next()
assert False, "getThingIterator pointed to non-empty iterable"
except StopIteration:
pass # no need to assert, by getting here, we know that getThingIterator
pointed to an empty iterable

Or if you'd prefer a more typical-looking assert:

expectedNullItem = null
try:
expectedNullItem = getThingIterator.next()
except StopIteration:
pass
assert expectedNullItem==null, "getThingIterator was supposed to be empty"
Suppose your iterator, through some bug in your code, pointed to a list of
100,000 database records, instead of an empty list as you expected. Making
a list from this iterator could be very time-consuming, when all you really
needed to know was that the iterator pointed to at least one element.

-- Paul
Jul 18 '05 #3
"Paul McGuire" <pt***@austin.stopthespam_rr.com> wrote:
Suppose your iterator, through some bug in your code, pointed to a list of
100,000 database records, instead of an empty list as you expected. Making
a list from this iterator could be very time-consuming, when all you really
needed to know was that the iterator pointed to at least one element.


I see your point, but this is a unit test. Even more so than normally,
in a unit test I think clarity of code is more important that
efficiency. And in this case, it's only inefficient if it fails the
test, which should never happen :-)
Jul 18 '05 #4
Roy Smith <ro*@panix.com> wrote in message news:<ro***********************@reader2.panix.com> ...
In the old days, if I wanted to return a sequence of items, I'd return a
list, and loop over it like this:

for thing in getListOfThings ():
do something

With iterators, I'm doing:

for thing in getThingIterator ():
do something.

Now I need to test to see if the iterator is empty. Actually, it's a
unit test where I want to assert that it is empty. In the old days, I
would have done:

assertEquals (getListOfThings (), [])

but I don't see any clean way to do this with an iterator. The best I
can come up with is something like:

flag = False
for thing in getThingIterator ():
flag = True
break
assertEquals (flag, False)

Is that really the only way to do it?


You may want to check this thread:

http://groups.google.it/groups?q=emp...gle.com&rnum=1

Michele Simionato
Jul 18 '05 #5
Roy Smith wrote:
Now I need to test to see if the iterator is empty. Actually, it's a
unit test where I want to assert that it is empty. In the old days, I
would have done:

assertEquals (getListOfThings (), [])

but I don't see any clean way to do this with an iterator. The best I
[and in a follow-up]
Oh, never mind, I got it...

assertEquals (list (getThingIterator ()), [])


An alternative would be

self.assertRaises(StopIteration, getThingIterator().next)

which is a bit stricter as it will choke if getThingIterator() returns a
list instead of an iterator.

Peter

Jul 18 '05 #6
Peter Otten <__*******@web.de> writes:
An alternative would be

self.assertRaises(StopIteration, getThingIterator().next)


Note that all those methods "consume" at least one element of the
iterator. You need something like ungetc for iterators (untested code):

class wrapper:
def __init__(self, iterator):
self.iterator = iterator
self.pushback = []
def __next__(self):
if self.pushback:
return self.pushback.pop(0)
def is_empty(self):
if self.pushback:
return False
try:
self.pushback.append(self.iterator.next())
return False
except StopIteration:
return True

Maybe something like that should go into itertools, if it's not
already there. Or the is_empty operation could be built into iterators.
Jul 18 '05 #7
Normally I add a __len__ method to my class
that contains an iterator if I need to keep
track of length/empty status. Basically it
is something like:

class getListOfThing:
def __init__(self):
self.ListOfThings=[]
self.next_index=0
#
# Code to build ListOfThings can be inserted here
# or in some other method.
#
return

def __iter__(self):
return self

def next(self):
#
# Try to get the next Thing
#
try: Thing=self.ListOfThings[self.next_index]
except IndexError:
self.next_index=0
raise StopIteration
#
# Increment the index pointer for the next call
#
self.next_index+=1
return Thing

def __len__(self):
return len(self.ListOfThings)
#
# Where ListOfThings is an attribute
# (list) that is defined in __init__
# and appended to in some way.
#

if __name__=="__main__":

T=getListOfThings()
print "Length of ListOfThings=",len(T)
for Thing in T:
# do something with Thing

But most of the time the fact that the iterator
doesn't return enything, so the loop is skipped
automatically is sufficient. I think you can do
this same thing with a yield, but this method works
and I continue to use it a lot.

HTH,
Larry Bates
Syscon, Inc.

"Roy Smith" <ro*@panix.com> wrote in message
news:ro***********************@reader2.panix.com.. .
In the old days, if I wanted to return a sequence of items, I'd return a
list, and loop over it like this:

for thing in getListOfThings ():
do something

With iterators, I'm doing:

for thing in getThingIterator ():
do something.

Now I need to test to see if the iterator is empty. Actually, it's a
unit test where I want to assert that it is empty. In the old days, I
would have done:

assertEquals (getListOfThings (), [])

but I don't see any clean way to do this with an iterator. The best I
can come up with is something like:

flag = False
for thing in getThingIterator ():
flag = True
break
assertEquals (flag, False)

Is that really the only way to do it?

Jul 18 '05 #8

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
by: steven | last post by:
Hi, Anyone was using pmock for unit testing with python? I met a problem and hope someone to help me. For short, the pmock seems can not mock a iterator object. For example, the tested...
10
by: Brian Roberts | last post by:
I'm using using generators and iterators more and more intead of passing lists around, and prefer them. However, I'm not clear on the best way to detect an empty generator (one that will return no...
3
by: Mark Turney | last post by:
Problem: I have a vector full of two different derived class objects (class B and class C) that are derived from the same base class A. I want to loop through vector and invoke a member function...
25
by: Matthias | last post by:
Hi, I am just reading that book by Scott Meyers. In Item 4 Meyers suggests to always use empty() instead of size() when probing for emptyness of STL containers. His reasoning is that size()...
5
by: gelbeiche | last post by:
Is ( cont.begin() == cont.end() ) essentially equivalent to writing ( cont.empty() ) for a STL container ?
2
by: ma740988 | last post by:
typedef std::vector < std::complex < double > > complex_vec_type; // option1 int main() { complex_vec_type cc ( 24000 ); complex_vec_type dd ( &cc, &cc ); } versus
0
ADezii
by: ADezii | last post by:
When you create a Recordset, you may want to know immediately whether that Recordset actually contains any Rows. There are Recordsets that don't return any Rows and you may need to take different...
24
by: David | last post by:
Hi list. What strategies do you use to ensure correctness of new code? Specifically, if you've just written 100 new lines of Python code, then: 1) How do you test the new code? 2) How do...
7
by: Moschops | last post by:
In moving some code from VS6 to VS2008 (bear with me, this is not a VS question, I'm just setting context), we find new crashes that weren't there before and we think they're related to trying an...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.