How to protect Python source from modification
lycka at carmen.se
Wed Sep 14 14:48:00 CEST 2005
Frank Millman wrote:
> I have seen Twisted mentioned many times in this ng, but I have no idea
> what it actually does. Can someone tell me in simple terms what
> advantage it might give me over a multi-threaded socket server program.
More control. Less resource usage. Twisted also provides a very
flexible way of building network aware software which you will
appreciate if you ever consider using something else than sockets.
Using several process means using more memory, and inter process
communication isn't as fast as in-process communication. Using
threads is error prone and difficult to debug. There are also scaling
issues with threads in Python (but maybe not when most threads wait
for network connections).
Twisted is based on an event loop, just like GUI programs. But instead
of waiting for GUI events, such as button clicks, the Twisted app will
wait for network events, such as data received. With Twisted and
sockets, you write code that will implement handlers for such events.
A simple example is provided here:
# Copyright (c) 2001-2004 Twisted Matrix Laboratories.
# See LICENSE for details.
from twisted.internet.protocol import Protocol, Factory
from twisted.internet import reactor
### Protocol Implementation
# This is just about the simplest possible protocol
def dataReceived(self, data):
"""As soon as any data is received, write it back."""
f = Factory()
f.protocol = Echo
if __name__ == '__main__':
You see? You just subclass Protocol and override the relevant
event handler, and get the thing going! The factory will create
an Echo instance for each socket connection.
The problem in Twisted is that functions in this single thread that
are run inside the event loop must be fast--just as the event
handlers in your GUI app. Twisted helps you achieve this. For
instance, there is the concept of deferred execution, (described
in a paper available at http://python.fyxm.net/pycon/papers/deferex/ )
but you might want to use a separate thread for things like database
There are a lot of other batteries included, check out the Twisted
You have to ask other Twisted users about scalability, but I think
it will scale well beyond your needs.
More information about the Python-list