[Python-Dev] Iterable sockets?

Alex Martelli aleax@aleax.it
Fri, 14 Mar 2003 08:44:12 +0100


On Friday 14 March 2003 02:47 am, Andrew McNamara wrote:
> Line oriented network protocols are very common, and I often find myself
> calling the socket makefile method so I can read complete lines from a
> socket. I'm probably not the first one who's wished that socket objects
> where more file-like.
>
> While I don't think we'd want to go as far as to turn them into a stdio
> based file object, it might make sense to allow them to be iterated over
> (and add a .readline() method, I guess). This would necessitate adding some
> input buffering, which will complicate things like the .recv() method, so
> I'm not sure it's that good an idea, but it removes one gotchya for
> neophytes (and forgetful veterans). Thoughts?

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 __init__(self, sock, *args):

        self.sock = socket.socket(*args)
        self.file = None


    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)


This has some issues (e.g. method close goes to self.sock when it
should probably go to self.file if not None; plus, the buffering issues
you mention, etc), but nothing that looks too hard to fix -- in my use
case I applied AGNI and never needed any more than this simple
and smooth "double alternate delegation" pattern.  Today, if type
socket supports inheritance (haven't checked), it should be even 
easier, I suspect.


Alex