51

From the documentation for the standard library json module:

json.dump(obj, fp, *, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, default=None, sort_keys=False, **kw)

Serialize obj as a JSON formatted stream to fp (a .write()-supporting file-like object) using this conversion table.

What exactly does this description mean? What object types are ".write()-supporting", and "file-like"?

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
Kordan Ou
  • 1,502
  • 3
  • 15
  • 25
  • 4
    Well, you answered your question yourself: really _any_ object that supports proper invocations of either read(), write(), or both, is considered to be a file-like object. It really can be any object you like - the joy of duck typing. – Jim Brissom Dec 05 '10 at 15:43
  • I don't think there's any official standard. Most interfaces should specify exactly the functionality they require. If you want to know if some other thing supports what is needed, you'll have to look at the docs for it or read its source code. – martineau Dec 05 '10 at 18:46
  • 2
    "File-like object" is, in fact, [precisely defined](https://docs.python.org/3/glossary.html#term-file-like-object). – chepner Nov 14 '19 at 16:21
  • In more recent versions of the documentation, this passage has been updated for `json.load` not to mention "file-like objects": "Deserialize fp (a .read()-supporting text file or binary file containing a JSON document) to a Python object using this conversion table." However, the `json.dump` description still mentions the concept. The documentation also hasn't used the `simplejson` name in approximately forever. – Karl Knechtel Jan 19 '23 at 06:24
  • **Historical note**: The `json` standard library module was added in Python 2.6, and its documentation didn't include a link to explain the "file-like object" concept, nor did it mention that in the glossary. This library came from a third-party project called `simplejson`, some version of which was incorporated wholesale; documentation at the time may have mentioned the `simplejson` name, but current documentation for 2.6 does not. (Legacy documentation for 2.5 and before seems not to contain a glossary at all.) – Karl Knechtel Jan 19 '23 at 06:37
  • 1
    I edited the question to show an example from the current documentation that does mention (and link) the concept, and to remove a section about motivation for the question (since it doesn't make sense with the changed example). If you are here because you are trying to figure out how to handle JSON from a web request (or close a question as a duplicate), like with OP's original motivation, please refer to the canonical: [How can I parse (read) and use JSON?](/questions/7771011). – Karl Knechtel Jan 19 '23 at 06:39

6 Answers6

26

From the glossary:

file-like object

A synonym for file object

and a file object is

file object

An object exposing a file-oriented API (with methods such as read() or write()) to an underlying resource. Depending on the way it was created, a file object can mediate access to a real on-disk file or to another type of storage or communication device (for example standard input/output, in-memory buffers, sockets, pipes, etc.). File objects are also called file-like objects or streams.

There are actually three categories of file objects: raw binary files, buffered binary files and text files. Their interfaces are defined in the io module. The canonical way to create a file object is by using the open() function.

chepner
  • 497,756
  • 71
  • 530
  • 681
  • 8
    "with methods such as" ... I suppose that really brings us back to the original question: what _exactly_ is this set of methods? Is e.g. "mode" a required attribute of such an object, or not? – Klaas van Schelven Jan 20 '22 at 12:54
  • @KlaasvanSchelven That, unfortunately, may depend on the underlying operating system or file system. – chepner Jan 20 '22 at 13:05
  • I suppose the question is rhetorical at this point ;-) The point being that we have different opinions on the meaning of "precisely defined" – Klaas van Schelven Jan 20 '22 at 15:05
  • "That, unfortunately, may depend on the underlying operating system or file system." Then it's not an API. Or at least not a single API. An API is a rigid interface; it's not conditional. – cowlinator Jun 23 '22 at 01:41
18

The IO Class Hierarchy section in the IO documentation contains a table listing the built-in and stub methods for the different types of file-like objects.

Basically, there is a hierarchy of abstract base classes:

To implement a file-like object, you would subclass one of the three descendants of IOBase, but not IOBase itself. See this answer for attempting to determine which of these a given file-like object is.

Each of these classes provides various stub methods and mixins:

Class Stub Methods Mixins
IOBase fileno, seek, truncate close, closed, __enter__, __exit__, flush, isatty, __iter__, __next__, readable, readline, readlines, seekable, tell, writable, writelines
RawIOBase readinto, write read, readall
BufferedIOBase detach, read, read1, write readinto, readinto1
TextIOBase detach, read, readline, write encoding, errors, newlines

The documentation for these methods can be found in the documentation for the classes, linked above.

Phoenix
  • 1,553
  • 2
  • 13
  • 29
17

In Python, a file object is an object exposing an API having methods for performing operations typically done on files, such as read() or write().

In the question's example: simplejson.load(fp, ...), the object passed as fp is only required to have a read() method, callable in the same way as a read() on a file (i.e. accepting an optional parameter size and returning either a str or a bytes object).

This does not need to be a real file, though, as long as it has a read() method.

A file-like object is just a synonym for file-object. See Python Glossary.

Adrian W
  • 4,563
  • 11
  • 38
  • 52
13

File-like objects are mainly StringIO objects, connected sockets and, well, actual file objects.

If everything goes well, urllib.urlopen() returns a file-like object supporting the necessary methods.

Alistair Carscadden
  • 1,198
  • 5
  • 18
ThiefMaster
  • 310,957
  • 84
  • 592
  • 636
5

This is the API for all file-like objects in the Python standard library (as of 3.10.5).

# All file-like objects inherit the IOBase interface:
# Documented at https://docs.python.org/3/library/io.html#io.IOBase .
    close() -> None
    closed() -> bool # Implemented as @property `closed`
    fileno() -> int
    flush() -> None
    isatty() -> bool
    readable() -> bool
    readline(size: int = -1) -> Union[str, bytes]
    readlines(hint: Union[int, None] = None) -> list
    seek(pos: int, whence: int = io.SEEK_SET) -> int # SEEK_SET is 0
    seekable() -> bool
    tell() -> int
    truncate(pos: int = None) -> int # The parameter is named "size" in class FileIO
    writable() -> bool
    writelines(lines: list) -> None
    __del__() -> None
# Documented at https://docs.python.org/3/library/io.html#class-hierarchy .
    __enter__()
    __exit__(*args) -> None:
    __iter__()
    __next__() -> Union[str, bytes]
# Documented in paragraph at https://docs.python.org/3/library/io.html#io.IOBase .
# Note that while the documentation claims that the method signatures 
# of `read` and `write` vary, all file-like objects included in the Python 
# Standard Library have the following exact method signatures for `read` and `write`:
    read(size: int = -1) -> Union[str, bytes]
    write(b: Union[str, bytes]) -> int # The parameter is named "s" in TextIOBase

Specific file-like objects may implement more than this, but this is the subset of methods that are common to ALL file-like objects.

cowlinator
  • 7,195
  • 6
  • 41
  • 61
  • 2
    This is true for the standard library only. In many places in the Python world (even on [docs.python.org](https://docs.python.org)) "file-like object" is a far looser notion. In many cases, having a `read(size: int)` method will be sufficient. – Lutz Prechelt Oct 02 '22 at 12:18
  • I updated my answer to be about the standard library only. – cowlinator Oct 04 '22 at 23:43
0

simplejson has the calls loads and dumps that consumes and produce strings instead of file like objects.

This link has an example in the context of StringIO and simplejson for both file-like and string objects.

http://svn.red-bean.com/bob/simplejson/tags/simplejson-1.3/docs/index.html

kevpie
  • 25,206
  • 2
  • 24
  • 28
  • 1
    @user313439, you're welcome. Just to be clear, you should be using dumps and loads with strings. Adding StringIO in your situation is extra overhead. – kevpie Dec 06 '10 at 11:42