开发者

Creating a stream class in Python

I have a class which expects a stream that contains an XML file.

I don't necessari开发者_JAVA百科ly 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?


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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜