blob: be2da41559c1caed75c696968b69cc265c0cfece [file] [log] [blame]
Martin v. Löwis09776b72002-08-04 17:22:59 +00001# -*- coding: iso-8859-1 -*-
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00002"""Get useful information from live Python objects.
3
4This module encapsulates the interface provided by the internal special
5attributes (func_*, co_*, im_*, tb_*, etc.) in a friendlier fashion.
6It also provides some help for examining source code and class layout.
7
8Here are some of the useful functions provided by this module:
9
10 ismodule(), isclass(), ismethod(), isfunction(), istraceback(),
11 isframe(), iscode(), isbuiltin(), isroutine() - check object types
12 getmembers() - get members of an object that satisfy a given condition
13
14 getfile(), getsourcefile(), getsource() - find an object's source code
15 getdoc(), getcomments() - get documentation on an object
16 getmodule() - determine the module that an object came from
17 getclasstree() - arrange classes so as to represent their hierarchy
18
19 getargspec(), getargvalues() - get info about function arguments
20 formatargspec(), formatargvalues() - format an argument spec
21 getouterframes(), getinnerframes() - get info about frames
22 currentframe() - get the current stack frame
23 stack(), trace() - get info about frames on the stack or in a traceback
24"""
25
26# This module is in the public domain. No warranties.
27
Ka-Ping Yee8b58b842001-03-01 13:56:16 +000028__author__ = 'Ka-Ping Yee <ping@lfw.org>'
29__date__ = '1 Jan 2001'
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +000030
Neil Schemenauerf06f8532002-03-23 23:51:04 +000031import sys, os, types, string, re, dis, imp, tokenize, linecache
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +000032
33# ----------------------------------------------------------- type-checking
34def ismodule(object):
35 """Return true if the object is a module.
36
37 Module objects provide these attributes:
38 __doc__ documentation string
39 __file__ filename (missing for built-in modules)"""
Tim Peters28bc59f2001-09-16 08:40:16 +000040 return isinstance(object, types.ModuleType)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +000041
42def isclass(object):
43 """Return true if the object is a class.
44
45 Class objects provide these attributes:
46 __doc__ documentation string
47 __module__ name of module in which this class was defined"""
Tim Peters28bc59f2001-09-16 08:40:16 +000048 return isinstance(object, types.ClassType) or hasattr(object, '__bases__')
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +000049
50def ismethod(object):
51 """Return true if the object is an instance method.
52
53 Instance method objects provide these attributes:
54 __doc__ documentation string
55 __name__ name with which this method was defined
56 im_class class object in which this method belongs
57 im_func function object containing implementation of method
58 im_self instance to which this method is bound, or None"""
Tim Peters28bc59f2001-09-16 08:40:16 +000059 return isinstance(object, types.MethodType)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +000060
Tim Peters536d2262001-09-20 05:13:38 +000061def ismethoddescriptor(object):
Tim Petersf1d90b92001-09-20 05:47:55 +000062 """Return true if the object is a method descriptor.
63
64 But not if ismethod() or isclass() or isfunction() are true.
Tim Peters536d2262001-09-20 05:13:38 +000065
66 This is new in Python 2.2, and, for example, is true of int.__add__.
67 An object passing this test has a __get__ attribute but not a __set__
68 attribute, but beyond that the set of attributes varies. __name__ is
69 usually sensible, and __doc__ often is.
70
Tim Petersf1d90b92001-09-20 05:47:55 +000071 Methods implemented via descriptors that also pass one of the other
72 tests return false from the ismethoddescriptor() test, simply because
73 the other tests promise more -- you can, e.g., count on having the
74 im_func attribute (etc) when an object passes ismethod()."""
Tim Peters536d2262001-09-20 05:13:38 +000075 return (hasattr(object, "__get__")
76 and not hasattr(object, "__set__") # else it's a data descriptor
77 and not ismethod(object) # mutual exclusion
Tim Petersf1d90b92001-09-20 05:47:55 +000078 and not isfunction(object)
Tim Peters536d2262001-09-20 05:13:38 +000079 and not isclass(object))
80
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +000081def isfunction(object):
82 """Return true if the object is a user-defined function.
83
84 Function objects provide these attributes:
85 __doc__ documentation string
86 __name__ name with which this function was defined
87 func_code code object containing compiled function bytecode
88 func_defaults tuple of any default values for arguments
89 func_doc (same as __doc__)
90 func_globals global namespace in which this function was defined
91 func_name (same as __name__)"""
Tim Peters28bc59f2001-09-16 08:40:16 +000092 return isinstance(object, types.FunctionType)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +000093
94def istraceback(object):
95 """Return true if the object is a traceback.
96
97 Traceback objects provide these attributes:
98 tb_frame frame object at this level
99 tb_lasti index of last attempted instruction in bytecode
100 tb_lineno current line number in Python source code
101 tb_next next inner traceback object (called by this level)"""
Tim Peters28bc59f2001-09-16 08:40:16 +0000102 return isinstance(object, types.TracebackType)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000103
104def isframe(object):
105 """Return true if the object is a frame object.
106
107 Frame objects provide these attributes:
108 f_back next outer frame object (this frame's caller)
109 f_builtins built-in namespace seen by this frame
110 f_code code object being executed in this frame
111 f_exc_traceback traceback if raised in this frame, or None
112 f_exc_type exception type if raised in this frame, or None
113 f_exc_value exception value if raised in this frame, or None
114 f_globals global namespace seen by this frame
115 f_lasti index of last attempted instruction in bytecode
116 f_lineno current line number in Python source code
117 f_locals local namespace seen by this frame
118 f_restricted 0 or 1 if frame is in restricted execution mode
119 f_trace tracing function for this frame, or None"""
Tim Peters28bc59f2001-09-16 08:40:16 +0000120 return isinstance(object, types.FrameType)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000121
122def iscode(object):
123 """Return true if the object is a code object.
124
125 Code objects provide these attributes:
126 co_argcount number of arguments (not including * or ** args)
127 co_code string of raw compiled bytecode
128 co_consts tuple of constants used in the bytecode
129 co_filename name of file in which this code object was created
130 co_firstlineno number of first line in Python source code
131 co_flags bitmap: 1=optimized | 2=newlocals | 4=*arg | 8=**arg
132 co_lnotab encoded mapping of line numbers to bytecode indices
133 co_name name with which this code object was defined
134 co_names tuple of names of local variables
135 co_nlocals number of local variables
136 co_stacksize virtual machine stack space required
137 co_varnames tuple of names of arguments and local variables"""
Tim Peters28bc59f2001-09-16 08:40:16 +0000138 return isinstance(object, types.CodeType)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000139
140def isbuiltin(object):
141 """Return true if the object is a built-in function or method.
142
143 Built-in functions and methods provide these attributes:
144 __doc__ documentation string
145 __name__ original name of this function or method
146 __self__ instance to which a method is bound, or None"""
Tim Peters28bc59f2001-09-16 08:40:16 +0000147 return isinstance(object, types.BuiltinFunctionType)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000148
149def isroutine(object):
150 """Return true if the object is any kind of function or method."""
Tim Peters536d2262001-09-20 05:13:38 +0000151 return (isbuiltin(object)
152 or isfunction(object)
153 or ismethod(object)
154 or ismethoddescriptor(object))
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000155
156def getmembers(object, predicate=None):
157 """Return all members of an object as (name, value) pairs sorted by name.
158 Optionally, only return members that satisfy a given predicate."""
159 results = []
160 for key in dir(object):
161 value = getattr(object, key)
162 if not predicate or predicate(value):
163 results.append((key, value))
164 results.sort()
165 return results
166
Tim Peters13b49d32001-09-23 02:00:29 +0000167def classify_class_attrs(cls):
168 """Return list of attribute-descriptor tuples.
169
170 For each name in dir(cls), the return list contains a 4-tuple
171 with these elements:
172
173 0. The name (a string).
174
175 1. The kind of attribute this is, one of these strings:
176 'class method' created via classmethod()
177 'static method' created via staticmethod()
178 'property' created via property()
179 'method' any other flavor of method
180 'data' not a method
181
182 2. The class which defined this attribute (a class).
183
184 3. The object as obtained directly from the defining class's
185 __dict__, not via getattr. This is especially important for
186 data attributes: C.data is just a data object, but
187 C.__dict__['data'] may be a data descriptor with additional
188 info, like a __doc__ string.
189 """
190
191 mro = getmro(cls)
192 names = dir(cls)
193 result = []
194 for name in names:
195 # Get the object associated with the name.
196 # Getting an obj from the __dict__ sometimes reveals more than
197 # using getattr. Static and class methods are dramatic examples.
198 if name in cls.__dict__:
199 obj = cls.__dict__[name]
200 else:
201 obj = getattr(cls, name)
202
203 # Figure out where it was defined.
Tim Peters13b49d32001-09-23 02:00:29 +0000204 homecls = getattr(obj, "__objclass__", None)
205 if homecls is None:
Guido van Rossum687ae002001-10-15 22:03:32 +0000206 # search the dicts.
Tim Peters13b49d32001-09-23 02:00:29 +0000207 for base in mro:
208 if name in base.__dict__:
209 homecls = base
210 break
211
212 # Get the object again, in order to get it from the defining
213 # __dict__ instead of via getattr (if possible).
214 if homecls is not None and name in homecls.__dict__:
215 obj = homecls.__dict__[name]
216
217 # Also get the object via getattr.
218 obj_via_getattr = getattr(cls, name)
219
220 # Classify the object.
221 if isinstance(obj, staticmethod):
222 kind = "static method"
223 elif isinstance(obj, classmethod):
224 kind = "class method"
225 elif isinstance(obj, property):
226 kind = "property"
227 elif (ismethod(obj_via_getattr) or
228 ismethoddescriptor(obj_via_getattr)):
229 kind = "method"
230 else:
231 kind = "data"
232
233 result.append((name, kind, homecls, obj))
234
235 return result
236
Tim Peterse0b2d7a2001-09-22 06:10:55 +0000237# ----------------------------------------------------------- class helpers
238def _searchbases(cls, accum):
239 # Simulate the "classic class" search order.
240 if cls in accum:
241 return
242 accum.append(cls)
243 for base in cls.__bases__:
244 _searchbases(base, accum)
245
246def getmro(cls):
247 "Return tuple of base classes (including cls) in method resolution order."
248 if hasattr(cls, "__mro__"):
249 return cls.__mro__
250 else:
251 result = []
252 _searchbases(cls, result)
253 return tuple(result)
254
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000255# -------------------------------------------------- source code extraction
256def indentsize(line):
257 """Return the indent size, in spaces, at the start of a line of text."""
258 expline = string.expandtabs(line)
259 return len(expline) - len(string.lstrip(expline))
260
261def getdoc(object):
262 """Get the documentation string for an object.
263
264 All tabs are expanded to spaces. To clean up docstrings that are
265 indented to line up with blocks of code, any whitespace than can be
266 uniformly removed from the second line onwards is removed."""
Tim Peters24008312002-03-17 18:56:20 +0000267 try:
268 doc = object.__doc__
269 except AttributeError:
270 return None
Michael W. Hudson755f75e2002-05-20 17:29:46 +0000271 if not isinstance(doc, types.StringTypes):
Tim Peters24008312002-03-17 18:56:20 +0000272 return None
273 try:
274 lines = string.split(string.expandtabs(doc), '\n')
275 except UnicodeError:
276 return None
277 else:
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000278 margin = None
279 for line in lines[1:]:
280 content = len(string.lstrip(line))
281 if not content: continue
282 indent = len(line) - content
283 if margin is None: margin = indent
284 else: margin = min(margin, indent)
285 if margin is not None:
286 for i in range(1, len(lines)): lines[i] = lines[i][margin:]
287 return string.join(lines, '\n')
288
289def getfile(object):
Ka-Ping Yeec113c242001-03-02 02:08:53 +0000290 """Work out which source or compiled file an object was defined in."""
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000291 if ismodule(object):
292 if hasattr(object, '__file__'):
293 return object.__file__
294 raise TypeError, 'arg is a built-in module'
295 if isclass(object):
Ka-Ping Yeec99e0f12001-04-13 12:10:40 +0000296 object = sys.modules.get(object.__module__)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000297 if hasattr(object, '__file__'):
298 return object.__file__
299 raise TypeError, 'arg is a built-in class'
300 if ismethod(object):
301 object = object.im_func
302 if isfunction(object):
303 object = object.func_code
304 if istraceback(object):
305 object = object.tb_frame
306 if isframe(object):
307 object = object.f_code
308 if iscode(object):
309 return object.co_filename
310 raise TypeError, 'arg is not a module, class, method, ' \
311 'function, traceback, frame, or code object'
312
Ka-Ping Yee4d6fc7f2001-04-10 11:43:00 +0000313def getmoduleinfo(path):
314 """Get the module name, suffix, mode, and module type for a given file."""
315 filename = os.path.basename(path)
316 suffixes = map(lambda (suffix, mode, mtype):
317 (-len(suffix), suffix, mode, mtype), imp.get_suffixes())
318 suffixes.sort() # try longest suffixes first, in case they overlap
319 for neglen, suffix, mode, mtype in suffixes:
320 if filename[neglen:] == suffix:
321 return filename[:neglen], suffix, mode, mtype
322
323def getmodulename(path):
324 """Return the module name for a given file, or None."""
325 info = getmoduleinfo(path)
326 if info: return info[0]
327
Ka-Ping Yeec113c242001-03-02 02:08:53 +0000328def getsourcefile(object):
329 """Return the Python source file an object was defined in, if it exists."""
330 filename = getfile(object)
331 if string.lower(filename[-4:]) in ['.pyc', '.pyo']:
332 filename = filename[:-4] + '.py'
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000333 for suffix, mode, kind in imp.get_suffixes():
334 if 'b' in mode and string.lower(filename[-len(suffix):]) == suffix:
335 # Looks like a binary file. We want to only return a text file.
336 return None
337 if os.path.exists(filename):
Ka-Ping Yeec113c242001-03-02 02:08:53 +0000338 return filename
339
340def getabsfile(object):
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000341 """Return an absolute path to the source or compiled file for an object.
Ka-Ping Yeec113c242001-03-02 02:08:53 +0000342
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000343 The idea is for each object to have a unique origin, so this routine
344 normalizes the result as much as possible."""
345 return os.path.normcase(
346 os.path.abspath(getsourcefile(object) or getfile(object)))
Ka-Ping Yeec113c242001-03-02 02:08:53 +0000347
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000348modulesbyfile = {}
349
350def getmodule(object):
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000351 """Return the module an object was defined in, or None if not found."""
Ka-Ping Yee202c99b2001-04-13 09:15:08 +0000352 if ismodule(object):
353 return object
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000354 if isclass(object):
Ka-Ping Yee8b58b842001-03-01 13:56:16 +0000355 return sys.modules.get(object.__module__)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000356 try:
Ka-Ping Yeec113c242001-03-02 02:08:53 +0000357 file = getabsfile(object)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000358 except TypeError:
359 return None
Raymond Hettinger54f02222002-06-01 14:18:47 +0000360 if file in modulesbyfile:
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000361 return sys.modules[modulesbyfile[file]]
362 for module in sys.modules.values():
363 if hasattr(module, '__file__'):
Ka-Ping Yeec113c242001-03-02 02:08:53 +0000364 modulesbyfile[getabsfile(module)] = module.__name__
Raymond Hettinger54f02222002-06-01 14:18:47 +0000365 if file in modulesbyfile:
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000366 return sys.modules[modulesbyfile[file]]
367 main = sys.modules['__main__']
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000368 if hasattr(main, object.__name__):
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000369 mainobject = getattr(main, object.__name__)
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000370 if mainobject is object:
371 return main
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000372 builtin = sys.modules['__builtin__']
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000373 if hasattr(builtin, object.__name__):
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000374 builtinobject = getattr(builtin, object.__name__)
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000375 if builtinobject is object:
376 return builtin
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000377
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000378def findsource(object):
379 """Return the entire source file and starting line number for an object.
380
381 The argument may be a module, class, method, function, traceback, frame,
382 or code object. The source code is returned as a list of all the lines
383 in the file and the line number indexes a line in that list. An IOError
384 is raised if the source code cannot be retrieved."""
Neil Schemenauerf06f8532002-03-23 23:51:04 +0000385 file = getsourcefile(object) or getfile(object)
386 lines = linecache.getlines(file)
387 if not lines:
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000388 raise IOError, 'could not get source code'
389
390 if ismodule(object):
391 return lines, 0
392
393 if isclass(object):
394 name = object.__name__
Ka-Ping Yeea6e59712001-03-10 09:31:55 +0000395 pat = re.compile(r'^\s*class\s*' + name + r'\b')
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000396 for i in range(len(lines)):
Ka-Ping Yeea6e59712001-03-10 09:31:55 +0000397 if pat.match(lines[i]): return lines, i
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000398 else: raise IOError, 'could not find class definition'
399
400 if ismethod(object):
401 object = object.im_func
402 if isfunction(object):
403 object = object.func_code
404 if istraceback(object):
405 object = object.tb_frame
406 if isframe(object):
407 object = object.f_code
408 if iscode(object):
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000409 if not hasattr(object, 'co_firstlineno'):
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000410 raise IOError, 'could not find function definition'
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000411 lnum = object.co_firstlineno - 1
Ka-Ping Yeea6e59712001-03-10 09:31:55 +0000412 pat = re.compile(r'^\s*def\s')
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000413 while lnum > 0:
Ka-Ping Yeea6e59712001-03-10 09:31:55 +0000414 if pat.match(lines[lnum]): break
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000415 lnum = lnum - 1
416 return lines, lnum
Neal Norwitz8a11f5d2002-03-13 03:14:26 +0000417 raise IOError, 'could not find code object'
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000418
419def getcomments(object):
Jeremy Hyltonb4c17c82002-03-28 23:01:56 +0000420 """Get lines of comments immediately preceding an object's source code.
421
422 Returns None when source can't be found.
423 """
424 try:
425 lines, lnum = findsource(object)
426 except (IOError, TypeError):
427 return None
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000428
429 if ismodule(object):
430 # Look for a comment block at the top of the file.
431 start = 0
Ka-Ping Yeeb910efe2001-04-12 13:17:17 +0000432 if lines and lines[0][:2] == '#!': start = 1
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000433 while start < len(lines) and string.strip(lines[start]) in ['', '#']:
434 start = start + 1
Ka-Ping Yeeb910efe2001-04-12 13:17:17 +0000435 if start < len(lines) and lines[start][:1] == '#':
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000436 comments = []
437 end = start
438 while end < len(lines) and lines[end][:1] == '#':
439 comments.append(string.expandtabs(lines[end]))
440 end = end + 1
441 return string.join(comments, '')
442
443 # Look for a preceding block of comments at the same indentation.
444 elif lnum > 0:
445 indent = indentsize(lines[lnum])
446 end = lnum - 1
447 if end >= 0 and string.lstrip(lines[end])[:1] == '#' and \
448 indentsize(lines[end]) == indent:
449 comments = [string.lstrip(string.expandtabs(lines[end]))]
450 if end > 0:
451 end = end - 1
452 comment = string.lstrip(string.expandtabs(lines[end]))
453 while comment[:1] == '#' and indentsize(lines[end]) == indent:
454 comments[:0] = [comment]
455 end = end - 1
456 if end < 0: break
457 comment = string.lstrip(string.expandtabs(lines[end]))
458 while comments and string.strip(comments[0]) == '#':
459 comments[:1] = []
460 while comments and string.strip(comments[-1]) == '#':
461 comments[-1:] = []
462 return string.join(comments, '')
463
464class ListReader:
465 """Provide a readline() method to return lines from a list of strings."""
466 def __init__(self, lines):
467 self.lines = lines
468 self.index = 0
469
470 def readline(self):
471 i = self.index
472 if i < len(self.lines):
473 self.index = i + 1
474 return self.lines[i]
475 else: return ''
476
Tim Peters4efb6e92001-06-29 23:51:08 +0000477class EndOfBlock(Exception): pass
478
479class BlockFinder:
480 """Provide a tokeneater() method to detect the end of a code block."""
481 def __init__(self):
482 self.indent = 0
483 self.started = 0
484 self.last = 0
485
486 def tokeneater(self, type, token, (srow, scol), (erow, ecol), line):
487 if not self.started:
488 if type == tokenize.NAME: self.started = 1
489 elif type == tokenize.NEWLINE:
490 self.last = srow
491 elif type == tokenize.INDENT:
492 self.indent = self.indent + 1
493 elif type == tokenize.DEDENT:
494 self.indent = self.indent - 1
495 if self.indent == 0: raise EndOfBlock, self.last
496
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000497def getblock(lines):
498 """Extract the block of code at the top of the given list of lines."""
Tim Peters4efb6e92001-06-29 23:51:08 +0000499 try:
500 tokenize.tokenize(ListReader(lines).readline, BlockFinder().tokeneater)
501 except EndOfBlock, eob:
502 return lines[:eob.args[0]]
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000503
504def getsourcelines(object):
505 """Return a list of source lines and starting line number for an object.
506
507 The argument may be a module, class, method, function, traceback, frame,
508 or code object. The source code is returned as a list of the lines
509 corresponding to the object and the line number indicates where in the
510 original source file the first line of code was found. An IOError is
511 raised if the source code cannot be retrieved."""
512 lines, lnum = findsource(object)
513
514 if ismodule(object): return lines, 0
515 else: return getblock(lines[lnum:]), lnum + 1
516
517def getsource(object):
518 """Return the text of the source code for an object.
519
520 The argument may be a module, class, method, function, traceback, frame,
521 or code object. The source code is returned as a single string. An
522 IOError is raised if the source code cannot be retrieved."""
523 lines, lnum = getsourcelines(object)
524 return string.join(lines, '')
525
526# --------------------------------------------------- class tree extraction
527def walktree(classes, children, parent):
528 """Recursive helper function for getclasstree()."""
529 results = []
530 classes.sort(lambda a, b: cmp(a.__name__, b.__name__))
531 for c in classes:
532 results.append((c, c.__bases__))
Raymond Hettinger54f02222002-06-01 14:18:47 +0000533 if c in children:
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000534 results.append(walktree(children[c], children, c))
535 return results
536
537def getclasstree(classes, unique=0):
538 """Arrange the given list of classes into a hierarchy of nested lists.
539
540 Where a nested list appears, it contains classes derived from the class
541 whose entry immediately precedes the list. Each entry is a 2-tuple
542 containing a class and a tuple of its base classes. If the 'unique'
543 argument is true, exactly one entry appears in the returned structure
544 for each class in the given list. Otherwise, classes using multiple
545 inheritance and their descendants will appear multiple times."""
546 children = {}
547 roots = []
548 for c in classes:
549 if c.__bases__:
550 for parent in c.__bases__:
Raymond Hettinger54f02222002-06-01 14:18:47 +0000551 if not parent in children:
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000552 children[parent] = []
553 children[parent].append(c)
554 if unique and parent in classes: break
555 elif c not in roots:
556 roots.append(c)
Raymond Hettingere0d49722002-06-02 18:55:56 +0000557 for parent in children:
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000558 if parent not in classes:
559 roots.append(parent)
560 return walktree(roots, children, None)
561
562# ------------------------------------------------ argument list extraction
563# These constants are from Python's compile.h.
564CO_OPTIMIZED, CO_NEWLOCALS, CO_VARARGS, CO_VARKEYWORDS = 1, 2, 4, 8
565
566def getargs(co):
567 """Get information about the arguments accepted by a code object.
568
569 Three things are returned: (args, varargs, varkw), where 'args' is
570 a list of argument names (possibly containing nested lists), and
571 'varargs' and 'varkw' are the names of the * and ** arguments or None."""
572 if not iscode(co): raise TypeError, 'arg is not a code object'
573
574 code = co.co_code
575 nargs = co.co_argcount
576 names = co.co_varnames
577 args = list(names[:nargs])
578 step = 0
579
580 # The following acrobatics are for anonymous (tuple) arguments.
581 for i in range(nargs):
582 if args[i][:1] in ['', '.']:
583 stack, remain, count = [], [], []
584 while step < len(code):
585 op = ord(code[step])
586 step = step + 1
587 if op >= dis.HAVE_ARGUMENT:
588 opname = dis.opname[op]
589 value = ord(code[step]) + ord(code[step+1])*256
590 step = step + 2
591 if opname in ['UNPACK_TUPLE', 'UNPACK_SEQUENCE']:
592 remain.append(value)
593 count.append(value)
594 elif opname == 'STORE_FAST':
595 stack.append(names[value])
596 remain[-1] = remain[-1] - 1
597 while remain[-1] == 0:
598 remain.pop()
599 size = count.pop()
600 stack[-size:] = [stack[-size:]]
601 if not remain: break
602 remain[-1] = remain[-1] - 1
603 if not remain: break
604 args[i] = stack[0]
605
606 varargs = None
607 if co.co_flags & CO_VARARGS:
608 varargs = co.co_varnames[nargs]
609 nargs = nargs + 1
610 varkw = None
611 if co.co_flags & CO_VARKEYWORDS:
612 varkw = co.co_varnames[nargs]
613 return args, varargs, varkw
614
615def getargspec(func):
616 """Get the names and default values of a function's arguments.
617
618 A tuple of four things is returned: (args, varargs, varkw, defaults).
619 'args' is a list of the argument names (it may contain nested lists).
620 'varargs' and 'varkw' are the names of the * and ** arguments or None.
621 'defaults' is an n-tuple of the default values of the last n arguments."""
622 if not isfunction(func): raise TypeError, 'arg is not a Python function'
623 args, varargs, varkw = getargs(func.func_code)
624 return args, varargs, varkw, func.func_defaults
625
626def getargvalues(frame):
627 """Get information about arguments passed into a particular frame.
628
629 A tuple of four things is returned: (args, varargs, varkw, locals).
630 'args' is a list of the argument names (it may contain nested lists).
631 'varargs' and 'varkw' are the names of the * and ** arguments or None.
632 'locals' is the locals dictionary of the given frame."""
633 args, varargs, varkw = getargs(frame.f_code)
634 return args, varargs, varkw, frame.f_locals
635
636def joinseq(seq):
637 if len(seq) == 1:
638 return '(' + seq[0] + ',)'
639 else:
640 return '(' + string.join(seq, ', ') + ')'
641
642def strseq(object, convert, join=joinseq):
643 """Recursively walk a sequence, stringifying each element."""
644 if type(object) in [types.ListType, types.TupleType]:
645 return join(map(lambda o, c=convert, j=join: strseq(o, c, j), object))
646 else:
647 return convert(object)
648
649def formatargspec(args, varargs=None, varkw=None, defaults=None,
650 formatarg=str,
651 formatvarargs=lambda name: '*' + name,
652 formatvarkw=lambda name: '**' + name,
653 formatvalue=lambda value: '=' + repr(value),
654 join=joinseq):
655 """Format an argument spec from the 4 values returned by getargspec.
656
657 The first four arguments are (args, varargs, varkw, defaults). The
658 other four arguments are the corresponding optional formatting functions
659 that are called to turn names and values into strings. The ninth
660 argument is an optional function to format the sequence of arguments."""
661 specs = []
662 if defaults:
663 firstdefault = len(args) - len(defaults)
664 for i in range(len(args)):
665 spec = strseq(args[i], formatarg, join)
666 if defaults and i >= firstdefault:
667 spec = spec + formatvalue(defaults[i - firstdefault])
668 specs.append(spec)
Raymond Hettinger936654b2002-06-01 03:06:31 +0000669 if varargs is not None:
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000670 specs.append(formatvarargs(varargs))
Raymond Hettinger936654b2002-06-01 03:06:31 +0000671 if varkw is not None:
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000672 specs.append(formatvarkw(varkw))
673 return '(' + string.join(specs, ', ') + ')'
674
675def formatargvalues(args, varargs, varkw, locals,
676 formatarg=str,
677 formatvarargs=lambda name: '*' + name,
678 formatvarkw=lambda name: '**' + name,
679 formatvalue=lambda value: '=' + repr(value),
680 join=joinseq):
681 """Format an argument spec from the 4 values returned by getargvalues.
682
683 The first four arguments are (args, varargs, varkw, locals). The
684 next four arguments are the corresponding optional formatting functions
685 that are called to turn names and values into strings. The ninth
686 argument is an optional function to format the sequence of arguments."""
687 def convert(name, locals=locals,
688 formatarg=formatarg, formatvalue=formatvalue):
689 return formatarg(name) + formatvalue(locals[name])
690 specs = []
691 for i in range(len(args)):
692 specs.append(strseq(args[i], convert, join))
693 if varargs:
694 specs.append(formatvarargs(varargs) + formatvalue(locals[varargs]))
695 if varkw:
696 specs.append(formatvarkw(varkw) + formatvalue(locals[varkw]))
697 return '(' + string.join(specs, ', ') + ')'
698
699# -------------------------------------------------- stack frame extraction
700def getframeinfo(frame, context=1):
701 """Get information about a frame or traceback object.
702
703 A tuple of five things is returned: the filename, the line number of
704 the current line, the function name, a list of lines of context from
705 the source code, and the index of the current line within that list.
706 The optional second argument specifies the number of lines of context
707 to return, which are centered around the current line."""
708 if istraceback(frame):
709 frame = frame.tb_frame
710 if not isframe(frame):
711 raise TypeError, 'arg is not a frame or traceback object'
712
Neil Schemenauerf06f8532002-03-23 23:51:04 +0000713 filename = getsourcefile(frame) or getfile(frame)
Ka-Ping Yee59ade082001-03-01 03:55:35 +0000714 lineno = getlineno(frame)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000715 if context > 0:
Guido van Rossum54e54c62001-09-04 19:14:14 +0000716 start = lineno - 1 - context//2
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000717 try:
718 lines, lnum = findsource(frame)
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000719 except IOError:
720 lines = index = None
721 else:
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000722 start = max(start, 1)
723 start = min(start, len(lines) - context)
724 lines = lines[start:start+context]
Ka-Ping Yee59ade082001-03-01 03:55:35 +0000725 index = lineno - 1 - start
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000726 else:
727 lines = index = None
728
Ka-Ping Yee59ade082001-03-01 03:55:35 +0000729 return (filename, lineno, frame.f_code.co_name, lines, index)
730
731def getlineno(frame):
732 """Get the line number from a frame object, allowing for optimization."""
733 # Written by Marc-André Lemburg; revised by Jim Hugunin and Fredrik Lundh.
734 lineno = frame.f_lineno
735 code = frame.f_code
736 if hasattr(code, 'co_lnotab'):
737 table = code.co_lnotab
738 lineno = code.co_firstlineno
739 addr = 0
740 for i in range(0, len(table), 2):
741 addr = addr + ord(table[i])
742 if addr > frame.f_lasti: break
743 lineno = lineno + ord(table[i+1])
744 return lineno
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000745
746def getouterframes(frame, context=1):
747 """Get a list of records for a frame and all higher (calling) frames.
748
749 Each record contains a frame object, filename, line number, function
750 name, a list of lines of context, and index within the context."""
751 framelist = []
752 while frame:
753 framelist.append((frame,) + getframeinfo(frame, context))
754 frame = frame.f_back
755 return framelist
756
757def getinnerframes(tb, context=1):
758 """Get a list of records for a traceback's frame and all lower frames.
759
760 Each record contains a frame object, filename, line number, function
761 name, a list of lines of context, and index within the context."""
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000762 framelist = []
763 while tb:
764 framelist.append((tb.tb_frame,) + getframeinfo(tb, context))
765 tb = tb.tb_next
766 return framelist
767
768def currentframe():
769 """Return the frame object for the caller's stack frame."""
770 try:
Skip Montanaroa959a362002-03-25 21:37:54 +0000771 1/0
772 except ZeroDivisionError:
Fred Draked451ec12002-04-26 02:29:55 +0000773 return sys.exc_info()[2].tb_frame.f_back
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000774
775if hasattr(sys, '_getframe'): currentframe = sys._getframe
776
777def stack(context=1):
778 """Return a list of records for the stack above the caller's frame."""
779 return getouterframes(currentframe().f_back, context)
780
781def trace(context=1):
Tim Peters85ba6732001-02-28 08:26:44 +0000782 """Return a list of records for the stack below the current exception."""
Fred Draked451ec12002-04-26 02:29:55 +0000783 return getinnerframes(sys.exc_info()[2], context)