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? 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 ()), [])
"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
"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 :-)
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
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
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.
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? This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics
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...
|
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...
|
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...
|
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()...
|
by: gelbeiche |
last post by:
Is
( cont.begin() == cont.end() )
essentially equivalent to writing
( cont.empty() )
for a STL container ?
|
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
|
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...
|
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...
|
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...
|
by: Charles Arthur |
last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
|
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
|
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...
|
by: nemocccc |
last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
|
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...
|
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,...
|
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,...
|
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...
|
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...
| |