473,666 Members | 2,368 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 getThingIterato r ():
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 (getListOfThing s (), [])

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 getThingIterato r ():
flag = True
break
assertEquals (flag, False)

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

Is that really the only way to do it?


Oh, never mind, I got it...

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

Is that really the only way to do it?


Oh, never mind, I got it...

assertEquals (list (getThingIterat or ()), [])


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

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

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

expectedNullIte m = null
try:
expectedNullIte m = getThingIterato r.next()
except StopIteration:
pass
assert expectedNullIte m==null, "getThingIterat or 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.s topthespam_rr.c om> 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.co m> 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 getThingIterato r ():
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 (getListOfThing s (), [])

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 getThingIterato r ():
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 (getListOfThing s (), [])

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 (getThingIterat or ()), [])


An alternative would be

self.assertRais es(StopIteratio n, getThingIterato r().next)

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

Peter

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

self.assertRais es(StopIteratio n, getThingIterato r().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.p op(0)
def is_empty(self):
if self.pushback:
return False
try:
self.pushback.a ppend(self.iter ator.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.ListOfThin gs=[]
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.List OfThings[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.ListOf Things)
#
# Where ListOfThings is an attribute
# (list) that is defined in __init__
# and appended to in some way.
#

if __name__=="__ma in__":

T=getListOfThin gs()
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.co m> 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 getThingIterato r ():
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 (getListOfThing s (), [])

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 getThingIterato r ():
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
2632
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 object is foo, who need to send message to another object bar. So, to test the foo, I need mock a mockBar. But the bar is a iterator, the foo use the bar in this way:
10
7843
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 items) when some sort of special case handling is required. Typical code for handling an empty list: if somelist: for x in somelist: something(x) else:
3
1981
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 in only objects of class B and skip over the objects of class C. To complicate things, I'm using the vector position (index) as an argument in the invoked member function. It is possible to move the position into the object by adding a data...
25
7567
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() might take linear time on some list implementations. That makes sense at first. However, he also says this at the very beginning: "That being the case , you might wonder why one construct should be preferred to the other, especially in view of the...
5
2174
by: gelbeiche | last post by:
Is ( cont.begin() == cont.end() ) essentially equivalent to writing ( cont.empty() ) for a STL container ?
2
2339
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
24935
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 steps based on this outcome. There are basically 3 Methods for testing for an Empty Recordset (Recordset that returns no Rows). We will be using DAO, but these Methods are equally applicable to ADO. 'Common Code Block Dim MyDB As DAO.Database, MyRS As...
24
2515
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 you ensure that the code will work correctly in the future? Short version:
7
2316
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 operation on a multimap that is empty - for example, std::multimap<double, aStructWeHaveDefined>::iterator low; low = c.begin() ; // c is empty (i.e. c.empty()==1) but we haven't checked for it In VS6 these crashed did not occur, in VS2008...
0
8440
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8355
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8866
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8781
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8550
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8638
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
4193
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4365
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2769
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

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.