Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Advancing Python generator function to just before the first yield [duplicate]

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?

like image 556
WGH Avatar asked Apr 19 '16 18:04

WGH


People also ask

Can we call generator multiple times in Python?

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.

What does next () do in a generator Python?

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.

How do I reinitialize a generator in Python?

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.

Can a generator function have multiple yield expressions?

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.


1 Answers

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

like image 182
user2357112 supports Monica Avatar answered Oct 20 '22 15:10

user2357112 supports Monica