exception - Advancing Python generator function to just before the first yield -


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

Popular posts from this blog

java - nested exception is org.hibernate.exception.SQLGrammarException: could not extract ResultSet Hibernate+SpringMVC -

sql - Postgresql tables exists, but getting "relation does not exist" when querying -

asp.net mvc - breakpoint on javascript in CSHTML? -