I'm trying to implement a PathLike object and use fspath command to retrieve the o/p from fspath function.
What I'm expecting is, if a PathLike object is passed to fspath function, it should return the value of fspath (here it should return the path in bytes). However, it is still returning in str.
import os,pathlib
class imp(os.PathLike):
def __init__(self,path):
self.path=path
def __fspath__(path):
return bytes(path)
re=imp('/etc/')
print(os.fspath(re.path))
Output: '/etc/'
Expected output : b '/etc/'
Can you please let me know where I went wrong and how should I change the code so that it works as expected?
The problem is that you’re calling fspath on re.path instead of on re.
While re is a pathlike object, for which fspath will use the __fspath__ protocol, re.path is just a string, so it returns the string unchanged.
As the docs say:
If
strorbytesis passed in, it is returned unchanged. Otherwise__fspath__()is called and its value is returned as long as it is astrorbytesobject. In all other cases,TypeErroris raised.
Meanwhile, your __fspath__ is wrong in two ways. First it’s a method, which should take self and do something with self.path; as-is, you’re taking that self as a variable named path and trying to use it as a string. Second, you have to call encode on your string (with the appropriate encoding—which is usually the fs encoding, although in that case you don’t even need to bother and can just return a string), not pass it to the bytes constructor.
Also, for debugging purposes, it would had been a lot easier to spot the problem if your string and bytes were completely unrelated. If, say, re.path were 'unicodepath' while __fspath__ returned ’8bitpath', it would be pretty clear whether it was ignoring your method or deciding things behind your back.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With