try:
raise TypeError
except TypeError:
try:
tb = sys.exc_info()[2]
TracebackType = type(tb)
FrameType = type(tb.tb_frame)
except AttributeError:
# In the restricted environment, exc_info returns (None, None,
# None) Then, tb.tb_frame gives an attribute erro开发者_StackOverflowr
pass
tb = None; del tb
I can't understand this code at all. What is it's purpose?
It's a trick to get a traceback object and a frame object so that TracebackType and FrameType can be assigned their types. It simply raises an exception so it can catch the exception, then get the traceback and frame from sys.exc_info
.
The code tries to find out the types used for the tracebacks returned by sys.exc_info()
and assigned these types to the variables TracebackType
and FrameType
.
To do so it first needs to raise an exception and catch it (the TypeError
), so that sys.exc_info()
can return a traceback for this exception. Then this traceback gets inspected to determine the types. In the end the local tb
variable is deleted to not keep unnecessary circular references around (see the warning in the documentation of sys.exc_info()
).
It appears as though this code is used to get the call stack. If you research the exc_info function from http://pyref.infogami.com/sys.exc_info you'll find that the function returns a tuple of 3 values where the third is a Traceback object. This object contains the call stack information which is then displayed.
精彩评论