pathlib already provides multiple methods / properties which return things as a str object
the reasoning is that It is kind of odd that you have a ton of properties that give you parts of the path, but no property that gives you the whole path
pathlib.PurePath.name for example
I propose an Pathobj.fullpath or Pathobj.full_path property be added
this should result in the same operation as str(Pathobj) so that Pathobj.resolve().full_path can also work
Given that str(path) does this already, I think you’ll have to convince people that it’s “odd”.
I wouldn’t consider it strange for Path to alias its string representation, if it had done from the start, but nor do I find it strange that it doesn’t do so. Either way seems fine, so why add anything?
os.fspath was added (PEP 519 – Adding a file system path protocol | peps.python.org) specifically to cover converting rich path objects like pathlib.Path and os.DirEntry to regular file system path strings without risking incorrect conversions of objects that don’t represent a path.
It’s a dunder protocol rather than a regular method for the same reason as other language level protocols: it allows generic handling in API consumers without having to reserve a regular public attribute name for the purpose.
I don’t see what’s wrong with str(path) but there is path.as_posix() which returns a string and works with windows paths too:
>>> from pathlib import *
>>> p = Path(r"C:\users\monarch\hello python\3.12")
>>> p.as_posix()
'C:\\users\\monarch\\hello python\\3.12'
>>>
Although ideally, you won’t need to convert Path objects to string, atleast I rarely have had to convert Path to strings thanks to the __fspath__ protocol.
It’s kinda annoying to import os just for os.fspath when working with Path. To keep the consistency, I would be in favor of adding Path.fspath as an alias to Path.__fspath__. That said, I’m not sure if it’s worth it but it would be a nice addition.
os.fspath is very useful in functions that take pathlike arguments, it enables to easily normalize the inputs without side effects. Path.fspath would be useful when calling functions that take str arguments. My last example is from this morning, where I wanted to use datetime.strftime() to format a filename with a path build with Path.
Yes. As others have said, there should be something in the pathlib API.
Recently I came across the third party library “path”. I really like it simply to be able to do path.write_text('some_text\n', append=True), but it also implements Path as a str subclass.