pythonhttphttpserverbasehttprequesthandler

Does Python HttpServer instantiate a new request handler for every request


I'm creating a server like this:

server = HTTPServer(('', PORT_NUMBER), MyHandler)

...and then the handler:

class MyHandler(BaseHTTPRequestHandler):
    x = 0
    some_object = SomeClass()

    def do_GET(self):
        print self.x
        self.x += 1
        # etc. but x is not used further

class SomeClass:
    def __init__(self):
        print "Initialising SomeClass"

Now, everytime I make a get request, the value printed for self.x is always 0. However, the SomeClass constructor is only called once, when the server is first fired up (I'm assuming this is the case because the print message in the constructor is only called once).

The fact that self.x keeps resetting for every request suggests that the handler class is recreated new for each request, but the fact that the SomeClass message only prints once contradicts this.

Can someone tell me what's going on here?


Solution

  • It doesn't contradict anything. Because you're calling SomeClass() in the class definition (rather than __init__), it's called when the class is defined, not when it is instantiated.

    What happens when self.x += 1 is called, is that the value of self.x is read from the class level, but then the assignment is made on the instance level, so a new x is created that is specific to the instance.

    You could try changing it from self.x to MyHandler.x and see what happens.