I want to create an iterator that counts the length of another iterator while consuming it. Here is a working example of what I want to achieve:
from random import random
def randleniter(p):
while random() < p:
yield 7
count = 0
def do():
def countiter(piter):
global count
for i in piter:
count += 1
yield i
list(countiter(randiter(0.99))) #simulator for a different method consuming the iterator
return count
>>> do()
81
However, I would have never built it like this if I intended to use a global variable. I imagined that since I can do this with nested methods:
def make_adder(x):
def add(y):
return x + y
return add
I would be able to do this:
def do():
count = 0
def countiter(piter):
for i in piter:
count += 1
yield i
list(countiter(randiter(0.99)))
return count
but this results in a UnboundLocalError: local variable 'count' referenced before assignment. When I print locals() from inside the countiter - it doesn't include count.
Can I make countiter access count somehow?