Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

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.



Pathlib opens and closes the file. With your version, unless I'm mistaken the file does not get closed


Python 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.


> 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


> 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.


CPython relies on reference count.

other python implementations, like PyPy, does not.




Consider applying for YC's Fall 2025 batch! Applications are open till Aug 4

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: