Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a Python class be written such it may be passed to write()?

Tags:

I'd like to pass an instance of my class to write() and have it written to a file. The underlying data is simply a bytearray.

mine = MyClass()

with open('Test.txt', 'wb') as f:

    f.write(mine)

I tried implementing __bytes__ to no avail. I'm aware of the buffer protocol but I believe it can only be implemented via the C API (though I did see talk of delegation to an underlying object that implemented the protocol).

like image 674
Kenny Avatar asked Feb 26 '19 21:02

Kenny


1 Answers

No, you can't, there are no special methods you can implement that'll make your Python class support the buffer protocol.

Yes, the io.RawIOBase.write() and io.BufferedIOBase.write() methods document that they accept a bytes-like object, but the buffer protocol needed to make something bytes-like is a C-level protocol only. There is an open Python issue to add Python hooks but no progress has been made on this.

The __bytes__ special method is only called if you passed an object to the bytes() callable; .write() does not do this.

So, when writing to a file, only actual bytes-like objects are accepted, everything else must be converted to such an object first. I'd stick with:

with open('Test.txt', 'wb') as f:
    f.write(bytes(mine))

which will call the MyClass.__bytes__() method, provided it is defined, or provide a method on your class that causes it to write itself to a file object:

with open('Test.txt', 'wb') as f:
    mine.dump(f)
like image 193
Martijn Pieters Avatar answered Oct 05 '22 23:10

Martijn Pieters