[Python-Dev] Iterable sockets?

Oren Tirosh oren-py-d at hishome.net
Fri Mar 14 03:34:27 EST 2003


On Fri, Mar 14, 2003 at 08:44:12AM +0100, Alex Martelli wrote:
> I've had occasion to code a "socket that turns into a filelike object at
> need" (back in Python 2.0, I believe) and I used something like (can't
> find the original code, but AFAIR it was a bit like the following):
> 
> class richsocket:
...
>     def __getattr__(self, name):
> 
>         try: result = getattr(self.sock, name)
>         except AttributeError: pass
>         else: return result
> 
>         if self.file is None: self.file = self.sock.makefile()
>         return getattr(self.file, name)

When the first line-oriented method is accessed on the socket is grows 
a file object. After this point you should not use recv because it will 
ignore the data already buffered by the *FILE.

This is somewhat similar to the readahead buffering file objects have 
in 2.3: when iternext is first used it gets a buffer and uses it. After
using the iterator interface the other methods should not be used 
without a seek operation that clears the readahead buffer (same 
limitation of the old xreadlines object).

    Oren





More information about the Python-list mailing list