Strange effect with import

Hans Mulder hansmu at xs4all.nl
Fri Dec 21 01:54:35 CET 2012


On 20/12/12 23:52:24, Jens Thoms Toerring wrote:
> I'm writing a TCP server, based on SocketServer:
> 
>  server = SocketServer.TCPServer((192.168.1.10, 12345), ReqHandler)
> 
> where ReqHandler is the name of a class derived from
> SocketServer.BaseRequestHandler
> 
>  class ReqHandler(SocketServer.BaseRequestHandler):
>      ...
> 
> A new instance of this class is gernerated for each connection
> request to the server. In the call that creates the server I can
> only specify the name of the class but no arguments to be passed
> to it on instantiation - at least I found nothing in the docu-
> mentation.

What happens if instead of a class you pass a function that
takes the same arguments as the SocketServer.BaseRequestHandler
constructor and returns a new instance of your ReqHandler?

That's not quite what the documentaion clls for, but I'd hope
it's close enough.


Maybe something like this:

class ReqHandler(SocketServer.BaseRequestHandler):
    def __init__(self, request, client_address, server, ham, spam)
        super(SocketServer, self).__init__(
                            self, request, client_address, server)
        self.ham = ham
        self.spam = spam
        ....

And later:

import functools

server = SocketServer.TCPServer((192.168.1.10, 12345),
           functools.partial(ReqHandler, ham="hello", spam=42))

> On the other hand I need to get some information into
> this class and thus the only idea I came up with was to use some
> kind of global variable for the purpose. Perhaps there's a much
> better way to do that but I haven't found one yet. Or perhaps it
> is an omission in the design of SocketServer

I think you could call it a weakness in the design of SocketServer.

Life would be easier if it took as an optional third argument some
sequence that it would pass as extra arguments when it instantiates
the handler instance.  Then you wouldn't have to play with functools
(or closures, or global variables) to solve your problems.

> or (more likely) my mis-understanding of the documentation
> (as I wrote I'm relatively new to Python).

>From where I sit, it looks like the authors of the SocketServer
module didn't expect subclasses of BaseRequestHandler to need
extra attributes than their base class.

Or maybe they thought everybody knew functools.partial.


Hope this helps,

-- HansM




More information about the Python-list mailing list