[Twisted-Python] callback conventions

Matthew R. Scott twisted at goldenspud.com
Tue Aug 5 17:01:00 MDT 2003


Where I work, we have been using a convention of specifying callbacks that do 
not need to be used outside of a certain scope, by defining functions within 
functions.  So far, it has helped us keep our code cleaner-looking and easier 
to browse and maintain.

Example snipped from working code:

class Daemon(pb.Referenceable):
    # ...
    def pingServer(self):
        def success(result):
            self.reactor.callLater(1, self.pingServer)
        def failure(reason):
            self.onDisconnect()
            self.connect()
        try:
            df = self.callRemote('ping')
        except:
            failure('Ping unsuccessful')
        else:
            df.addCallbacks(success, failure)
    # ...

What you would typically have to do the 'classic' way:

class Daemon(pb.Referenceable:
    # ...
    def cb_pingServerSuccess(self, result):
        self.reactor.callLater(1, self.pingServer)
    def cb_pingServerFailure(self, reason):
        self.onDisconnect()
        self.connect()
    def pingServer(self):
        try:
            df = self.callRemote('ping')
        except:
            self.cb_pingServerFailure('Ping unsuccessful')
        else:
            df.addCallbacks(cb_pingServerSuccess, 
                            cb_pingServerFailure)
    # ...

Others may already use this, but we speculated that the reason it is not in 
widespread use is because prior to python2.2 the scoping rules for 
functions-inside-functions made it more difficult to do this easily.

(I personally am not sure as Python 2.2 was the first Python version I've 
developed with)

Comments, questions, mild flames appreciated :) ... 

-- 
Matthew R. Scott
OMAjA / http://www.omaja.com/





More information about the Twisted-Python mailing list