new command for getting traceback?

Tim Peters tim.one at home.com
Sun Feb 4 17:45:50 EST 2001


[Pete Shinners]
> one trick in python i've always thought was bizarre was getting
> the current stack trace by raising a false exception.
>
>         import sys
>         try:
>             raise None
>         except:
>             return sys.exc_info()[2].tb_frame
>
> obviously grabbing the current stack is usually a sign of some
> sort of "magic ahead", this is one of those things that is a
> bit obscure. even harder from inside my C extension modules. It
> would make things a bit nicer and more understandable if there
> was some sort of traceback() builtin. (accessable from C too!)

The details of frame manipulation are internal, and not guaranteed to work
the same way across releases.  So it's *good* that deep magic looks like
deep magic -- you're playing with fire.

Nevertheless,

Python 2.1a2 (#10, Feb  3 2001, 22:01:45) [MSC 32 bit (Intel)] on win32
Type "copyright", "credits" or "license" for more information.
>>> import sys
>>> print sys._getframe.__doc__
_getframe([depth]) -> frameobject

Return a frame object from the call stack.  If optional integer depth is
given, return the frame object that many calls below the top of the stack.
If that is deeper than the call stack, ValueError is raised.  The default
for depth is zero, returning the frame at the top of the call stack.

This function should be used for internal and specialized
purposes only.
>>>

That's new for 2.1, and can replace current uses of the try/except trick, if
you're willing to live with that frame interals are subject to change
without notice.  Note that there have long been traceback-manipulating
functions in the std traceback module, if you want to work at a more
abstract (and safer) level.

If you want more than that, you'll have to talk someone into submitting a
patch and making a case for it.





More information about the Python-list mailing list