It's my understanding that python generator expressions return lazily evaluated comprehensions, and view objects on dictionaries update when their underlying dictionary is changed.
Given the following code (Python 2.7.6 Windows):
d = {}
gt_three = (x for x in d.viewkeys() if x > 3)
print list(gt_three)
d[1] = 'one'
d[4] = 'four'
print list(gt_three)
I would expect output like:
[]
[4]
Instead, I'm receiving:
[]
[]
If I recreate the generator after adding to the dictionary, or print the view itself, I do see the expected output. What am I not understanding about generators? I'm quite new to python.
A generator expression returns an iterator, which you can only iterate over once. Attempts to iterate over an iterator after the first time will always see it as empty.