Open file and using instructions in Python

I have a function like:

def func(filename): with open(filename) as f: return [line.split('\t')[0] for line in f] 

Does the c operator close the file even when the flash function returns? Can I ignore the expression "c"? i.e. safe and equivalent (in terms of memory leak),

 def func(filename): return [line.split('\t')[0] for line in open(filename)] 

?

+4
source share
2 answers

It is safe. The __exit__ context manager is called even if you return while inside the context, so the file descriptor is properly closed.

Here is a simple test:

 class ContextTest(object): def __enter__(self): print('Enter') def __exit__(self, type, value, traceback): print('Exit') def test(): with ContextTest() as foo: print('Inside') return 

When you call test() , you get:

 Enter Inside Exit 
+4
source

The guarantee of this security is actually the whole syntax with...as... ; it replaces try / finally blocks, which would otherwise be rather inconvenient. So yes, it is guaranteed to be safe, so I prefer with open as f to f = open .

See http://effbot.org/zone/python-with-statement.htm for a good explanation of why the syntax exists and how it works. Note that you can write your own classes using the __enter__ and __exit__ methods to really take advantage of this syntax.

Also see PEP for this function: http://www.python.org/dev/peps/pep-0343/

0
source

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


All Articles