I have a custom File class. I want to be able to pass it to the built-in open function like this:
f = File('./example.txt')
with open(f, 'rb') as fh:
# read content as usual
But this results in the error
TypeError: expected str, bytes or os.PathLike object, not File
The File class has a __str__ method which returns a string that can be used with open, so this works for me:
with open(str(f), 'rb') as fh:
But I want to use f directly. I tried inheriting it from Path but could not figure it out. Is there a simple way to make this work?
>Solution :
You need to create an os.PathLike object by adding an __fspath__ method that returns the path.
Example:
>>> class File:
... def __fspath__(self):
... return "C:\\temp"
...
>>> open(File())
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
PermissionError: [Errno 13] Permission denied: 'C:\\temp'
For more info, see the relevant documentation.