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?
But we need to consume the generator multiple times in multiple functions. In order to call the generator and each generated object exactly once we can use threads and Run each of the consuming methods in different thread.
Generator Implementation in Python Above I had first created a generator function that has three yield statements and when we call this function is returns a generator which is an iterator object. We then called the next() method to retrieve elements from this object.
To reset a generator object in Python, we can use the itertools. tee method. to call itertools. tee with generator y to get a 2nd version of the generator.
If you want to return multiple values from a function, you can use generator functions with yield keywords. The yield expressions return multiple values. They return one value, then wait, save the local state, and resume again.
Wrap a regular function around the generator and put the initialization there:
def file_contents_repeated(filename):
with open(filename) as f:
data = f.read()
return _gen(data)
def _gen(data):
while True:
yield data
(In this case, you could replace the inner generator with itertools.repeat
, but not in general.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With