Feb-25-2021, 03:12 AM
Feb-25-2021, 09:23 AM
The documentation looks crystal clear to me.
Feb-25-2021, 10:14 AM
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
Feb-25-2021, 11:35 AM
There where also a own PEP just for this PEP 519.
519 Wrote:This lack of support required users ofpathlib
to manually convert path objects to strings by callingstr(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, 07:41 PM
(Feb-25-2021, 03:12 AM)Skaperen Wrote: [ -> ]what does os.fspath() really do?
but not to me.
Feb-25-2021, 07:43 PM
so, basically, they wanted str() to not work right and made something else that would/
Feb-26-2021, 03:05 AM
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.
Feb-27-2021, 10:47 PM
Hat jemand die Dokumentation für os.fspath() auf Deutsch?