4 ms·
I'm not sure I understand what value pathlib is providing here. The explanation is to avoid the context manager / multi-line. Why though? What is saving you on
by Twirrim 4y ago
I'm not sure I understand what value pathlib is providing here. The explanation is to avoid the context manager / multi-line.
Why though? What is saving you one line really getting? It's not really improving readability in any way.
An alternative one liner could be
contents = open("foo").read(100)
No need to import another library and use its features.
Added to which pathlib has some speed issues. Pathlib has some really neat advantages and should be favoured over most of os library file stuff, but not as a replacement for a simple open.
- Majestic121 4y agoPathlib 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.