What does a file-like object's `write` method return?

Viewed 288

Python's built-in open function returns a "file-like object". These file objects can be obtained in other ways as well, and may not actually represent files.

I haven't been able to find what I want to know about these.

https://docs.python.org/3/glossary.html#term-file-object states that all file objects all have 1 thing in common: they expose "a file-oriented API". But I can't find any documentation about this api.

A file object's write method seems to return an integer, but what does it represent? Is the return value guaranteed to be an integer? What methods and properties are file objects guaranteed to have?

1 Answers

People are so unlikely to use the return value of write that I wouldn't be surprised if any particular file-like object just returned None. That said, there is something resembling a spec.

The behavior a file-like object's methods should provide is documented in the io module docs, under the abstract base classes. While many file-like objects will not be instances of those ABCs, and many file-like objects will not provide all methods in the nearest ABC, methods they do provide should match the ABC docs.

For a binary file-like object, write should return the number of bytes written, as documented under RawIOBase.write.

For a text file-like object, write should return the number of characters written, as documented under TextIOBase.write.

Related