blob: c4c15f51dd33c08df583eb074e9f164cc071c7eb [file] [log] [blame]
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001"""Get useful information from live Python objects.
2
3This module encapsulates the interface provided by the internal special
4attributes (func_*, co_*, im_*, tb_*, etc.) in a friendlier fashion.
5It also provides some help for examining source code and class layout.
6
7Here are some of the useful functions provided by this module:
8
9 ismodule(), isclass(), ismethod(), isfunction(), istraceback(),
10 isframe(), iscode(), isbuiltin(), isroutine() - check object types
11 getmembers() - get members of an object that satisfy a given condition
12
13 getfile(), getsourcefile(), getsource() - find an object's source code
14 getdoc(), getcomments() - get documentation on an object
15 getmodule() - determine the module that an object came from
16 getclasstree() - arrange classes so as to represent their hierarchy
17
18 getargspec(), getargvalues() - get info about function arguments
19 formatargspec(), formatargvalues() - format an argument spec
20 getouterframes(), getinnerframes() - get info about frames
21 currentframe() - get the current stack frame
22 stack(), trace() - get info about frames on the stack or in a traceback
23"""
24
25# This module is in the public domain. No warranties.
26
Ka-Ping Yee8b58b842001-03-01 13:56:16 +000027__author__ = 'Ka-Ping Yee <ping@lfw.org>'
28__date__ = '1 Jan 2001'
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +000029
Ka-Ping Yeea6e59712001-03-10 09:31:55 +000030import sys, os, types, string, re, dis, imp, tokenize
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +000031
32# ----------------------------------------------------------- type-checking
33def ismodule(object):
34 """Return true if the object is a module.
35
36 Module objects provide these attributes:
37 __doc__ documentation string
38 __file__ filename (missing for built-in modules)"""
Tim Peters28bc59f2001-09-16 08:40:16 +000039 return isinstance(object, types.ModuleType)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +000040
41def isclass(object):
42 """Return true if the object is a class.
43
44 Class objects provide these attributes:
45 __doc__ documentation string
46 __module__ name of module in which this class was defined"""
Tim Peters28bc59f2001-09-16 08:40:16 +000047 return isinstance(object, types.ClassType) or hasattr(object, '__bases__')
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +000048
49def ismethod(object):
50 """Return true if the object is an instance method.
51
52 Instance method objects provide these attributes:
53 __doc__ documentation string
54 __name__ name with which this method was defined
55 im_class class object in which this method belongs
56 im_func function object containing implementation of method
57 im_self instance to which this method is bound, or None"""
Tim Peters28bc59f2001-09-16 08:40:16 +000058 return isinstance(object, types.MethodType)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +000059
Tim Peters536d2262001-09-20 05:13:38 +000060def ismethoddescriptor(object):
61 """Return true if the object is a method descriptor, and ismethod false.
62
63 This is new in Python 2.2, and, for example, is true of int.__add__.
64 An object passing this test has a __get__ attribute but not a __set__
65 attribute, but beyond that the set of attributes varies. __name__ is
66 usually sensible, and __doc__ often is.
67
68 Methods implemented via descriptors that also pass the ismethod() test
69 return false from the ismethoddescriptor() test, simply because
70 ismethod() is more informative -- you can, e.g., count on having the
71 im_func attribute (etc) when an object passes the latter."""
72 return (hasattr(object, "__get__")
73 and not hasattr(object, "__set__") # else it's a data descriptor
74 and not ismethod(object) # mutual exclusion
75 and not isclass(object))
76
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +000077def isfunction(object):
78 """Return true if the object is a user-defined function.
79
80 Function objects provide these attributes:
81 __doc__ documentation string
82 __name__ name with which this function was defined
83 func_code code object containing compiled function bytecode
84 func_defaults tuple of any default values for arguments
85 func_doc (same as __doc__)
86 func_globals global namespace in which this function was defined
87 func_name (same as __name__)"""
Tim Peters28bc59f2001-09-16 08:40:16 +000088 return isinstance(object, types.FunctionType)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +000089
90def istraceback(object):
91 """Return true if the object is a traceback.
92
93 Traceback objects provide these attributes:
94 tb_frame frame object at this level
95 tb_lasti index of last attempted instruction in bytecode
96 tb_lineno current line number in Python source code
97 tb_next next inner traceback object (called by this level)"""
Tim Peters28bc59f2001-09-16 08:40:16 +000098 return isinstance(object, types.TracebackType)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +000099
100def isframe(object):
101 """Return true if the object is a frame object.
102
103 Frame objects provide these attributes:
104 f_back next outer frame object (this frame's caller)
105 f_builtins built-in namespace seen by this frame
106 f_code code object being executed in this frame
107 f_exc_traceback traceback if raised in this frame, or None
108 f_exc_type exception type if raised in this frame, or None
109 f_exc_value exception value if raised in this frame, or None
110 f_globals global namespace seen by this frame
111 f_lasti index of last attempted instruction in bytecode
112 f_lineno current line number in Python source code
113 f_locals local namespace seen by this frame
114 f_restricted 0 or 1 if frame is in restricted execution mode
115 f_trace tracing function for this frame, or None"""
Tim Peters28bc59f2001-09-16 08:40:16 +0000116 return isinstance(object, types.FrameType)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000117
118def iscode(object):
119 """Return true if the object is a code object.
120
121 Code objects provide these attributes:
122 co_argcount number of arguments (not including * or ** args)
123 co_code string of raw compiled bytecode
124 co_consts tuple of constants used in the bytecode
125 co_filename name of file in which this code object was created
126 co_firstlineno number of first line in Python source code
127 co_flags bitmap: 1=optimized | 2=newlocals | 4=*arg | 8=**arg
128 co_lnotab encoded mapping of line numbers to bytecode indices
129 co_name name with which this code object was defined
130 co_names tuple of names of local variables
131 co_nlocals number of local variables
132 co_stacksize virtual machine stack space required
133 co_varnames tuple of names of arguments and local variables"""
Tim Peters28bc59f2001-09-16 08:40:16 +0000134 return isinstance(object, types.CodeType)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000135
136def isbuiltin(object):
137 """Return true if the object is a built-in function or method.
138
139 Built-in functions and methods provide these attributes:
140 __doc__ documentation string
141 __name__ original name of this function or method
142 __self__ instance to which a method is bound, or None"""
Tim Peters28bc59f2001-09-16 08:40:16 +0000143 return isinstance(object, types.BuiltinFunctionType)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000144
145def isroutine(object):
146 """Return true if the object is any kind of function or method."""
Tim Peters536d2262001-09-20 05:13:38 +0000147 return (isbuiltin(object)
148 or isfunction(object)
149 or ismethod(object)
150 or ismethoddescriptor(object))
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000151
152def getmembers(object, predicate=None):
153 """Return all members of an object as (name, value) pairs sorted by name.
154 Optionally, only return members that satisfy a given predicate."""
155 results = []
156 for key in dir(object):
157 value = getattr(object, key)
158 if not predicate or predicate(value):
159 results.append((key, value))
160 results.sort()
161 return results
162
163# -------------------------------------------------- source code extraction
164def indentsize(line):
165 """Return the indent size, in spaces, at the start of a line of text."""
166 expline = string.expandtabs(line)
167 return len(expline) - len(string.lstrip(expline))
168
169def getdoc(object):
170 """Get the documentation string for an object.
171
172 All tabs are expanded to spaces. To clean up docstrings that are
173 indented to line up with blocks of code, any whitespace than can be
174 uniformly removed from the second line onwards is removed."""
175 if hasattr(object, '__doc__') and object.__doc__:
176 lines = string.split(string.expandtabs(object.__doc__), '\n')
177 margin = None
178 for line in lines[1:]:
179 content = len(string.lstrip(line))
180 if not content: continue
181 indent = len(line) - content
182 if margin is None: margin = indent
183 else: margin = min(margin, indent)
184 if margin is not None:
185 for i in range(1, len(lines)): lines[i] = lines[i][margin:]
186 return string.join(lines, '\n')
187
188def getfile(object):
Ka-Ping Yeec113c242001-03-02 02:08:53 +0000189 """Work out which source or compiled file an object was defined in."""
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000190 if ismodule(object):
191 if hasattr(object, '__file__'):
192 return object.__file__
193 raise TypeError, 'arg is a built-in module'
194 if isclass(object):
Ka-Ping Yeec99e0f12001-04-13 12:10:40 +0000195 object = sys.modules.get(object.__module__)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000196 if hasattr(object, '__file__'):
197 return object.__file__
198 raise TypeError, 'arg is a built-in class'
199 if ismethod(object):
200 object = object.im_func
201 if isfunction(object):
202 object = object.func_code
203 if istraceback(object):
204 object = object.tb_frame
205 if isframe(object):
206 object = object.f_code
207 if iscode(object):
208 return object.co_filename
209 raise TypeError, 'arg is not a module, class, method, ' \
210 'function, traceback, frame, or code object'
211
Ka-Ping Yee4d6fc7f2001-04-10 11:43:00 +0000212def getmoduleinfo(path):
213 """Get the module name, suffix, mode, and module type for a given file."""
214 filename = os.path.basename(path)
215 suffixes = map(lambda (suffix, mode, mtype):
216 (-len(suffix), suffix, mode, mtype), imp.get_suffixes())
217 suffixes.sort() # try longest suffixes first, in case they overlap
218 for neglen, suffix, mode, mtype in suffixes:
219 if filename[neglen:] == suffix:
220 return filename[:neglen], suffix, mode, mtype
221
222def getmodulename(path):
223 """Return the module name for a given file, or None."""
224 info = getmoduleinfo(path)
225 if info: return info[0]
226
Ka-Ping Yeec113c242001-03-02 02:08:53 +0000227def getsourcefile(object):
228 """Return the Python source file an object was defined in, if it exists."""
229 filename = getfile(object)
230 if string.lower(filename[-4:]) in ['.pyc', '.pyo']:
231 filename = filename[:-4] + '.py'
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000232 for suffix, mode, kind in imp.get_suffixes():
233 if 'b' in mode and string.lower(filename[-len(suffix):]) == suffix:
234 # Looks like a binary file. We want to only return a text file.
235 return None
236 if os.path.exists(filename):
Ka-Ping Yeec113c242001-03-02 02:08:53 +0000237 return filename
238
239def getabsfile(object):
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000240 """Return an absolute path to the source or compiled file for an object.
Ka-Ping Yeec113c242001-03-02 02:08:53 +0000241
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000242 The idea is for each object to have a unique origin, so this routine
243 normalizes the result as much as possible."""
244 return os.path.normcase(
245 os.path.abspath(getsourcefile(object) or getfile(object)))
Ka-Ping Yeec113c242001-03-02 02:08:53 +0000246
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000247modulesbyfile = {}
248
249def getmodule(object):
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000250 """Return the module an object was defined in, or None if not found."""
Ka-Ping Yee202c99b2001-04-13 09:15:08 +0000251 if ismodule(object):
252 return object
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000253 if isclass(object):
Ka-Ping Yee8b58b842001-03-01 13:56:16 +0000254 return sys.modules.get(object.__module__)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000255 try:
Ka-Ping Yeec113c242001-03-02 02:08:53 +0000256 file = getabsfile(object)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000257 except TypeError:
258 return None
259 if modulesbyfile.has_key(file):
260 return sys.modules[modulesbyfile[file]]
261 for module in sys.modules.values():
262 if hasattr(module, '__file__'):
Ka-Ping Yeec113c242001-03-02 02:08:53 +0000263 modulesbyfile[getabsfile(module)] = module.__name__
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000264 if modulesbyfile.has_key(file):
265 return sys.modules[modulesbyfile[file]]
266 main = sys.modules['__main__']
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000267 if hasattr(main, object.__name__):
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000268 mainobject = getattr(main, object.__name__)
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000269 if mainobject is object:
270 return main
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000271 builtin = sys.modules['__builtin__']
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000272 if hasattr(builtin, object.__name__):
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000273 builtinobject = getattr(builtin, object.__name__)
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000274 if builtinobject is object:
275 return builtin
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000276
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000277def findsource(object):
278 """Return the entire source file and starting line number for an object.
279
280 The argument may be a module, class, method, function, traceback, frame,
281 or code object. The source code is returned as a list of all the lines
282 in the file and the line number indexes a line in that list. An IOError
283 is raised if the source code cannot be retrieved."""
284 try:
285 file = open(getsourcefile(object))
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000286 except (TypeError, IOError):
287 raise IOError, 'could not get source code'
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000288 lines = file.readlines()
289 file.close()
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000290
291 if ismodule(object):
292 return lines, 0
293
294 if isclass(object):
295 name = object.__name__
Ka-Ping Yeea6e59712001-03-10 09:31:55 +0000296 pat = re.compile(r'^\s*class\s*' + name + r'\b')
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000297 for i in range(len(lines)):
Ka-Ping Yeea6e59712001-03-10 09:31:55 +0000298 if pat.match(lines[i]): return lines, i
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000299 else: raise IOError, 'could not find class definition'
300
301 if ismethod(object):
302 object = object.im_func
303 if isfunction(object):
304 object = object.func_code
305 if istraceback(object):
306 object = object.tb_frame
307 if isframe(object):
308 object = object.f_code
309 if iscode(object):
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000310 if not hasattr(object, 'co_firstlineno'):
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000311 raise IOError, 'could not find function definition'
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000312 lnum = object.co_firstlineno - 1
Ka-Ping Yeea6e59712001-03-10 09:31:55 +0000313 pat = re.compile(r'^\s*def\s')
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000314 while lnum > 0:
Ka-Ping Yeea6e59712001-03-10 09:31:55 +0000315 if pat.match(lines[lnum]): break
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000316 lnum = lnum - 1
317 return lines, lnum
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000318
319def getcomments(object):
320 """Get lines of comments immediately preceding an object's source code."""
321 try: lines, lnum = findsource(object)
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000322 except IOError: return None
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000323
324 if ismodule(object):
325 # Look for a comment block at the top of the file.
326 start = 0
Ka-Ping Yeeb910efe2001-04-12 13:17:17 +0000327 if lines and lines[0][:2] == '#!': start = 1
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000328 while start < len(lines) and string.strip(lines[start]) in ['', '#']:
329 start = start + 1
Ka-Ping Yeeb910efe2001-04-12 13:17:17 +0000330 if start < len(lines) and lines[start][:1] == '#':
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000331 comments = []
332 end = start
333 while end < len(lines) and lines[end][:1] == '#':
334 comments.append(string.expandtabs(lines[end]))
335 end = end + 1
336 return string.join(comments, '')
337
338 # Look for a preceding block of comments at the same indentation.
339 elif lnum > 0:
340 indent = indentsize(lines[lnum])
341 end = lnum - 1
342 if end >= 0 and string.lstrip(lines[end])[:1] == '#' and \
343 indentsize(lines[end]) == indent:
344 comments = [string.lstrip(string.expandtabs(lines[end]))]
345 if end > 0:
346 end = end - 1
347 comment = string.lstrip(string.expandtabs(lines[end]))
348 while comment[:1] == '#' and indentsize(lines[end]) == indent:
349 comments[:0] = [comment]
350 end = end - 1
351 if end < 0: break
352 comment = string.lstrip(string.expandtabs(lines[end]))
353 while comments and string.strip(comments[0]) == '#':
354 comments[:1] = []
355 while comments and string.strip(comments[-1]) == '#':
356 comments[-1:] = []
357 return string.join(comments, '')
358
359class ListReader:
360 """Provide a readline() method to return lines from a list of strings."""
361 def __init__(self, lines):
362 self.lines = lines
363 self.index = 0
364
365 def readline(self):
366 i = self.index
367 if i < len(self.lines):
368 self.index = i + 1
369 return self.lines[i]
370 else: return ''
371
Tim Peters4efb6e92001-06-29 23:51:08 +0000372class EndOfBlock(Exception): pass
373
374class BlockFinder:
375 """Provide a tokeneater() method to detect the end of a code block."""
376 def __init__(self):
377 self.indent = 0
378 self.started = 0
379 self.last = 0
380
381 def tokeneater(self, type, token, (srow, scol), (erow, ecol), line):
382 if not self.started:
383 if type == tokenize.NAME: self.started = 1
384 elif type == tokenize.NEWLINE:
385 self.last = srow
386 elif type == tokenize.INDENT:
387 self.indent = self.indent + 1
388 elif type == tokenize.DEDENT:
389 self.indent = self.indent - 1
390 if self.indent == 0: raise EndOfBlock, self.last
391
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000392def getblock(lines):
393 """Extract the block of code at the top of the given list of lines."""
Tim Peters4efb6e92001-06-29 23:51:08 +0000394 try:
395 tokenize.tokenize(ListReader(lines).readline, BlockFinder().tokeneater)
396 except EndOfBlock, eob:
397 return lines[:eob.args[0]]
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000398
399def getsourcelines(object):
400 """Return a list of source lines and starting line number for an object.
401
402 The argument may be a module, class, method, function, traceback, frame,
403 or code object. The source code is returned as a list of the lines
404 corresponding to the object and the line number indicates where in the
405 original source file the first line of code was found. An IOError is
406 raised if the source code cannot be retrieved."""
407 lines, lnum = findsource(object)
408
409 if ismodule(object): return lines, 0
410 else: return getblock(lines[lnum:]), lnum + 1
411
412def getsource(object):
413 """Return the text of the source code for an object.
414
415 The argument may be a module, class, method, function, traceback, frame,
416 or code object. The source code is returned as a single string. An
417 IOError is raised if the source code cannot be retrieved."""
418 lines, lnum = getsourcelines(object)
419 return string.join(lines, '')
420
421# --------------------------------------------------- class tree extraction
422def walktree(classes, children, parent):
423 """Recursive helper function for getclasstree()."""
424 results = []
425 classes.sort(lambda a, b: cmp(a.__name__, b.__name__))
426 for c in classes:
427 results.append((c, c.__bases__))
428 if children.has_key(c):
429 results.append(walktree(children[c], children, c))
430 return results
431
432def getclasstree(classes, unique=0):
433 """Arrange the given list of classes into a hierarchy of nested lists.
434
435 Where a nested list appears, it contains classes derived from the class
436 whose entry immediately precedes the list. Each entry is a 2-tuple
437 containing a class and a tuple of its base classes. If the 'unique'
438 argument is true, exactly one entry appears in the returned structure
439 for each class in the given list. Otherwise, classes using multiple
440 inheritance and their descendants will appear multiple times."""
441 children = {}
442 roots = []
443 for c in classes:
444 if c.__bases__:
445 for parent in c.__bases__:
446 if not children.has_key(parent):
447 children[parent] = []
448 children[parent].append(c)
449 if unique and parent in classes: break
450 elif c not in roots:
451 roots.append(c)
452 for parent in children.keys():
453 if parent not in classes:
454 roots.append(parent)
455 return walktree(roots, children, None)
456
457# ------------------------------------------------ argument list extraction
458# These constants are from Python's compile.h.
459CO_OPTIMIZED, CO_NEWLOCALS, CO_VARARGS, CO_VARKEYWORDS = 1, 2, 4, 8
460
461def getargs(co):
462 """Get information about the arguments accepted by a code object.
463
464 Three things are returned: (args, varargs, varkw), where 'args' is
465 a list of argument names (possibly containing nested lists), and
466 'varargs' and 'varkw' are the names of the * and ** arguments or None."""
467 if not iscode(co): raise TypeError, 'arg is not a code object'
468
469 code = co.co_code
470 nargs = co.co_argcount
471 names = co.co_varnames
472 args = list(names[:nargs])
473 step = 0
474
475 # The following acrobatics are for anonymous (tuple) arguments.
476 for i in range(nargs):
477 if args[i][:1] in ['', '.']:
478 stack, remain, count = [], [], []
479 while step < len(code):
480 op = ord(code[step])
481 step = step + 1
482 if op >= dis.HAVE_ARGUMENT:
483 opname = dis.opname[op]
484 value = ord(code[step]) + ord(code[step+1])*256
485 step = step + 2
486 if opname in ['UNPACK_TUPLE', 'UNPACK_SEQUENCE']:
487 remain.append(value)
488 count.append(value)
489 elif opname == 'STORE_FAST':
490 stack.append(names[value])
491 remain[-1] = remain[-1] - 1
492 while remain[-1] == 0:
493 remain.pop()
494 size = count.pop()
495 stack[-size:] = [stack[-size:]]
496 if not remain: break
497 remain[-1] = remain[-1] - 1
498 if not remain: break
499 args[i] = stack[0]
500
501 varargs = None
502 if co.co_flags & CO_VARARGS:
503 varargs = co.co_varnames[nargs]
504 nargs = nargs + 1
505 varkw = None
506 if co.co_flags & CO_VARKEYWORDS:
507 varkw = co.co_varnames[nargs]
508 return args, varargs, varkw
509
510def getargspec(func):
511 """Get the names and default values of a function's arguments.
512
513 A tuple of four things is returned: (args, varargs, varkw, defaults).
514 'args' is a list of the argument names (it may contain nested lists).
515 'varargs' and 'varkw' are the names of the * and ** arguments or None.
516 'defaults' is an n-tuple of the default values of the last n arguments."""
517 if not isfunction(func): raise TypeError, 'arg is not a Python function'
518 args, varargs, varkw = getargs(func.func_code)
519 return args, varargs, varkw, func.func_defaults
520
521def getargvalues(frame):
522 """Get information about arguments passed into a particular frame.
523
524 A tuple of four things is returned: (args, varargs, varkw, locals).
525 'args' is a list of the argument names (it may contain nested lists).
526 'varargs' and 'varkw' are the names of the * and ** arguments or None.
527 'locals' is the locals dictionary of the given frame."""
528 args, varargs, varkw = getargs(frame.f_code)
529 return args, varargs, varkw, frame.f_locals
530
531def joinseq(seq):
532 if len(seq) == 1:
533 return '(' + seq[0] + ',)'
534 else:
535 return '(' + string.join(seq, ', ') + ')'
536
537def strseq(object, convert, join=joinseq):
538 """Recursively walk a sequence, stringifying each element."""
539 if type(object) in [types.ListType, types.TupleType]:
540 return join(map(lambda o, c=convert, j=join: strseq(o, c, j), object))
541 else:
542 return convert(object)
543
544def formatargspec(args, varargs=None, varkw=None, defaults=None,
545 formatarg=str,
546 formatvarargs=lambda name: '*' + name,
547 formatvarkw=lambda name: '**' + name,
548 formatvalue=lambda value: '=' + repr(value),
549 join=joinseq):
550 """Format an argument spec from the 4 values returned by getargspec.
551
552 The first four arguments are (args, varargs, varkw, defaults). The
553 other four arguments are the corresponding optional formatting functions
554 that are called to turn names and values into strings. The ninth
555 argument is an optional function to format the sequence of arguments."""
556 specs = []
557 if defaults:
558 firstdefault = len(args) - len(defaults)
559 for i in range(len(args)):
560 spec = strseq(args[i], formatarg, join)
561 if defaults and i >= firstdefault:
562 spec = spec + formatvalue(defaults[i - firstdefault])
563 specs.append(spec)
564 if varargs:
565 specs.append(formatvarargs(varargs))
566 if varkw:
567 specs.append(formatvarkw(varkw))
568 return '(' + string.join(specs, ', ') + ')'
569
570def formatargvalues(args, varargs, varkw, locals,
571 formatarg=str,
572 formatvarargs=lambda name: '*' + name,
573 formatvarkw=lambda name: '**' + name,
574 formatvalue=lambda value: '=' + repr(value),
575 join=joinseq):
576 """Format an argument spec from the 4 values returned by getargvalues.
577
578 The first four arguments are (args, varargs, varkw, locals). The
579 next four arguments are the corresponding optional formatting functions
580 that are called to turn names and values into strings. The ninth
581 argument is an optional function to format the sequence of arguments."""
582 def convert(name, locals=locals,
583 formatarg=formatarg, formatvalue=formatvalue):
584 return formatarg(name) + formatvalue(locals[name])
585 specs = []
586 for i in range(len(args)):
587 specs.append(strseq(args[i], convert, join))
588 if varargs:
589 specs.append(formatvarargs(varargs) + formatvalue(locals[varargs]))
590 if varkw:
591 specs.append(formatvarkw(varkw) + formatvalue(locals[varkw]))
592 return '(' + string.join(specs, ', ') + ')'
593
594# -------------------------------------------------- stack frame extraction
595def getframeinfo(frame, context=1):
596 """Get information about a frame or traceback object.
597
598 A tuple of five things is returned: the filename, the line number of
599 the current line, the function name, a list of lines of context from
600 the source code, and the index of the current line within that list.
601 The optional second argument specifies the number of lines of context
602 to return, which are centered around the current line."""
603 if istraceback(frame):
604 frame = frame.tb_frame
605 if not isframe(frame):
606 raise TypeError, 'arg is not a frame or traceback object'
607
608 filename = getsourcefile(frame)
Ka-Ping Yee59ade082001-03-01 03:55:35 +0000609 lineno = getlineno(frame)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000610 if context > 0:
Guido van Rossum54e54c62001-09-04 19:14:14 +0000611 start = lineno - 1 - context//2
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000612 try:
613 lines, lnum = findsource(frame)
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000614 except IOError:
615 lines = index = None
616 else:
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000617 start = max(start, 1)
618 start = min(start, len(lines) - context)
619 lines = lines[start:start+context]
Ka-Ping Yee59ade082001-03-01 03:55:35 +0000620 index = lineno - 1 - start
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000621 else:
622 lines = index = None
623
Ka-Ping Yee59ade082001-03-01 03:55:35 +0000624 return (filename, lineno, frame.f_code.co_name, lines, index)
625
626def getlineno(frame):
627 """Get the line number from a frame object, allowing for optimization."""
628 # Written by Marc-André Lemburg; revised by Jim Hugunin and Fredrik Lundh.
629 lineno = frame.f_lineno
630 code = frame.f_code
631 if hasattr(code, 'co_lnotab'):
632 table = code.co_lnotab
633 lineno = code.co_firstlineno
634 addr = 0
635 for i in range(0, len(table), 2):
636 addr = addr + ord(table[i])
637 if addr > frame.f_lasti: break
638 lineno = lineno + ord(table[i+1])
639 return lineno
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000640
641def getouterframes(frame, context=1):
642 """Get a list of records for a frame and all higher (calling) frames.
643
644 Each record contains a frame object, filename, line number, function
645 name, a list of lines of context, and index within the context."""
646 framelist = []
647 while frame:
648 framelist.append((frame,) + getframeinfo(frame, context))
649 frame = frame.f_back
650 return framelist
651
652def getinnerframes(tb, context=1):
653 """Get a list of records for a traceback's frame and all lower frames.
654
655 Each record contains a frame object, filename, line number, function
656 name, a list of lines of context, and index within the context."""
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000657 framelist = []
658 while tb:
659 framelist.append((tb.tb_frame,) + getframeinfo(tb, context))
660 tb = tb.tb_next
661 return framelist
662
663def currentframe():
664 """Return the frame object for the caller's stack frame."""
665 try:
666 raise 'catch me'
667 except:
668 return sys.exc_traceback.tb_frame.f_back
669
670if hasattr(sys, '_getframe'): currentframe = sys._getframe
671
672def stack(context=1):
673 """Return a list of records for the stack above the caller's frame."""
674 return getouterframes(currentframe().f_back, context)
675
676def trace(context=1):
Tim Peters85ba6732001-02-28 08:26:44 +0000677 """Return a list of records for the stack below the current exception."""
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000678 return getinnerframes(sys.exc_traceback, context)