Question

In the twisted docs, it says:

New application code should prefer to pass and accept the reactor as a parameter where it is needed, rather than relying on being able to import this module to get a reference. This simplifies unit testing and may make it easier to one day support multiple reactors (as a performance enhancement), though this is not currently possible.

What is the preferred way of doing this? In particular, what is the best way to pass it to a protocol? (Especially when the standard twisted.internet.protocol.Factory is all that's needed.)

Edit: To clarify, since the protocol is not instantiated directly, I am wondering if the method below is the preferred way, or if there is a better way of allowing access to the reactor in the protocol.

class MyFactory(protocol.Factory):
    def __init__(self, rct):
        self.reactor = rct

class MyProtocol(protocol.Protocol):
    def __init__(self):
        self.reactor = None

    def connectionMade(self):
        self.reactor = self.factory.reactor

if __name__=="__main__":
    from twisted.internet import reactor
    f = MyFactory(reactor)
    f.protocol = MyProtocol
    reactor.listenXXX(whatever)
    reactor.run()

It seems a little bit silly to make a factory class solely for the purpose of accessing the reactor, since wanting access to the reactor must be fairly common.

Was it helpful?

Solution

It seems a little bit silly to make a factory class solely for the purpose of accessing the reactor

A lot of programming tasks are "a little bit silly". The state of the art in programming is actually a lot silly in most areas, in my experience.

But if you're using a sufficiently new version of Twisted, then you can do what you want like this:

from twisted.internet.protocol import Factory

factory = Factory.forProtocol(YourProtocol, reactor)

If you're using an older version of Twisted without this API then you can do this instead:

from twisted.internet.protocol import ClientCreator

ClientCreator(reactor, YourProtocol, reactor).connectTCP(...)

But this is only for clients which isn't specifically what your question is about.

The idea of making the reactor attribute that most transports already have part of the guaranteed transport interface (which it is not currently part of) has been discussed by the Twisted development team from time to time. If you want a better answer to this question then you could try motivating some action on that front.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top