OOP Pattern in Python

Andrew Bennetts andrew-pythonlist at puzzling.org
Thu May 22 00:19:17 EDT 2003


On Thu, May 22, 2003 at 11:16:30AM +0800, Simon Wittber (Maptek) wrote:
> I am writing a server program in Python.
> 
> I have a 'server' class designed to maintain a list of connections
> (Server). 
> I have a 'connection' class designed to maintain a single connection
> (Connection).
> 
> I sub class Connection to maintain a different type of Connection
> (ANSIConnection). I sub class Server to maintain a different set of
> connections (ANSIServer).
> The original Server class is passed the new Connection class as a
> parameter to its __init__ method, so it knows what sort of connections
> to maintain. See the below incomplete code snippets for more
> information.
> 
> Is this a good way of programming? Or am I digging myself into a hole or
> doing something silly? If this is actually an acceptable
> methodology/pattern, what would you call it?

This is similar to how Twisted works, although there are also significant
differences.

Twisted has a "reactor", which is essentially the event loop (i.e. the thing
that calls poll/select/etc).  For servers, you register Factories with the
reactor.  Factories build Protocols, which correspond to individual
connections.  You can change the Protocol a Factory will build by simple
assignment or by subclassing, i.e.:

    from twisted.internet.protocols import Factory
    
    f = Factory()
    f.protocol = ANSIProtocol

is effectively the same as:

    class ANSIFactory(Factory):
        protocol = ANSIProtocol
    
    f = ANSIFactory

If all you want to customise about your Factory is which Protocol it builds,
the first method is fine.  Sometimes you'll want to override methods like
stopFactory, startFactory and buildProtocol, so you'll want to subclass.  It
depends on what you're doing.

Twisted also seperates out the Transport from the Protocol, so that it is
trivial to reuse the same Protocol class with TCP, SSL, TLS and even named
pipes.  After all, as far as a Protocol is concerned, it's just a processor
of a byte-stream, and how those bytes arrive doesn't matter (but if a
Protocol does need to know more about the transport, such as the IP address
of the remote end, it can interrogate self.transport).

A good, practical overview of how you write servers in Twisted is here:
    http://twistedmatrix.com/documents/howto/servers

There's also a fair bit of example code here:
    http://twistedmatrix.com/documents/examples/

In particular, the simpleserv.py example is a simple echo server.

Regards,

-Andrew.






More information about the Python-list mailing list