[issue23227] Generator's finally block not run if close() called before first iteration

Marco Paolini report at bugs.python.org
Wed Apr 22 12:17:12 CEST 2015


Marco Paolini added the comment:

I think there is an issue in the way you designed your cleanup logic. So I think this issue is invalid.

Usually, the code (funcion, class, ...) that *opens* the file should also be resposible of closing it.

option 1) the caller opens and closes the file and wrapping the logged lines in a try/finally


def logged_lines(f):
    try:
        for line in f:
            logging.warning(line.strip())
            yield line
    finally:
        logging.warning('closing')


f = open('yyy', 'r')
try:
    for l in logged_lines(f):
       print(l)
finally:
    f.close()


option 2) the funcion opens and closes the file

def logged_lines(fname):
    f = open('yyy', 'r')
    try:
        for line in f:
            logging.warning(line.strip())
            yield line
    finally:
        logging.warning('closing')
        f.close()

for l in logged_lines('yyy'):
   print(l)

----------
nosy: +mpaolini

_______________________________________
Python tracker <report at bugs.python.org>
<http://bugs.python.org/issue23227>
_______________________________________


More information about the Python-bugs-list mailing list