3 ms·
Pathlib opens and closes the file. With your version, unless I'm mistaken the file does not get closed
by Majestic121 4y ago
Pathlib opens and closes the file. With your version, unless I'm mistaken the file does not get closed
- kevincox 4y agoPython is reference counted and it is very clear in this code that a reference to the file isn't leaked, so the file will be reliably closed at the end of the statement. Some people don't like to rely on the reference counter but I think in simple cases like this where only a temporary is created it is quite safe.
- rcthompson 4y ago> it is very clear in this code that a reference to the file isn't leaked Is it? What if an exception is thrown? See e.g. this SO answer[1]: > However if an exception is thrown [...] then a reference to the file will be kept as part of the stack trace in the traceback object and the file will not be closed, at least until the next exception is thrown. So your code, if called from somewhere else inside a try block, leaks a filehandle potentially indefinitely. [1]: https://stackoverflow.com/a/2404671/125921 https://stackoverflow.com/a/2404671/125921
- _ZeD_ 4y agoCPython relies on reference count. other python implementations, like PyPy, does not.
- nicolaslem 4y ago> the file will be reliably closed at the end of the statement. The only guarantee CPython makes is that it may eventually close the file once all references are gone. The fact that it does it immediately and reliably in this specific case is an implementation detail and should not be relied upon. Use context managers when things need to be closed and save yourself trouble down the line.