On The Value Of File-Like Objects In Python

The aim of this page📝is to learn about file-like objects in python. This is a convenient and fairly informal description of a set of expectations we can place on an object. These expectations are enabled by duck typing. It is therefore too simple to claim that file-like object is a synonym for file object and nothing else (https://docs.python.org/3/glossary.html#term-file-like-object).

Instead, it should be understood that this is the language feature enabling treatment of custom types of resources as if they were files with standard ways of file handling.

# output
<class '_io.TextIOWrapper'>
[3, 9, 9, 3, 9, 9]
<class 'http.client.HTTPResponse'>
[6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 5, 5, 7, 8, 14, 12, 8]
  • file-like objects that behave like files
  • there is not a formal specific protocol such as a sequence/iterator protocol that a custom type would have to implement
  • but, thanks to polymorphism allowed by duck typing — the concept works well in practice
  • reasons for the absence of exact protocol:
  • many types of data streams and devices have different capabilities/behavior/expectations
  • difficult to define a highly specific protocol
  • it is here where EAFP approach is useful
  • for example, try to perform seek() on a file-like object if you believe it allows random access (is not an iterator) — be prepared to fail if seek() is not supported
  • an object exposing a file-oriented API with methods such as read() or write() to an underlying resource
  • also open() & close() to open and close the resource
  • also seek() & tell() to manipulate stream pointer

Technical Support Engineer/Technical Writer (Snowplow Analytics). with a passion for Python / writing documentation. More about me: https://pavol.kutaj.com