Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a stream class in Python

Tags:

python

stream

I have a class which expects a stream that contains an XML file.
I don't necessarily want a file stream and I might want to use other sources like a database, a socket etc.
What class do I need to subclass from the io module in order to supply the stream interface from other sources?

like image 796
the_drow Avatar asked Apr 05 '11 21:04

the_drow


2 Answers

The answer given by Andrey isn't entirely correct.

In Python, streams are "file-like" objects. You can read/write to them using tools defined in the io module. The module also provides interfaces which you should implement if you want to define a stream object.

Note that the io module differentiates between three different types of streams, which require slightly different interfaces. (They differ mostly in terms of data types.)

  1. Text I/O - interface TextIOBase
  2. Binary I/O - interface BufferedIOBase
  3. Raw I/O - interface RawIOBase

StringIO for example is an in-memory implementation of the TextIOBase.

Note that these interfaces are available both on Python 2 and 3.

like image 81
arnuschky Avatar answered Oct 01 '22 13:10

arnuschky


Dynamic typing allows you not to subclass from any base class in this case. You should implement some methods with proper names. Blog post on the subject

like image 22
Andrey Sboev Avatar answered Oct 01 '22 13:10

Andrey Sboev