Name
stack
Synopsis
stack(context
=1)
Returns a list of six-item tuples. The first tuple is about
stack
’s caller, the second tuple
is about the caller’s caller, and so on. Each
tuple’s items, in order, are: frame object,
filename, line number, function name, list of
context
source code lines around the
current line, and index of current line within the list.
For example, suppose that at some point in your program you execute a statement such as:
x.f( )
and unexpectedly receive an AttributeError
informing you that object x
has no
attribute named f
. This means that object
x
is not as you expected, so you want to
determine more about x
as a preliminary to
ascertaining why x
is that way and what
you should do about it. Change the statement to:
try: x.f( ) except AttributeError: import sys, inspect sys.stderr.write('x is type %s,(%r)\n'%(type(x),x)) sys.stderr.write("x's methods are: ") for n, v in inspect.getmembers(x, callable): sys.stderr.write('%s '%n) sys.stderr.write('\n') raise
This example uses sys.stderr
(covered in Chapter 8), since it’s displaying
diagnostic information related to an error, not program results.
Function getmembers
of module
inspect
obtains the name of all methods available
on x
in order to display them. Of course,
if you need this kind of diagnostic functionality often, you should
package it up into a separate function, such as:
import sys, inspect def show_obj_methods(obj, name, show=sys.stderr.write): show('%s is type %s(%r)\n'%(name,obj,type(obj))) show("%s's methods ...
Get Python in a Nutshell now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.