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.)
- Text I/O - interface TextIOBase
- Binary I/O - interface BufferedIOBase
- 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
精彩评论