When working with pathlib.Path objects, I have been recommending the use of open(path) over path.open() and it’s been brought to my attention that this recommendation is at odds with some linter rules, such as ruff’s PTH123 which recommends replacing open(path) with path.open().
I would like to know what folks think about updating the pathlib documentation to recommend one of these over the other (for an official stance on “there should be one and preferably only one obvious way”).
My reasoning for recommending open(path) over path.open() can be summed up as:
pathlibwas added to Python in Python 3.4 (it was previously a third-party library)- The built-in
openfunction did not acceptpathlib.Pathobjects in Python 3.4 or Python 3.5 - After PEP 519 was accepted, the new
__fspath__was used by the built-inopenfunction (and many other tools) to allow the built-inopenfunction to acceptpathlib.Pathobjects directly - Since Python 3.5’s EOL in 2020,
pathlib.Path.openhas been rendered redundant (now that the built-inopenfunction accepts any Path-like object in all supported Python versions
Personally, I also prefer using the built-in open function because if I see Python code that includes the expression open(args.cf), I know that a file is being opened, but when I see args.cf.open() I may feel the need to find where args.con was defined to make sure I understand what it is.
I would like to see the pathlib documentation take a stance on whether the built-in open function should be preferred over the open method (or the other way around).