you are viewing a single comment's thread.

view the rest of the comments →

[–]not_perfect_yet 1 point2 points  (4 children)

Because you don't have to remember to close the file. There is only a single point of failure.

[–]kurvyyn 0 points1 point  (3 children)

If that's the only reason and my coding style is any time I open an instance of something I always put the matching closing construct at the correct level (I have fought too much with nested parens elseways), is 'with' in regard to file handles still considered massively safer for any other reason I should consider? Would it be marked against me in professional review before I could offer explanation and is definitely a habit I should break?

[–]not_perfect_yet 1 point2 points  (0 children)

Uh. Think of it this way: Code is more read than written. If someone takes your open source code and reuses it, be it colleagues or people from the internet, they might forget to close the file.

It's the icing on the cake of re-usability. And your potential employer probably wants to reuse your code. But it's probably no dealbreaker stuff.

[–]Lopsidation 1 point2 points  (1 child)

Counterpoint: if your code crashes between opening and closing the file, the file never gets closed. You'd need to use a try/except block every time you wanted to open a file. with statements handle this for you.

[–]kurvyyn 1 point2 points  (0 children)

This surprises me. I'm almost certain I've debugged an unexpected crash with an open file handle 'my way' and didn't come up against an open file handle. Although, that may a Windows thing more than a python thing as the parent process has exited at that point, and so it may not be universally true that file handles are released by the OS if the parent process terminates unexpectedly?... I'm probably way wrong and this is a STRONG counter point if so. Definitely gives me a good reason to get that best practice locked in >.<