Duration of open handles in a python generator housing

I have a question about generators and / or python runtime models.

Given something like:

def g(filename): with open(filename) as handle: for line in handle: yield some_trasformation_on(line) 

My main misunderstanding: what happens if

 res = g() print(next(res)) 

only called once? Does the pen remain open for program life? What if we have limited resources allocated in the generator housing? Streams? Does the database process?

Perhaps I see generators as functions under the hood.

+5
source share
1 answer

Answer the code as it is written

As described, the file will remain open for the life of the program. As long as you refer to the res variable, it saves the generator life cycle, so the only way to get a with-statement to close the file is to continue calling next () until the for-loop completes normally.

How to clean the generator

A tool designed to clean the generator, generator.close () , which calls GeneratorExit inside the generator.

Here is some working code that shows how to do this:

 def genfunc(filename): try: with open(filename) as datafile: for line in datafile: yield len(line) finally: print('Status: %s' % datafile.closed) 

And here is an example session showing that the closing operation is actually happening:

 >>> g = genfunc('somefile.txt') >>> next(g) 23 >>> g.close() Status: True 
+3
source

Source: https://habr.com/ru/post/1240044/


All Articles