blob: 1102c3b2580909cbd078a859287b475dbdecf773 [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):
Tim Petersf1d90b92001-09-20 05:47:55 +000061 """Return true if the object is a method descriptor.
62
63 But not if ismethod() or isclass() or isfunction() are true.
Tim Peters536d2262001-09-20 05:13:38 +000064
65 This is new in Python 2.2, and, for example, is true of int.__add__.
66 An object passing this test has a __get__ attribute but not a __set__
67 attribute, but beyond that the set of attributes varies. __name__ is
68 usually sensible, and __doc__ often is.
69
Tim Petersf1d90b92001-09-20 05:47:55 +000070 Methods implemented via descriptors that also pass one of the other
71 tests return false from the ismethoddescriptor() test, simply because
72 the other tests promise more -- you can, e.g., count on having the
73 im_func attribute (etc) when an object passes ismethod()."""
Tim Peters536d2262001-09-20 05:13:38 +000074 return (hasattr(object, "__get__")
75 and not hasattr(object, "__set__") # else it's a data descriptor
76 and not ismethod(object) # mutual exclusion
Tim Petersf1d90b92001-09-20 05:47:55 +000077 and not isfunction(object)
Tim Peters536d2262001-09-20 05:13:38 +000078 and not isclass(object))
79
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +000080def isfunction(object):
81 """Return true if the object is a user-defined function.
82
83 Function objects provide these attributes:
84 __doc__ documentation string
85 __name__ name with which this function was defined
86 func_code code object containing compiled function bytecode
87 func_defaults tuple of any default values for arguments
88 func_doc (same as __doc__)
89 func_globals global namespace in which this function was defined
90 func_name (same as __name__)"""
Tim Peters28bc59f2001-09-16 08:40:16 +000091 return isinstance(object, types.FunctionType)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +000092
93def istraceback(object):
94 """Return true if the object is a traceback.
95
96 Traceback objects provide these attributes:
97 tb_frame frame object at this level
98 tb_lasti index of last attempted instruction in bytecode
99 tb_lineno current line number in Python source code
100 tb_next next inner traceback object (called by this level)"""
Tim Peters28bc59f2001-09-16 08:40:16 +0000101 return isinstance(object, types.TracebackType)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000102
103def isframe(object):
104 """Return true if the object is a frame object.
105
106 Frame objects provide these attributes:
107 f_back next outer frame object (this frame's caller)
108 f_builtins built-in namespace seen by this frame
109 f_code code object being executed in this frame
110 f_exc_traceback traceback if raised in this frame, or None
111 f_exc_type exception type if raised in this frame, or None
112 f_exc_value exception value if raised in this frame, or None
113 f_globals global namespace seen by this frame
114 f_lasti index of last attempted instruction in bytecode
115 f_lineno current line number in Python source code
116 f_locals local namespace seen by this frame
117 f_restricted 0 or 1 if frame is in restricted execution mode
118 f_trace tracing function for this frame, or None"""
Tim Peters28bc59f2001-09-16 08:40:16 +0000119 return isinstance(object, types.FrameType)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000120
121def iscode(object):
122 """Return true if the object is a code object.
123
124 Code objects provide these attributes:
125 co_argcount number of arguments (not including * or ** args)
126 co_code string of raw compiled bytecode
127 co_consts tuple of constants used in the bytecode
128 co_filename name of file in which this code object was created
129 co_firstlineno number of first line in Python source code
130 co_flags bitmap: 1=optimized | 2=newlocals | 4=*arg | 8=**arg
131 co_lnotab encoded mapping of line numbers to bytecode indices
132 co_name name with which this code object was defined
133 co_names tuple of names of local variables
134 co_nlocals number of local variables
135 co_stacksize virtual machine stack space required
136 co_varnames tuple of names of arguments and local variables"""
Tim Peters28bc59f2001-09-16 08:40:16 +0000137 return isinstance(object, types.CodeType)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000138
139def isbuiltin(object):
140 """Return true if the object is a built-in function or method.
141
142 Built-in functions and methods provide these attributes:
143 __doc__ documentation string
144 __name__ original name of this function or method
145 __self__ instance to which a method is bound, or None"""
Tim Peters28bc59f2001-09-16 08:40:16 +0000146 return isinstance(object, types.BuiltinFunctionType)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000147
148def isroutine(object):
149 """Return true if the object is any kind of function or method."""
Tim Peters536d2262001-09-20 05:13:38 +0000150 return (isbuiltin(object)
151 or isfunction(object)
152 or ismethod(object)
153 or ismethoddescriptor(object))
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000154
155def getmembers(object, predicate=None):
156 """Return all members of an object as (name, value) pairs sorted by name.
157 Optionally, only return members that satisfy a given predicate."""
158 results = []
159 for key in dir(object):
160 value = getattr(object, key)
161 if not predicate or predicate(value):
162 results.append((key, value))
163 results.sort()
164 return results
165
166# -------------------------------------------------- source code extraction
167def indentsize(line):
168 """Return the indent size, in spaces, at the start of a line of text."""
169 expline = string.expandtabs(line)
170 return len(expline) - len(string.lstrip(expline))
171
172def getdoc(object):
173 """Get the documentation string for an object.
174
175 All tabs are expanded to spaces. To clean up docstrings that are
176 indented to line up with blocks of code, any whitespace than can be
177 uniformly removed from the second line onwards is removed."""
178 if hasattr(object, '__doc__') and object.__doc__:
179 lines = string.split(string.expandtabs(object.__doc__), '\n')
180 margin = None
181 for line in lines[1:]:
182 content = len(string.lstrip(line))
183 if not content: continue
184 indent = len(line) - content
185 if margin is None: margin = indent
186 else: margin = min(margin, indent)
187 if margin is not None:
188 for i in range(1, len(lines)): lines[i] = lines[i][margin:]
189 return string.join(lines, '\n')
190
191def getfile(object):
Ka-Ping Yeec113c242001-03-02 02:08:53 +0000192 """Work out which source or compiled file an object was defined in."""
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000193 if ismodule(object):
194 if hasattr(object, '__file__'):
195 return object.__file__
196 raise TypeError, 'arg is a built-in module'
197 if isclass(object):
Ka-Ping Yeec99e0f12001-04-13 12:10:40 +0000198 object = sys.modules.get(object.__module__)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000199 if hasattr(object, '__file__'):
200 return object.__file__
201 raise TypeError, 'arg is a built-in class'
202 if ismethod(object):
203 object = object.im_func
204 if isfunction(object):
205 object = object.func_code
206 if istraceback(object):
207 object = object.tb_frame
208 if isframe(object):
209 object = object.f_code
210 if iscode(object):
211 return object.co_filename
212 raise TypeError, 'arg is not a module, class, method, ' \
213 'function, traceback, frame, or code object'
214
Ka-Ping Yee4d6fc7f2001-04-10 11:43:00 +0000215def getmoduleinfo(path):
216 """Get the module name, suffix, mode, and module type for a given file."""
217 filename = os.path.basename(path)
218 suffixes = map(lambda (suffix, mode, mtype):
219 (-len(suffix), suffix, mode, mtype), imp.get_suffixes())
220 suffixes.sort() # try longest suffixes first, in case they overlap
221 for neglen, suffix, mode, mtype in suffixes:
222 if filename[neglen:] == suffix:
223 return filename[:neglen], suffix, mode, mtype
224
225def getmodulename(path):
226 """Return the module name for a given file, or None."""
227 info = getmoduleinfo(path)
228 if info: return info[0]
229
Ka-Ping Yeec113c242001-03-02 02:08:53 +0000230def getsourcefile(object):
231 """Return the Python source file an object was defined in, if it exists."""
232 filename = getfile(object)
233 if string.lower(filename[-4:]) in ['.pyc', '.pyo']:
234 filename = filename[:-4] + '.py'
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000235 for suffix, mode, kind in imp.get_suffixes():
236 if 'b' in mode and string.lower(filename[-len(suffix):]) == suffix:
237 # Looks like a binary file. We want to only return a text file.
238 return None
239 if os.path.exists(filename):
Ka-Ping Yeec113c242001-03-02 02:08:53 +0000240 return filename
241
242def getabsfile(object):
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000243 """Return an absolute path to the source or compiled file for an object.
Ka-Ping Yeec113c242001-03-02 02:08:53 +0000244
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000245 The idea is for each object to have a unique origin, so this routine
246 normalizes the result as much as possible."""
247 return os.path.normcase(
248 os.path.abspath(getsourcefile(object) or getfile(object)))
Ka-Ping Yeec113c242001-03-02 02:08:53 +0000249
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000250modulesbyfile = {}
251
252def getmodule(object):
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000253 """Return the module an object was defined in, or None if not found."""
Ka-Ping Yee202c99b2001-04-13 09:15:08 +0000254 if ismodule(object):
255 return object
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000256 if isclass(object):
Ka-Ping Yee8b58b842001-03-01 13:56:16 +0000257 return sys.modules.get(object.__module__)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000258 try:
Ka-Ping Yeec113c242001-03-02 02:08:53 +0000259 file = getabsfile(object)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000260 except TypeError:
261 return None
262 if modulesbyfile.has_key(file):
263 return sys.modules[modulesbyfile[file]]
264 for module in sys.modules.values():
265 if hasattr(module, '__file__'):
Ka-Ping Yeec113c242001-03-02 02:08:53 +0000266 modulesbyfile[getabsfile(module)] = module.__name__
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000267 if modulesbyfile.has_key(file):
268 return sys.modules[modulesbyfile[file]]
269 main = sys.modules['__main__']
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000270 if hasattr(main, object.__name__):
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000271 mainobject = getattr(main, object.__name__)
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000272 if mainobject is object:
273 return main
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000274 builtin = sys.modules['__builtin__']
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000275 if hasattr(builtin, object.__name__):
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000276 builtinobject = getattr(builtin, object.__name__)
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000277 if builtinobject is object:
278 return builtin
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000279
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000280def findsource(object):
281 """Return the entire source file and starting line number for an object.
282
283 The argument may be a module, class, method, function, traceback, frame,
284 or code object. The source code is returned as a list of all the lines
285 in the file and the line number indexes a line in that list. An IOError
286 is raised if the source code cannot be retrieved."""
287 try:
288 file = open(getsourcefile(object))
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000289 except (TypeError, IOError):
290 raise IOError, 'could not get source code'
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000291 lines = file.readlines()
292 file.close()
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000293
294 if ismodule(object):
295 return lines, 0
296
297 if isclass(object):
298 name = object.__name__
Ka-Ping Yeea6e59712001-03-10 09:31:55 +0000299 pat = re.compile(r'^\s*class\s*' + name + r'\b')
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000300 for i in range(len(lines)):
Ka-Ping Yeea6e59712001-03-10 09:31:55 +0000301 if pat.match(lines[i]): return lines, i
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000302 else: raise IOError, 'could not find class definition'
303
304 if ismethod(object):
305 object = object.im_func
306 if isfunction(object):
307 object = object.func_code
308 if istraceback(object):
309 object = object.tb_frame
310 if isframe(object):
311 object = object.f_code
312 if iscode(object):
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000313 if not hasattr(object, 'co_firstlineno'):
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000314 raise IOError, 'could not find function definition'
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000315 lnum = object.co_firstlineno - 1
Ka-Ping Yeea6e59712001-03-10 09:31:55 +0000316 pat = re.compile(r'^\s*def\s')
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000317 while lnum > 0:
Ka-Ping Yeea6e59712001-03-10 09:31:55 +0000318 if pat.match(lines[lnum]): break
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000319 lnum = lnum - 1
320 return lines, lnum
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000321
322def getcomments(object):
323 """Get lines of comments immediately preceding an object's source code."""
324 try: lines, lnum = findsource(object)
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000325 except IOError: return None
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000326
327 if ismodule(object):
328 # Look for a comment block at the top of the file.
329 start = 0
Ka-Ping Yeeb910efe2001-04-12 13:17:17 +0000330 if lines and lines[0][:2] == '#!': start = 1
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000331 while start < len(lines) and string.strip(lines[start]) in ['', '#']:
332 start = start + 1
Ka-Ping Yeeb910efe2001-04-12 13:17:17 +0000333 if start < len(lines) and lines[start][:1] == '#':
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000334 comments = []
335 end = start
336 while end < len(lines) and lines[end][:1] == '#':
337 comments.append(string.expandtabs(lines[end]))
338 end = end + 1
339 return string.join(comments, '')
340
341 # Look for a preceding block of comments at the same indentation.
342 elif lnum > 0:
343 indent = indentsize(lines[lnum])
344 end = lnum - 1
345 if end >= 0 and string.lstrip(lines[end])[:1] == '#' and \
346 indentsize(lines[end]) == indent:
347 comments = [string.lstrip(string.expandtabs(lines[end]))]
348 if end > 0:
349 end = end - 1
350 comment = string.lstrip(string.expandtabs(lines[end]))
351 while comment[:1] == '#' and indentsize(lines[end]) == indent:
352 comments[:0] = [comment]
353 end = end - 1
354 if end < 0: break
355 comment = string.lstrip(string.expandtabs(lines[end]))
356 while comments and string.strip(comments[0]) == '#':
357 comments[:1] = []
358 while comments and string.strip(comments[-1]) == '#':
359 comments[-1:] = []
360 return string.join(comments, '')
361
362class ListReader:
363 """Provide a readline() method to return lines from a list of strings."""
364 def __init__(self, lines):
365 self.lines = lines
366 self.index = 0
367
368 def readline(self):
369 i = self.index
370 if i < len(self.lines):
371 self.index = i + 1
372 return self.lines[i]
373 else: return ''
374
Tim Peters4efb6e92001-06-29 23:51:08 +0000375class EndOfBlock(Exception): pass
376
377class BlockFinder:
378 """Provide a tokeneater() method to detect the end of a code block."""
379 def __init__(self):
380 self.indent = 0
381 self.started = 0
382 self.last = 0
383
384 def tokeneater(self, type, token, (srow, scol), (erow, ecol), line):
385 if not self.started:
386 if type == tokenize.NAME: self.started = 1
387 elif type == tokenize.NEWLINE:
388 self.last = srow
389 elif type == tokenize.INDENT:
390 self.indent = self.indent + 1
391 elif type == tokenize.DEDENT:
392 self.indent = self.indent - 1
393 if self.indent == 0: raise EndOfBlock, self.last
394
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000395def getblock(lines):
396 """Extract the block of code at the top of the given list of lines."""
Tim Peters4efb6e92001-06-29 23:51:08 +0000397 try:
398 tokenize.tokenize(ListReader(lines).readline, BlockFinder().tokeneater)
399 except EndOfBlock, eob:
400 return lines[:eob.args[0]]
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000401
402def getsourcelines(object):
403 """Return a list of source lines and starting line number for an object.
404
405 The argument may be a module, class, method, function, traceback, frame,
406 or code object. The source code is returned as a list of the lines
407 corresponding to the object and the line number indicates where in the
408 original source file the first line of code was found. An IOError is
409 raised if the source code cannot be retrieved."""
410 lines, lnum = findsource(object)
411
412 if ismodule(object): return lines, 0
413 else: return getblock(lines[lnum:]), lnum + 1
414
415def getsource(object):
416 """Return the text of the source code for an object.
417
418 The argument may be a module, class, method, function, traceback, frame,
419 or code object. The source code is returned as a single string. An
420 IOError is raised if the source code cannot be retrieved."""
421 lines, lnum = getsourcelines(object)
422 return string.join(lines, '')
423
424# --------------------------------------------------- class tree extraction
425def walktree(classes, children, parent):
426 """Recursive helper function for getclasstree()."""
427 results = []
428 classes.sort(lambda a, b: cmp(a.__name__, b.__name__))
429 for c in classes:
430 results.append((c, c.__bases__))
431 if children.has_key(c):
432 results.append(walktree(children[c], children, c))
433 return results
434
435def getclasstree(classes, unique=0):
436 """Arrange the given list of classes into a hierarchy of nested lists.
437
438 Where a nested list appears, it contains classes derived from the class
439 whose entry immediately precedes the list. Each entry is a 2-tuple
440 containing a class and a tuple of its base classes. If the 'unique'
441 argument is true, exactly one entry appears in the returned structure
442 for each class in the given list. Otherwise, classes using multiple
443 inheritance and their descendants will appear multiple times."""
444 children = {}
445 roots = []
446 for c in classes:
447 if c.__bases__:
448 for parent in c.__bases__:
449 if not children.has_key(parent):
450 children[parent] = []
451 children[parent].append(c)
452 if unique and parent in classes: break
453 elif c not in roots:
454 roots.append(c)
455 for parent in children.keys():
456 if parent not in classes:
457 roots.append(parent)
458 return walktree(roots, children, None)
459
460# ------------------------------------------------ argument list extraction
461# These constants are from Python's compile.h.
462CO_OPTIMIZED, CO_NEWLOCALS, CO_VARARGS, CO_VARKEYWORDS = 1, 2, 4, 8
463
464def getargs(co):
465 """Get information about the arguments accepted by a code object.
466
467 Three things are returned: (args, varargs, varkw), where 'args' is
468 a list of argument names (possibly containing nested lists), and
469 'varargs' and 'varkw' are the names of the * and ** arguments or None."""
470 if not iscode(co): raise TypeError, 'arg is not a code object'
471
472 code = co.co_code
473 nargs = co.co_argcount
474 names = co.co_varnames
475 args = list(names[:nargs])
476 step = 0
477
478 # The following acrobatics are for anonymous (tuple) arguments.
479 for i in range(nargs):
480 if args[i][:1] in ['', '.']:
481 stack, remain, count = [], [], []
482 while step < len(code):
483 op = ord(code[step])
484 step = step + 1
485 if op >= dis.HAVE_ARGUMENT:
486 opname = dis.opname[op]
487 value = ord(code[step]) + ord(code[step+1])*256
488 step = step + 2
489 if opname in ['UNPACK_TUPLE', 'UNPACK_SEQUENCE']:
490 remain.append(value)
491 count.append(value)
492 elif opname == 'STORE_FAST':
493 stack.append(names[value])
494 remain[-1] = remain[-1] - 1
495 while remain[-1] == 0:
496 remain.pop()
497 size = count.pop()
498 stack[-size:] = [stack[-size:]]
499 if not remain: break
500 remain[-1] = remain[-1] - 1
501 if not remain: break
502 args[i] = stack[0]
503
504 varargs = None
505 if co.co_flags & CO_VARARGS:
506 varargs = co.co_varnames[nargs]
507 nargs = nargs + 1
508 varkw = None
509 if co.co_flags & CO_VARKEYWORDS:
510 varkw = co.co_varnames[nargs]
511 return args, varargs, varkw
512
513def getargspec(func):
514 """Get the names and default values of a function's arguments.
515
516 A tuple of four things is returned: (args, varargs, varkw, defaults).
517 'args' is a list of the argument names (it may contain nested lists).
518 'varargs' and 'varkw' are the names of the * and ** arguments or None.
519 'defaults' is an n-tuple of the default values of the last n arguments."""
520 if not isfunction(func): raise TypeError, 'arg is not a Python function'
521 args, varargs, varkw = getargs(func.func_code)
522 return args, varargs, varkw, func.func_defaults
523
524def getargvalues(frame):
525 """Get information about arguments passed into a particular frame.
526
527 A tuple of four things is returned: (args, varargs, varkw, locals).
528 'args' is a list of the argument names (it may contain nested lists).
529 'varargs' and 'varkw' are the names of the * and ** arguments or None.
530 'locals' is the locals dictionary of the given frame."""
531 args, varargs, varkw = getargs(frame.f_code)
532 return args, varargs, varkw, frame.f_locals
533
534def joinseq(seq):
535 if len(seq) == 1:
536 return '(' + seq[0] + ',)'
537 else:
538 return '(' + string.join(seq, ', ') + ')'
539
540def strseq(object, convert, join=joinseq):
541 """Recursively walk a sequence, stringifying each element."""
542 if type(object) in [types.ListType, types.TupleType]:
543 return join(map(lambda o, c=convert, j=join: strseq(o, c, j), object))
544 else:
545 return convert(object)
546
547def formatargspec(args, varargs=None, varkw=None, defaults=None,
548 formatarg=str,
549 formatvarargs=lambda name: '*' + name,
550 formatvarkw=lambda name: '**' + name,
551 formatvalue=lambda value: '=' + repr(value),
552 join=joinseq):
553 """Format an argument spec from the 4 values returned by getargspec.
554
555 The first four arguments are (args, varargs, varkw, defaults). The
556 other four arguments are the corresponding optional formatting functions
557 that are called to turn names and values into strings. The ninth
558 argument is an optional function to format the sequence of arguments."""
559 specs = []
560 if defaults:
561 firstdefault = len(args) - len(defaults)
562 for i in range(len(args)):
563 spec = strseq(args[i], formatarg, join)
564 if defaults and i >= firstdefault:
565 spec = spec + formatvalue(defaults[i - firstdefault])
566 specs.append(spec)
567 if varargs:
568 specs.append(formatvarargs(varargs))
569 if varkw:
570 specs.append(formatvarkw(varkw))
571 return '(' + string.join(specs, ', ') + ')'
572
573def formatargvalues(args, varargs, varkw, locals,
574 formatarg=str,
575 formatvarargs=lambda name: '*' + name,
576 formatvarkw=lambda name: '**' + name,
577 formatvalue=lambda value: '=' + repr(value),
578 join=joinseq):
579 """Format an argument spec from the 4 values returned by getargvalues.
580
581 The first four arguments are (args, varargs, varkw, locals). The
582 next four arguments are the corresponding optional formatting functions
583 that are called to turn names and values into strings. The ninth
584 argument is an optional function to format the sequence of arguments."""
585 def convert(name, locals=locals,
586 formatarg=formatarg, formatvalue=formatvalue):
587 return formatarg(name) + formatvalue(locals[name])
588 specs = []
589 for i in range(len(args)):
590 specs.append(strseq(args[i], convert, join))
591 if varargs:
592 specs.append(formatvarargs(varargs) + formatvalue(locals[varargs]))
593 if varkw:
594 specs.append(formatvarkw(varkw) + formatvalue(locals[varkw]))
595 return '(' + string.join(specs, ', ') + ')'
596
597# -------------------------------------------------- stack frame extraction
598def getframeinfo(frame, context=1):
599 """Get information about a frame or traceback object.
600
601 A tuple of five things is returned: the filename, the line number of
602 the current line, the function name, a list of lines of context from
603 the source code, and the index of the current line within that list.
604 The optional second argument specifies the number of lines of context
605 to return, which are centered around the current line."""
606 if istraceback(frame):
607 frame = frame.tb_frame
608 if not isframe(frame):
609 raise TypeError, 'arg is not a frame or traceback object'
610
611 filename = getsourcefile(frame)
Ka-Ping Yee59ade082001-03-01 03:55:35 +0000612 lineno = getlineno(frame)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000613 if context > 0:
Guido van Rossum54e54c62001-09-04 19:14:14 +0000614 start = lineno - 1 - context//2
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000615 try:
616 lines, lnum = findsource(frame)
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000617 except IOError:
618 lines = index = None
619 else:
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000620 start = max(start, 1)
621 start = min(start, len(lines) - context)
622 lines = lines[start:start+context]
Ka-Ping Yee59ade082001-03-01 03:55:35 +0000623 index = lineno - 1 - start
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000624 else:
625 lines = index = None
626
Ka-Ping Yee59ade082001-03-01 03:55:35 +0000627 return (filename, lineno, frame.f_code.co_name, lines, index)
628
629def getlineno(frame):
630 """Get the line number from a frame object, allowing for optimization."""
631 # Written by Marc-André Lemburg; revised by Jim Hugunin and Fredrik Lundh.
632 lineno = frame.f_lineno
633 code = frame.f_code
634 if hasattr(code, 'co_lnotab'):
635 table = code.co_lnotab
636 lineno = code.co_firstlineno
637 addr = 0
638 for i in range(0, len(table), 2):
639 addr = addr + ord(table[i])
640 if addr > frame.f_lasti: break
641 lineno = lineno + ord(table[i+1])
642 return lineno
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000643
644def getouterframes(frame, context=1):
645 """Get a list of records for a frame and all higher (calling) frames.
646
647 Each record contains a frame object, filename, line number, function
648 name, a list of lines of context, and index within the context."""
649 framelist = []
650 while frame:
651 framelist.append((frame,) + getframeinfo(frame, context))
652 frame = frame.f_back
653 return framelist
654
655def getinnerframes(tb, context=1):
656 """Get a list of records for a traceback's frame and all lower frames.
657
658 Each record contains a frame object, filename, line number, function
659 name, a list of lines of context, and index within the context."""
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000660 framelist = []
661 while tb:
662 framelist.append((tb.tb_frame,) + getframeinfo(tb, context))
663 tb = tb.tb_next
664 return framelist
665
666def currentframe():
667 """Return the frame object for the caller's stack frame."""
668 try:
669 raise 'catch me'
670 except:
671 return sys.exc_traceback.tb_frame.f_back
672
673if hasattr(sys, '_getframe'): currentframe = sys._getframe
674
675def stack(context=1):
676 """Return a list of records for the stack above the caller's frame."""
677 return getouterframes(currentframe().f_back, context)
678
679def trace(context=1):
Tim Peters85ba6732001-02-28 08:26:44 +0000680 """Return a list of records for the stack below the current exception."""
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000681 return getinnerframes(sys.exc_traceback, context)