[Twisted-Python] Help using XmlStreamFactory & XmlStream : XPathQuery error?

Phil Mayers p.mayers at imperial.ac.uk
Thu Feb 21 06:31:40 EST 2008

>> One solution is to have a difference instance for each connection and 
>> to use
>> a bound method as the event handler.  This gives you an obvious 
>> per-instance
>> place to keep state and such - on the instance.  
> Jean-Paul, sorry for the dumb question, when you mean a different 
> instance, you mean a thread? What is a bound method? I'm fairly new to 
> python and very new to twisted (as you can probably tell).

A bound method is a function on a class instance. e.g.:

 >>> class A:
...   def func(self):
...     pass
 >>> aa = A()

 >>> A.func
<unbound method A.func>
 >>> aa.func
<bound method A.func of <__main__.A instance at 0x2aaaaab423b0>>

A.func is the unbound method - it's a function object, defined in the 
class, but the class is not instantiated so it's unbound.

aa.func is a bound version of A.func - it's bound to the instance "aa" 
and will fill in the "self" argument when called.

Think about it like this:

When you use 1 thread per connection, your "state" is usually stored as 
local variables inside a function i.e. on the stack.

When you use 1 thread for all connections, your "state" needs to be 
attached to the connection e.g. as instance variables of the protocol or 
an attached object.

So, you might do this:

from twisted.protocols import basic
from twisted.internet import protocol, reactor

class MyProto(basic.LineReceiver):
     def lineReceived(self, line):

     def connectionLost(self, reason):
         print "my data was", '\n'.join(self.data)

class MyFactory(protocol.ServerFactory):
     protocol = MyProto
     def buildProtocol(self, *pargs, **kwargs):
         p = protocol.ServerFactory.buildProtocol(self, *pargs, **kwargs)
         p.data = []
         return p

reactor.listenTCP(8000, MyFactory())

Relating to your other email - a similar technique works for more 
complex things e.g.

class MyProto(...)
  def dataReceived(self, data):

class MyFactory(...)
  def buildProtocol(...)
    p = ..
    p.parser = XmlParser()

More information about the Twisted-Python mailing list