What is the minimal subset of file methods I need to implement to get the full python file interface?
<p>Python has the marvelous <a href="http://docs.python.org/library/collections.html" rel="nofollow"><code>collections</code></a> module that has tools to allow you to implement a full <code>dict</code> (for example) from a minimal set of methods. Is there a similar thing for the <code>file</code> interface in Python? If not, what would you recommend as a minimal set of methods to implement for a <code>file</code>-like object for duck-typing purposes?</p>

<p>And how do you deal with things that would like to use your file like object in a <code>with</code> statement, like you can with a regular file, or who want to iterate over it (like you can with a regular file) or who want to be able to call <code>readline</code> or <code>readlines</code> and have it do something intelligent and useful (like you can with a regular file)? Do you have to implement them all yourself? Or are there better options?</p>

<p>I know I can implement each and every single one of these myself, by hand. But the <code>collections</code> interface allows me to implement a <code>dict</code> by implementing just <code>__len__</code>, <code>__iter__</code>, <code>__setitem__</code>, and <code>__getitem__</code>. I get <code>pop</code>, <code>popitem</code>, <code>clear</code>, <code>update</code>, <code>setdefault</code>, <code>__contains__</code>, <code>keys</code>, <code>items</code>, <code>values</code>, <code>get</code>, <code>__eq__</code>, and <code>__ne__</code> all for free. There is a minimal interface for <code>__dict__</code> defined, and if I implement it, I get the full <code>dict</code> interface, all of the extra methods being implemented in terms of the minimal interface.</p>

<p>Similarly, I would like to know what the minimal interface for file is that I have to implement in order to get the full interface. Is there a way to get <code>__enter__</code>, <code>__exit__</code>, <code>readline</code>, <code>readlines</code>, <code>__iter__</code> and <code>next</code> if I just implement <code>read</code>, <code>write</code> and <code>close</code>, or do I have to implement everything myself by hand each and every time I want the full <code>file</code> interface?</p>
