Consider following code snippet:
class C(object):
a = 0
b = 1
seq = [1, 2, 4, 16, 17]
list_comp = [a if v%2 else b for v in seq]
gen_comp = (a if v%2 else b for v in seq)
Code above in interpreted fine. Printing object bound to class variables results in:
print C.list_comp # [0, 1, 1, 1, 0]
print C.gen_comp # <generator object <genexpr> at ...>
Sad part is - attempt to retrieve value from generator results in NameError
:
next(C.gen_comp) # NameError: global name 'a' is not defined
Expected behavior should be similar to list comprehension - it should yield 5 values and raise StopIteration
on each next next()
call.
What makes a difference here? How names are resolved in each case and why discrepancy occures?