exception - Advancing Python generator function to just before the first yield -
this question has answer here:
when instantiate generator function, won't execute code until call next
on it.
it means if generator function contains kind of of initialization code, won't executed until it's iterated on.
consider example:
def generator(filename): open(filename) f: data = f.read() while true: yield data gen = generator('/tmp/some_file') # @ point, no generator code executed # initialization code executed @ first iteration x in gen: pass
if file not exist, exception raised @ loop. i'd code before first yield
execute before generator iterated over, exceptions during initialization raised @ generator instantiation.
is there clean pythonic way so?
wrap regular function around generator , put initialization there:
def file_contents_repeated(filename): open(filename) f: data = f.read() return _gen(data) def _gen(data): while true: yield data
(in case, replace inner generator itertools.repeat
, not in general.)
Comments
Post a Comment