Storing tracebacks

George Sakkis george.sakkis at gmail.com
Tue May 29 12:51:09 EDT 2007


On May 29, 9:46 am, kyoso... at gmail.com wrote:
> On May 28, 10:46 pm, George Sakkis <george.sak... at gmail.com> wrote:
>
>
>
> > I'm reading the docs on sys.exc_info() but I can't tell for sure
> > whether I'm using it safely to get a snapshot of an exception and
> > reraise it later. The use case is a class which acts like a deferred
> > callable, a callable that will be called at some point in the future
> > (possibly in a different thread) and whose result or raised exception
> > is to be stored as an attribute. This will be available by calling the
> > result() method, which returns the original result or reraises the
> > exception:
>
> > class JobRequest(object):
>
> >     def __init__(self, *args, **kwds):
> >         self.args = args
> >         self.kwds = kwds
> >         self._exc_info = None
>
> >     def __call__(self):
> >         raise NotImplementedError('Abstract method')
>
> >     def process(self):
> >         try:
> >             self._result = self(*self.args, **self.kwds)
> >         except:
> >             self._exc_info = sys.exc_info()
> >         else:
> >             self._exc_info = None
>
> >     def result(self):
> >         if self._exc_info is not None:
> >             type,exception,traceback = self._exc_info
> >             raise type,exception,traceback
> >         try: return self._result
> >         except AttributeError:
> >             raise UnprocessedRequestError()
>
> > class UnprocessedRequestError(RuntimeError):
> >     pass
>
> > So far it seems it works as expected but I'd like to know if this is
> > error-prone and why.
>
> > George
>
> I don't know enough about this method of getting tracebacks, but why
> wouldn't the traceback module work for you? It sounds like it uses the
> sys.exc_info() method you refer to.
>
> http://python.active-venture.com/lib/module-traceback.html

The traceback module is handy if you want a text representation of the
traceback, not the actual traceback. The reason I want to store the
actual traceback is to make the exception transparent to the user,
i.e. not be able to tell whether the exception was thrown in the
current stack frame or in another thread or even process.
Unfortunately tracebacks are not pickleable, otherwise I could just
pickle them in process() and unpickle them in result().

George




More information about the Python-list mailing list