Open file and with statement in Python -
i have function like:
def func(filename): open(filename) f: return [line.split('\t')[0] line in f]
is "with" statement closing file when there 'sudden' function return? can ignore "with" statement? i.e. safe , equivalent (from memory leak perspective) do,
def func(filename): return [line.split('\t')[0] line in open(filename)]
?
it's safe. context manager's __exit__
called if return
while inside of context, file handle closed.
here's simple test:
class contexttest(object): def __enter__(self): print('enter') def __exit__(self, type, value, traceback): print('exit') def test(): contexttest() foo: print('inside') return
when call test()
, get:
enter inside exit
Comments
Post a Comment