views:

22

answers:

1

When should I use a twisted.python.failure.Failure, and when should I use something like twisted.internet.error.ConnectionDone? Or should I do twisted.python.failure.Failure(twisted.internet.error.ConnectionDone), and if so, in what casese should I do that?

+3  A: 

A Failure represents an exception and a traceback (often different from the current stack trace). You should use Failure when you are constructing an asynchronous exception. So, when you're going to fire a Deferred with an error, or when you're going to call a method like IProtocol.connectionLost or ClientFactory.clientConnectionFailed. This is because in such cases, you want the ability to associate a different stack trace with the exception than the current stack trace.

You shouldn't use Failure(ConnectionDone) because the correct one-argument invocation of Failure accepts an exception instance, not an exception class. So, instead, use Failure(ConnectionDone()). You can also use the zero-argument form to create a new Failure: Failure(). This only works when there is a "current" exception, eg in the suite of an except statement. It constructs the Failure using that current exception, as well as its traceback.

You can also construct a Failure with three-arguments, an exception class, instance, and traceback. This is most commonly done using the return value of sys.exc_info().

When you just want to raise an exception, you don't need to create a Failure. Just do what you'd normally do in a Python program to raise an exception: raise SomeException(...).

Jean-Paul Calderone