Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Making class useable as a Path or str in python open function

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading