Python Forum

Full Version: what does os.fspath() really do?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
what does os.fspath() really do?
The documentation looks crystal clear to me.
Here an example with a class, which has two behaviors:
  • string representation
  • path representation

class MyPath:
    def __str__(self):
        return "This is a str"
    def __fspath__(self):
        return "This is the path of the instance"
If you create an instance and use the built-in function open(), it uses the str representation of the instance for the path.

test_path = MyPath()

try:
    fd = open(test_path, "rb")
except FileNotFoundError as e:
    print(e)
else:
    fd.close()
Now the same with pathlib, which access __fspath__ if the input is not a str or bytes:
from pathlib import Path

test_path = MyPath()

my_path = Path(test_path)
print(my_path)
Output:
This is the path of the instance
There where also a own PEP just for this PEP 519.
519 Wrote:This lack of support required users of pathlib to manually convert path objects to strings by calling str(path) which many found error-prone.

One issue in converting path objects to strings comes from the fact that the only generic way to get a string representation of the path was to pass the object to str().
This can pose a problem when done blindly as nearly all Python objects have some string representation whether they are a path or not,
e.g. str(None) will give a result that builtins.open() [5] will happily use to create a new file.
>>> from pathlib import Path
>>> from os import fspath
>>> 
>>> working_dir = Path.cwd()
>>> working_dir
WindowsPath('E:/div_code')
>>> 
>>> # Convert Path object to string the recommend way not using str()
>>> fspath(working_dir)
'E:\\div_code'
>>> 
>>> # Can also to it without import of os.fspath() 
>>> working_dir.__fspath__()
'E:\\div_code'
(Feb-25-2021, 03:12 AM)Skaperen Wrote: [ -> ]what does os.fspath() really do?

but not to me.
so, basically, they wanted str() to not work right and made something else that would/
i've re-read the documentation a couple dozen times and have concluded that not understanding this is due to a pronoun ambiguity where two pronoun references precede a third pronoun making its unstated reference ambiguous. maybe i should go read this documentation in another language.
Hat jemand die Dokumentation für os.fspath() auf Deutsch?