How should I deal with file handles when I return a generator?
<p>I have this function in my code:</p>

<pre><code>def load_fasta(filename):
    f = open(filename)
    return (seq.group(0) for seq in re.finditer(r"&gt;[^&gt;]*", f.read()))
</code></pre>

<p>This will leave the file open indefinitely, which isn't good practice. How do I close the file when the generator is exhausted? I guess I could expand the generator expression into a for loop with yield statements and then close the file afterwards. I'm trying to use functional programming as often as possible, though (just as a learning exercise). Is there a different way to do this?</p>

<p>Use <code>yield</code> instead of a single generator expression.</p>

<pre><code>def load_fasta(filename):
    with open(filename) as f:
        for seq in re.finditer(r"&gt;[^&gt;]*", f.read()):
            yield seq.group(0)

for thing in load_fasta(filename):
    ...
</code></pre>

<p>The <code>with</code> statement will close the file once the <code>for</code> loop completes. Note that since you read the entire file into memory anyway, you could simply use</p>

<pre><code>def load_fasta(filename):
    with open(filename) as f:
        data = f.read()
    for seq in re.finditer(r"&gt;[^&gt;]*", data):
        yield seq.group(0)
</code></pre>

python functional-programming generator