WildGunman WildGunman - 1 year ago 85
Python Question

Why is this python generator function running correctly only once?

This is almost certainly a result of my ignorance of how generators work, but I am completely lost.

If I interactively create the following generator:

def neighborhood(iterable):
iterator = iter(iterable)
prev = None
item = next(iterator)
for post in iterator:
yield (prev,item,post)
prev = item
item = post
yield (prev,item,None)

and then test it like:

for prev,item,next in neighborhood([1,2,3,4,5]):
print(prev, item, next)

It produces:

None 1 2
1 2 3
2 3 4
3 4 5
4 5 None

as expected. If I run it again, or try to redefine it in any way, I get a

'NoneType' object is not callable"


Answer Source

When you did

for prev,item,next in ...
#             ^^^^

you shadowed the built-in next function. The next time you try to use your generator, it fails because it gets your next variable instead of the function it needed.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download