When you instantiate a generator function, it won't execute any code until you call next
on it.
It means that if generator function contains some kind of of initialization code, it won't be executed until it's iterated on.
Consider this example:
def generator(filename):
with open(filename) as f:
data = f.read()
while True:
yield data
gen = generator('/tmp/some_file')
# at this point, no generator code is executed
# initialization code is executed only at the first iteration
for x in gen:
pass
If the file does not exist, the exception will be raised at the for loop. I'd
like the code before the first yield
to execute before generator is iterated over, so any exceptions during the initialization will be raised
at generator instantiation.
Is there a clean pythonic way to do so?