[Twisted-Python] deferred as a Protocol class attribute, Protocol as class attribute of a Factory ...
Michael Tharp
gxti at partiallystapled.com
Wed Jun 16 16:14:28 MDT 2010
On 06/16/2010 12:50 PM, Jean Daniel wrote:
> Hello,
>
> Reading the SMTP client tutorial[1], I do not see the impact of the
> factory having a protocol defined as a class attribute. Especially
> when here is a big fat warning [2] that I should actually understand
> the inplications. My guess is that in this first case the protocol
> methods do not need access to the protocol instance, maybe it is a
> clear indication that the protocol is stateless, and there is a gain
> ressource-wise since there is no instance created and maintained. But
> I am not sure.
This isn't storing a protocol instance, just the protocol class. It then
instantiates that class in the buildProtocol() method. This is a common
pattern that lets you override settings easily by subclassing.
> Almost the same question: in the imapclient example [3], there is a
> LineReceiver subclass hooked to stdio. The lineReceived callback willl
> fire a callback added to an _class attribute_ deferred filled with a
> user function. I think this design prevents two instances of the
> LineReceiver subclass which would race on the class attribute
> deferred.
This is also not storing an instance in a class variable. It simply has
a 'default' value of None, which is overridden at the instance level in
SimpleIMAP4ClientFactory.buildProtocol().
Instance variables always override class variables. Additionally,
declaring a class variable has no effect on subsequent instance
assignments (unless it's an attribute descriptor, but twisted doesn't
use those). If all your initial instance values are immutable (like
None) you can forgo having an __init__ method at all and simply declare
them at the class level as was done here.
To answer your question in a hypothetical sense, no it would not make
sense to store either of those things in a class variable.
-- m. tharp
More information about the Twisted-Python
mailing list