0

What is the behavior of .close() on a generator that has just started?

def gen():
  while True:
    yield 1

g = gen()
g.send(1)

throws TypeError: can't send non-None value to a just-started generator

def gen():
    while True:
        try:
            yield 1
        except GeneratorExit:
            print("exit")
            raise

g = gen()
next(g)
g.close()

prints exit

But what is the behavior of:

def gen():
    while True:
        try:
            yield 1
        except GeneratorExit:
            print("exit")
            raise

g = gen()
g.close()

and how can I check it?

EDIT:

When I try it, nothing happens, but subsequent calls to next(g) raise StopIteration.

My question is actually: what happens in terms of memory, but I guess most is freed.

Labo
  • 2,482
  • 2
  • 18
  • 38
  • Did you try it? ("Try it" isn't a fully reliable way to know what something does, since you don't know if it'll *always* do the same thing, but... you tried the first two code blocks. Why not the last one?) – user2357112 Nov 29 '22 at 09:23
  • Does this answer your question? [Send method using generator. still trying to understand the send method and quirky behaviour](https://stackoverflow.com/questions/19892204/send-method-using-generator-still-trying-to-understand-the-send-method-and-quir) – Sin Han Jinn Nov 29 '22 at 09:34

1 Answers1

1

Quoting from the docs (shortened):

Raises a GeneratorExit at the point where the generator function was paused.

close() does nothing if the generator has already exited

When it was not started, it couldn't be paused or exited. The case it was not started (with an initial next or send) is not mentioned.

But we could easily check that not a single statemenet from the generator function was executed before .close() and no statement could be executed after the .close().

That is the only logical behaviour, IMO. There is nothing to be cleaned up in the generator function, because it did not get a chance to run.

VPfB
  • 14,927
  • 6
  • 41
  • 75