Subclassing socket

Steve Holden steve at holdenweb.com
Wed Dec 21 12:53:13 EST 2005


groups.20.thebriguy at spamgourmet.com wrote:
> socket objects have a little quirk.  If you try to receive 0 bytes on a
> blocking socket, they block.  That is, if I call recv(0), it blocks
> (until some data arrives).
> 
Well, arguably you should just try to stop receiving zero bytes. Why on 
earth is your application doing this?

> I think that's wrong, but I don't want to argue that.  I would like to
> create a subclass of socket that fixes the problem.  Ideally, something
> like:
> 
> class new_socket(socket):
>     def recv( self, bufsize, flags=0 ):
>         if bufsize == 0:
>             return ""
>         else:
>             return socket.recv( bufsize, flags )
> 
That would indeed work, were it not for the complications you are about 
to relate.

> They only problem is, sockets return socket objects via the accept
> call.  And the socket returned is of type socket, of course, not
> new_socket, as I would like.  I could override accept() to return a
> new_socket, but I don't know how to convert the old socket to a new
> socket.  That is, I'd like to add a method to the class above something
> like:
> 
>     def accept( self ):
>         conn, addr = socket.accept()
>         <convert conn, which is type socket to type new_socket>
>         return ( conn, addr )
> 
> Does anyone have any suggestions on how to do the above?
> 
You could use the "delegation" pattern - return an object that contains 
a reference to the socket returned by accept(), and have that object 
implement recv() as you outline above, and  __getattr__() so that any 
methods your socket *doesn't* implement are instead called on the socket 
returned by accept().

There's a whole page of stuff at
 
http://aspn.activestate.com/ASPN/search?query=delegation&x=0&y=0&type=ASPN

but the best read will probably be

   http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52295

In that article Alex talks about how old-style classes can't inherit 
from basic Python types. This is out of date now for most types, but his 
exposition of the principles of delegation remains a beacon of clarity.

regards
  Steve
-- 
Steve Holden       +44 150 684 7255  +1 800 494 3119
Holden Web LLC                     www.holdenweb.com
PyCon TX 2006                  www.python.org/pycon/




More information about the Python-list mailing list