0

I'm working with a collection which can only be iterated once (stemming, I think, from how this collection proxies search results returned via a paged network API).

At present the behaviour is that if iteration is attempted a second time, the new iterator acts as if the collection is empty.

This feels a bit wrong to me; I'd be more comfortable if it raised an exception.

I can't find any chapter or verse indicating what the right convention is here. Is there one?

Ben Clifford
  • 1,398
  • 1
  • 12
  • 23
  • When trying to do `next()` on an empty iterator it raises `StopIteration`. Does that what you mean? when using a for-loop, this exception is consumed and the loop simply exits. I guess you are using for-loop. You can switch to a while-loop using `next` and then an exception will be raised – Tomerikoo Jul 30 '19 at 13:44

3 Answers3

0

First of all, you should look at PEP 255 (https://www.python.org/dev/peps/pep-0255/)

A collection that can only be iterated once is a generator. And a generator causes a StopIteration which literally is an exception once it does not have any items left. Most of the time (basically always) you dont care for the StopIteration exception because it gets handled by your iteration method.

Saritus
  • 918
  • 7
  • 15
0

It's not an API, but a programming functionality called a "generator." In Python, it's called yield

From What does the "yield" keyword do?

yield is a keyword that is used like return, except the function will return a generator.

>>> def createGenerator():
...    mylist = range(3)
...    for i in mylist:
...        yield i*i
...
>>> mygenerator = createGenerator() # create a generator
>>> print(mygenerator) # mygenerator is an object!
<generator object createGenerator at 0xb7555c34>
>>> for i in mygenerator:
...     print(i)
0
1
4

Here it's a useless example, but it's handy when you know your function will return a huge set of values that you will only need to read once. To master yield, you must understand that when you call the function, the code you have written in the function body does not run. The function only returns the generator object, this is a bit tricky :-)

Answer originally by e-satis

thlik
  • 401
  • 6
  • 12
0

you are working with generator function, that is why you are getting this type of result.

if you want to store the function/api output just do copy() operation.

For example

def func(l):
    for i in l:
        yield i

l=[i for i in range(1,100)]
p=func(l)

print(list(p))
print(list(p))


k=list(func(l)).copy() #solution to problem
print(k)
print(k)

above is sample case of problem

sahasrara62
  • 10,069
  • 3
  • 29
  • 44