pony icon indicating copy to clipboard operation
pony copied to clipboard

Can't call `next()` when iterating through Query; can't iterate through QueryResultIterator

Open jcbgamboa opened this issue 5 years ago • 1 comments

(I'm new to PonyORM. I understand I may be asking some nonsense)

I have a table Word, from which I'm selecting:

result = select(w for w in Word)

Then I can iterate through the table with a for loop:

for i in result:
    print(i)

This works. But if I try calling next() on result,

for i in result:
    print(i)
    # skip every second element
    a = next(result)

I get an error:

TypeError: 'Query' object is not an iterator

I thought I'd try calling iter() on result, to create an iterator. Then I can call next(result):

result = iter(result)
a = next(result)
for i in result:  # <-- will crash here
    print(i)

But then I get another error:

TypeError: 'QueryResultIterator' object is not iterable

In other words, this is an iterator that I can't iterate through (?). I am very confused about this problem.

I'm using Python3.6.8, and PonyORM 0.7.13. (let me know if you need more details)

jcbgamboa avatar Jul 24 '20 10:07 jcbgamboa

The first way you tried is not possible for native Python objects either, e.g. try:

result = list(range(10))
for i in result:
    print(i)
    a = next(result)

However, the second way works on native objects as I know (tested with list). And following example, which then also works, displays only every second entry:

# range(0, 10, 2) in a more complex shape:
result = list(range(10))
result = iter(result)
for i in result:
    print(i)
    a = next(result)

Got the same error as you did in your second example while working with Pony today. I will see if I can create a PR fixing this, should be easy to do.

EDIT: Did not know that before, but implementing the __iter__ method to an Iterator as well (and not just to an Iterable) is even a requirement by Python, so that first calling iter(iterable) and then using it in a for loop is possible without hassle.

Zocker1999NET avatar Jul 02 '22 18:07 Zocker1999NET