Search code examples
pythongenerator

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


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.


Solution

  • 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.