Martin v. Löwis | 09776b7 | 2002-08-04 17:22:59 +0000 | [diff] [blame] | 1 | # -*- coding: iso-8859-1 -*- |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 2 | """Get useful information from live Python objects. |
| 3 | |
| 4 | This module encapsulates the interface provided by the internal special |
| 5 | attributes (func_*, co_*, im_*, tb_*, etc.) in a friendlier fashion. |
| 6 | It also provides some help for examining source code and class layout. |
| 7 | |
| 8 | Here 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 Yee | 8b58b84 | 2001-03-01 13:56:16 +0000 | [diff] [blame] | 28 | __author__ = 'Ka-Ping Yee <ping@lfw.org>' |
| 29 | __date__ = '1 Jan 2001' |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 30 | |
Neil Schemenauer | f06f853 | 2002-03-23 23:51:04 +0000 | [diff] [blame] | 31 | import sys, os, types, string, re, dis, imp, tokenize, linecache |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 32 | |
| 33 | # ----------------------------------------------------------- type-checking |
| 34 | def 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 Peters | 28bc59f | 2001-09-16 08:40:16 +0000 | [diff] [blame] | 40 | return isinstance(object, types.ModuleType) |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 41 | |
| 42 | def 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 Peters | 28bc59f | 2001-09-16 08:40:16 +0000 | [diff] [blame] | 48 | return isinstance(object, types.ClassType) or hasattr(object, '__bases__') |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 49 | |
| 50 | def 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 Peters | 28bc59f | 2001-09-16 08:40:16 +0000 | [diff] [blame] | 59 | return isinstance(object, types.MethodType) |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 60 | |
Tim Peters | 536d226 | 2001-09-20 05:13:38 +0000 | [diff] [blame] | 61 | def ismethoddescriptor(object): |
Tim Peters | f1d90b9 | 2001-09-20 05:47:55 +0000 | [diff] [blame] | 62 | """Return true if the object is a method descriptor. |
| 63 | |
| 64 | But not if ismethod() or isclass() or isfunction() are true. |
Tim Peters | 536d226 | 2001-09-20 05:13:38 +0000 | [diff] [blame] | 65 | |
| 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 Peters | f1d90b9 | 2001-09-20 05:47:55 +0000 | [diff] [blame] | 71 | 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 Peters | 536d226 | 2001-09-20 05:13:38 +0000 | [diff] [blame] | 75 | return (hasattr(object, "__get__") |
| 76 | and not hasattr(object, "__set__") # else it's a data descriptor |
| 77 | and not ismethod(object) # mutual exclusion |
Tim Peters | f1d90b9 | 2001-09-20 05:47:55 +0000 | [diff] [blame] | 78 | and not isfunction(object) |
Tim Peters | 536d226 | 2001-09-20 05:13:38 +0000 | [diff] [blame] | 79 | and not isclass(object)) |
| 80 | |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 81 | def 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 Peters | 28bc59f | 2001-09-16 08:40:16 +0000 | [diff] [blame] | 92 | return isinstance(object, types.FunctionType) |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 93 | |
| 94 | def 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 Peters | 28bc59f | 2001-09-16 08:40:16 +0000 | [diff] [blame] | 102 | return isinstance(object, types.TracebackType) |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 103 | |
| 104 | def 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 Peters | 28bc59f | 2001-09-16 08:40:16 +0000 | [diff] [blame] | 120 | return isinstance(object, types.FrameType) |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 121 | |
| 122 | def 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 Peters | 28bc59f | 2001-09-16 08:40:16 +0000 | [diff] [blame] | 138 | return isinstance(object, types.CodeType) |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 139 | |
| 140 | def 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 Peters | 28bc59f | 2001-09-16 08:40:16 +0000 | [diff] [blame] | 147 | return isinstance(object, types.BuiltinFunctionType) |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 148 | |
| 149 | def isroutine(object): |
| 150 | """Return true if the object is any kind of function or method.""" |
Tim Peters | 536d226 | 2001-09-20 05:13:38 +0000 | [diff] [blame] | 151 | return (isbuiltin(object) |
| 152 | or isfunction(object) |
| 153 | or ismethod(object) |
| 154 | or ismethoddescriptor(object)) |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 155 | |
| 156 | def 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 Peters | 13b49d3 | 2001-09-23 02:00:29 +0000 | [diff] [blame] | 167 | def 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 Peters | 13b49d3 | 2001-09-23 02:00:29 +0000 | [diff] [blame] | 204 | homecls = getattr(obj, "__objclass__", None) |
| 205 | if homecls is None: |
Guido van Rossum | 687ae00 | 2001-10-15 22:03:32 +0000 | [diff] [blame] | 206 | # search the dicts. |
Tim Peters | 13b49d3 | 2001-09-23 02:00:29 +0000 | [diff] [blame] | 207 | 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 Peters | e0b2d7a | 2001-09-22 06:10:55 +0000 | [diff] [blame] | 237 | # ----------------------------------------------------------- class helpers |
| 238 | def _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 | |
| 246 | def 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 Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 255 | # -------------------------------------------------- source code extraction |
| 256 | def 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 | |
| 261 | def 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 Peters | 2400831 | 2002-03-17 18:56:20 +0000 | [diff] [blame] | 267 | try: |
| 268 | doc = object.__doc__ |
| 269 | except AttributeError: |
| 270 | return None |
Michael W. Hudson | 755f75e | 2002-05-20 17:29:46 +0000 | [diff] [blame] | 271 | if not isinstance(doc, types.StringTypes): |
Tim Peters | 2400831 | 2002-03-17 18:56:20 +0000 | [diff] [blame] | 272 | return None |
| 273 | try: |
| 274 | lines = string.split(string.expandtabs(doc), '\n') |
| 275 | except UnicodeError: |
| 276 | return None |
| 277 | else: |
Ka-Ping Yee | a59ef7b | 2002-11-30 03:53:15 +0000 | [diff] [blame] | 278 | # Find minimum indentation of any non-blank lines after first line. |
| 279 | margin = sys.maxint |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 280 | for line in lines[1:]: |
| 281 | content = len(string.lstrip(line)) |
Ka-Ping Yee | a59ef7b | 2002-11-30 03:53:15 +0000 | [diff] [blame] | 282 | if content: |
| 283 | indent = len(line) - content |
| 284 | margin = min(margin, indent) |
| 285 | # Remove indentation. |
| 286 | if lines: |
| 287 | lines[0] = lines[0].lstrip() |
| 288 | if margin < sys.maxint: |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 289 | for i in range(1, len(lines)): lines[i] = lines[i][margin:] |
Ka-Ping Yee | a59ef7b | 2002-11-30 03:53:15 +0000 | [diff] [blame] | 290 | # Remove any trailing or leading blank lines. |
| 291 | while lines and not lines[-1]: |
| 292 | lines.pop() |
| 293 | while lines and not lines[0]: |
| 294 | lines.pop(0) |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 295 | return string.join(lines, '\n') |
| 296 | |
| 297 | def getfile(object): |
Ka-Ping Yee | c113c24 | 2001-03-02 02:08:53 +0000 | [diff] [blame] | 298 | """Work out which source or compiled file an object was defined in.""" |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 299 | if ismodule(object): |
| 300 | if hasattr(object, '__file__'): |
| 301 | return object.__file__ |
| 302 | raise TypeError, 'arg is a built-in module' |
| 303 | if isclass(object): |
Ka-Ping Yee | c99e0f1 | 2001-04-13 12:10:40 +0000 | [diff] [blame] | 304 | object = sys.modules.get(object.__module__) |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 305 | if hasattr(object, '__file__'): |
| 306 | return object.__file__ |
| 307 | raise TypeError, 'arg is a built-in class' |
| 308 | if ismethod(object): |
| 309 | object = object.im_func |
| 310 | if isfunction(object): |
| 311 | object = object.func_code |
| 312 | if istraceback(object): |
| 313 | object = object.tb_frame |
| 314 | if isframe(object): |
| 315 | object = object.f_code |
| 316 | if iscode(object): |
| 317 | return object.co_filename |
| 318 | raise TypeError, 'arg is not a module, class, method, ' \ |
| 319 | 'function, traceback, frame, or code object' |
| 320 | |
Ka-Ping Yee | 4d6fc7f | 2001-04-10 11:43:00 +0000 | [diff] [blame] | 321 | def getmoduleinfo(path): |
| 322 | """Get the module name, suffix, mode, and module type for a given file.""" |
| 323 | filename = os.path.basename(path) |
| 324 | suffixes = map(lambda (suffix, mode, mtype): |
| 325 | (-len(suffix), suffix, mode, mtype), imp.get_suffixes()) |
| 326 | suffixes.sort() # try longest suffixes first, in case they overlap |
| 327 | for neglen, suffix, mode, mtype in suffixes: |
| 328 | if filename[neglen:] == suffix: |
| 329 | return filename[:neglen], suffix, mode, mtype |
| 330 | |
| 331 | def getmodulename(path): |
| 332 | """Return the module name for a given file, or None.""" |
| 333 | info = getmoduleinfo(path) |
| 334 | if info: return info[0] |
| 335 | |
Ka-Ping Yee | c113c24 | 2001-03-02 02:08:53 +0000 | [diff] [blame] | 336 | def getsourcefile(object): |
| 337 | """Return the Python source file an object was defined in, if it exists.""" |
| 338 | filename = getfile(object) |
| 339 | if string.lower(filename[-4:]) in ['.pyc', '.pyo']: |
| 340 | filename = filename[:-4] + '.py' |
Ka-Ping Yee | 4eb0c00 | 2001-03-02 05:50:34 +0000 | [diff] [blame] | 341 | for suffix, mode, kind in imp.get_suffixes(): |
| 342 | if 'b' in mode and string.lower(filename[-len(suffix):]) == suffix: |
| 343 | # Looks like a binary file. We want to only return a text file. |
| 344 | return None |
| 345 | if os.path.exists(filename): |
Ka-Ping Yee | c113c24 | 2001-03-02 02:08:53 +0000 | [diff] [blame] | 346 | return filename |
| 347 | |
| 348 | def getabsfile(object): |
Ka-Ping Yee | 4eb0c00 | 2001-03-02 05:50:34 +0000 | [diff] [blame] | 349 | """Return an absolute path to the source or compiled file for an object. |
Ka-Ping Yee | c113c24 | 2001-03-02 02:08:53 +0000 | [diff] [blame] | 350 | |
Ka-Ping Yee | 4eb0c00 | 2001-03-02 05:50:34 +0000 | [diff] [blame] | 351 | The idea is for each object to have a unique origin, so this routine |
| 352 | normalizes the result as much as possible.""" |
| 353 | return os.path.normcase( |
| 354 | os.path.abspath(getsourcefile(object) or getfile(object))) |
Ka-Ping Yee | c113c24 | 2001-03-02 02:08:53 +0000 | [diff] [blame] | 355 | |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 356 | modulesbyfile = {} |
| 357 | |
| 358 | def getmodule(object): |
Ka-Ping Yee | 4eb0c00 | 2001-03-02 05:50:34 +0000 | [diff] [blame] | 359 | """Return the module an object was defined in, or None if not found.""" |
Ka-Ping Yee | 202c99b | 2001-04-13 09:15:08 +0000 | [diff] [blame] | 360 | if ismodule(object): |
| 361 | return object |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 362 | if isclass(object): |
Ka-Ping Yee | 8b58b84 | 2001-03-01 13:56:16 +0000 | [diff] [blame] | 363 | return sys.modules.get(object.__module__) |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 364 | try: |
Ka-Ping Yee | c113c24 | 2001-03-02 02:08:53 +0000 | [diff] [blame] | 365 | file = getabsfile(object) |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 366 | except TypeError: |
| 367 | return None |
Raymond Hettinger | 54f0222 | 2002-06-01 14:18:47 +0000 | [diff] [blame] | 368 | if file in modulesbyfile: |
Ka-Ping Yee | b38bbbd | 2003-03-28 16:29:50 +0000 | [diff] [blame] | 369 | return sys.modules.get(modulesbyfile[file]) |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 370 | for module in sys.modules.values(): |
| 371 | if hasattr(module, '__file__'): |
Ka-Ping Yee | c113c24 | 2001-03-02 02:08:53 +0000 | [diff] [blame] | 372 | modulesbyfile[getabsfile(module)] = module.__name__ |
Raymond Hettinger | 54f0222 | 2002-06-01 14:18:47 +0000 | [diff] [blame] | 373 | if file in modulesbyfile: |
Ka-Ping Yee | b38bbbd | 2003-03-28 16:29:50 +0000 | [diff] [blame] | 374 | return sys.modules.get(modulesbyfile[file]) |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 375 | main = sys.modules['__main__'] |
Ka-Ping Yee | 4eb0c00 | 2001-03-02 05:50:34 +0000 | [diff] [blame] | 376 | if hasattr(main, object.__name__): |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 377 | mainobject = getattr(main, object.__name__) |
Ka-Ping Yee | 4eb0c00 | 2001-03-02 05:50:34 +0000 | [diff] [blame] | 378 | if mainobject is object: |
| 379 | return main |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 380 | builtin = sys.modules['__builtin__'] |
Ka-Ping Yee | 4eb0c00 | 2001-03-02 05:50:34 +0000 | [diff] [blame] | 381 | if hasattr(builtin, object.__name__): |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 382 | builtinobject = getattr(builtin, object.__name__) |
Ka-Ping Yee | 4eb0c00 | 2001-03-02 05:50:34 +0000 | [diff] [blame] | 383 | if builtinobject is object: |
| 384 | return builtin |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 385 | |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 386 | def findsource(object): |
| 387 | """Return the entire source file and starting line number for an object. |
| 388 | |
| 389 | The argument may be a module, class, method, function, traceback, frame, |
| 390 | or code object. The source code is returned as a list of all the lines |
| 391 | in the file and the line number indexes a line in that list. An IOError |
| 392 | is raised if the source code cannot be retrieved.""" |
Neil Schemenauer | f06f853 | 2002-03-23 23:51:04 +0000 | [diff] [blame] | 393 | file = getsourcefile(object) or getfile(object) |
| 394 | lines = linecache.getlines(file) |
| 395 | if not lines: |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 396 | raise IOError, 'could not get source code' |
| 397 | |
| 398 | if ismodule(object): |
| 399 | return lines, 0 |
| 400 | |
| 401 | if isclass(object): |
| 402 | name = object.__name__ |
Ka-Ping Yee | a6e5971 | 2001-03-10 09:31:55 +0000 | [diff] [blame] | 403 | pat = re.compile(r'^\s*class\s*' + name + r'\b') |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 404 | for i in range(len(lines)): |
Ka-Ping Yee | a6e5971 | 2001-03-10 09:31:55 +0000 | [diff] [blame] | 405 | if pat.match(lines[i]): return lines, i |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 406 | else: raise IOError, 'could not find class definition' |
| 407 | |
| 408 | if ismethod(object): |
| 409 | object = object.im_func |
| 410 | if isfunction(object): |
| 411 | object = object.func_code |
| 412 | if istraceback(object): |
| 413 | object = object.tb_frame |
| 414 | if isframe(object): |
| 415 | object = object.f_code |
| 416 | if iscode(object): |
Ka-Ping Yee | 4eb0c00 | 2001-03-02 05:50:34 +0000 | [diff] [blame] | 417 | if not hasattr(object, 'co_firstlineno'): |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 418 | raise IOError, 'could not find function definition' |
Ka-Ping Yee | 4eb0c00 | 2001-03-02 05:50:34 +0000 | [diff] [blame] | 419 | lnum = object.co_firstlineno - 1 |
Raymond Hettinger | 2d375f7 | 2003-01-14 02:19:36 +0000 | [diff] [blame] | 420 | pat = re.compile(r'^(\s*def\s)|(.*\slambda(:|\s))') |
Ka-Ping Yee | 4eb0c00 | 2001-03-02 05:50:34 +0000 | [diff] [blame] | 421 | while lnum > 0: |
Ka-Ping Yee | a6e5971 | 2001-03-10 09:31:55 +0000 | [diff] [blame] | 422 | if pat.match(lines[lnum]): break |
Ka-Ping Yee | 4eb0c00 | 2001-03-02 05:50:34 +0000 | [diff] [blame] | 423 | lnum = lnum - 1 |
| 424 | return lines, lnum |
Neal Norwitz | 8a11f5d | 2002-03-13 03:14:26 +0000 | [diff] [blame] | 425 | raise IOError, 'could not find code object' |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 426 | |
| 427 | def getcomments(object): |
Jeremy Hylton | b4c17c8 | 2002-03-28 23:01:56 +0000 | [diff] [blame] | 428 | """Get lines of comments immediately preceding an object's source code. |
| 429 | |
| 430 | Returns None when source can't be found. |
| 431 | """ |
| 432 | try: |
| 433 | lines, lnum = findsource(object) |
| 434 | except (IOError, TypeError): |
| 435 | return None |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 436 | |
| 437 | if ismodule(object): |
| 438 | # Look for a comment block at the top of the file. |
| 439 | start = 0 |
Ka-Ping Yee | b910efe | 2001-04-12 13:17:17 +0000 | [diff] [blame] | 440 | if lines and lines[0][:2] == '#!': start = 1 |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 441 | while start < len(lines) and string.strip(lines[start]) in ['', '#']: |
| 442 | start = start + 1 |
Ka-Ping Yee | b910efe | 2001-04-12 13:17:17 +0000 | [diff] [blame] | 443 | if start < len(lines) and lines[start][:1] == '#': |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 444 | comments = [] |
| 445 | end = start |
| 446 | while end < len(lines) and lines[end][:1] == '#': |
| 447 | comments.append(string.expandtabs(lines[end])) |
| 448 | end = end + 1 |
| 449 | return string.join(comments, '') |
| 450 | |
| 451 | # Look for a preceding block of comments at the same indentation. |
| 452 | elif lnum > 0: |
| 453 | indent = indentsize(lines[lnum]) |
| 454 | end = lnum - 1 |
| 455 | if end >= 0 and string.lstrip(lines[end])[:1] == '#' and \ |
| 456 | indentsize(lines[end]) == indent: |
| 457 | comments = [string.lstrip(string.expandtabs(lines[end]))] |
| 458 | if end > 0: |
| 459 | end = end - 1 |
| 460 | comment = string.lstrip(string.expandtabs(lines[end])) |
| 461 | while comment[:1] == '#' and indentsize(lines[end]) == indent: |
| 462 | comments[:0] = [comment] |
| 463 | end = end - 1 |
| 464 | if end < 0: break |
| 465 | comment = string.lstrip(string.expandtabs(lines[end])) |
| 466 | while comments and string.strip(comments[0]) == '#': |
| 467 | comments[:1] = [] |
| 468 | while comments and string.strip(comments[-1]) == '#': |
| 469 | comments[-1:] = [] |
| 470 | return string.join(comments, '') |
| 471 | |
| 472 | class ListReader: |
| 473 | """Provide a readline() method to return lines from a list of strings.""" |
| 474 | def __init__(self, lines): |
| 475 | self.lines = lines |
| 476 | self.index = 0 |
| 477 | |
| 478 | def readline(self): |
| 479 | i = self.index |
| 480 | if i < len(self.lines): |
| 481 | self.index = i + 1 |
| 482 | return self.lines[i] |
| 483 | else: return '' |
| 484 | |
Tim Peters | 4efb6e9 | 2001-06-29 23:51:08 +0000 | [diff] [blame] | 485 | class EndOfBlock(Exception): pass |
| 486 | |
| 487 | class BlockFinder: |
| 488 | """Provide a tokeneater() method to detect the end of a code block.""" |
| 489 | def __init__(self): |
| 490 | self.indent = 0 |
| 491 | self.started = 0 |
| 492 | self.last = 0 |
| 493 | |
| 494 | def tokeneater(self, type, token, (srow, scol), (erow, ecol), line): |
| 495 | if not self.started: |
| 496 | if type == tokenize.NAME: self.started = 1 |
| 497 | elif type == tokenize.NEWLINE: |
| 498 | self.last = srow |
| 499 | elif type == tokenize.INDENT: |
| 500 | self.indent = self.indent + 1 |
| 501 | elif type == tokenize.DEDENT: |
| 502 | self.indent = self.indent - 1 |
| 503 | if self.indent == 0: raise EndOfBlock, self.last |
Raymond Hettinger | 2e7b748 | 2003-01-19 13:21:20 +0000 | [diff] [blame] | 504 | elif type == tokenize.NAME and scol == 0: |
| 505 | raise EndOfBlock, self.last |
Tim Peters | 4efb6e9 | 2001-06-29 23:51:08 +0000 | [diff] [blame] | 506 | |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 507 | def getblock(lines): |
| 508 | """Extract the block of code at the top of the given list of lines.""" |
Tim Peters | 4efb6e9 | 2001-06-29 23:51:08 +0000 | [diff] [blame] | 509 | try: |
| 510 | tokenize.tokenize(ListReader(lines).readline, BlockFinder().tokeneater) |
| 511 | except EndOfBlock, eob: |
| 512 | return lines[:eob.args[0]] |
Raymond Hettinger | 2d375f7 | 2003-01-14 02:19:36 +0000 | [diff] [blame] | 513 | # Fooling the indent/dedent logic implies a one-line definition |
| 514 | return lines[:1] |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 515 | |
| 516 | def getsourcelines(object): |
| 517 | """Return a list of source lines and starting line number for an object. |
| 518 | |
| 519 | The argument may be a module, class, method, function, traceback, frame, |
| 520 | or code object. The source code is returned as a list of the lines |
| 521 | corresponding to the object and the line number indicates where in the |
| 522 | original source file the first line of code was found. An IOError is |
| 523 | raised if the source code cannot be retrieved.""" |
| 524 | lines, lnum = findsource(object) |
| 525 | |
| 526 | if ismodule(object): return lines, 0 |
| 527 | else: return getblock(lines[lnum:]), lnum + 1 |
| 528 | |
| 529 | def getsource(object): |
| 530 | """Return the text of the source code for an object. |
| 531 | |
| 532 | The argument may be a module, class, method, function, traceback, frame, |
| 533 | or code object. The source code is returned as a single string. An |
| 534 | IOError is raised if the source code cannot be retrieved.""" |
| 535 | lines, lnum = getsourcelines(object) |
| 536 | return string.join(lines, '') |
| 537 | |
| 538 | # --------------------------------------------------- class tree extraction |
| 539 | def walktree(classes, children, parent): |
| 540 | """Recursive helper function for getclasstree().""" |
| 541 | results = [] |
| 542 | classes.sort(lambda a, b: cmp(a.__name__, b.__name__)) |
| 543 | for c in classes: |
| 544 | results.append((c, c.__bases__)) |
Raymond Hettinger | 54f0222 | 2002-06-01 14:18:47 +0000 | [diff] [blame] | 545 | if c in children: |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 546 | results.append(walktree(children[c], children, c)) |
| 547 | return results |
| 548 | |
| 549 | def getclasstree(classes, unique=0): |
| 550 | """Arrange the given list of classes into a hierarchy of nested lists. |
| 551 | |
| 552 | Where a nested list appears, it contains classes derived from the class |
| 553 | whose entry immediately precedes the list. Each entry is a 2-tuple |
| 554 | containing a class and a tuple of its base classes. If the 'unique' |
| 555 | argument is true, exactly one entry appears in the returned structure |
| 556 | for each class in the given list. Otherwise, classes using multiple |
| 557 | inheritance and their descendants will appear multiple times.""" |
| 558 | children = {} |
| 559 | roots = [] |
| 560 | for c in classes: |
| 561 | if c.__bases__: |
| 562 | for parent in c.__bases__: |
Raymond Hettinger | 54f0222 | 2002-06-01 14:18:47 +0000 | [diff] [blame] | 563 | if not parent in children: |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 564 | children[parent] = [] |
| 565 | children[parent].append(c) |
| 566 | if unique and parent in classes: break |
| 567 | elif c not in roots: |
| 568 | roots.append(c) |
Raymond Hettinger | e0d4972 | 2002-06-02 18:55:56 +0000 | [diff] [blame] | 569 | for parent in children: |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 570 | if parent not in classes: |
| 571 | roots.append(parent) |
| 572 | return walktree(roots, children, None) |
| 573 | |
| 574 | # ------------------------------------------------ argument list extraction |
| 575 | # These constants are from Python's compile.h. |
| 576 | CO_OPTIMIZED, CO_NEWLOCALS, CO_VARARGS, CO_VARKEYWORDS = 1, 2, 4, 8 |
| 577 | |
| 578 | def getargs(co): |
| 579 | """Get information about the arguments accepted by a code object. |
| 580 | |
| 581 | Three things are returned: (args, varargs, varkw), where 'args' is |
| 582 | a list of argument names (possibly containing nested lists), and |
| 583 | 'varargs' and 'varkw' are the names of the * and ** arguments or None.""" |
| 584 | if not iscode(co): raise TypeError, 'arg is not a code object' |
| 585 | |
| 586 | code = co.co_code |
| 587 | nargs = co.co_argcount |
| 588 | names = co.co_varnames |
| 589 | args = list(names[:nargs]) |
| 590 | step = 0 |
| 591 | |
| 592 | # The following acrobatics are for anonymous (tuple) arguments. |
| 593 | for i in range(nargs): |
| 594 | if args[i][:1] in ['', '.']: |
| 595 | stack, remain, count = [], [], [] |
| 596 | while step < len(code): |
| 597 | op = ord(code[step]) |
| 598 | step = step + 1 |
| 599 | if op >= dis.HAVE_ARGUMENT: |
| 600 | opname = dis.opname[op] |
| 601 | value = ord(code[step]) + ord(code[step+1])*256 |
| 602 | step = step + 2 |
| 603 | if opname in ['UNPACK_TUPLE', 'UNPACK_SEQUENCE']: |
| 604 | remain.append(value) |
| 605 | count.append(value) |
| 606 | elif opname == 'STORE_FAST': |
| 607 | stack.append(names[value]) |
| 608 | remain[-1] = remain[-1] - 1 |
| 609 | while remain[-1] == 0: |
| 610 | remain.pop() |
| 611 | size = count.pop() |
| 612 | stack[-size:] = [stack[-size:]] |
| 613 | if not remain: break |
| 614 | remain[-1] = remain[-1] - 1 |
| 615 | if not remain: break |
| 616 | args[i] = stack[0] |
| 617 | |
| 618 | varargs = None |
| 619 | if co.co_flags & CO_VARARGS: |
| 620 | varargs = co.co_varnames[nargs] |
| 621 | nargs = nargs + 1 |
| 622 | varkw = None |
| 623 | if co.co_flags & CO_VARKEYWORDS: |
| 624 | varkw = co.co_varnames[nargs] |
| 625 | return args, varargs, varkw |
| 626 | |
| 627 | def getargspec(func): |
| 628 | """Get the names and default values of a function's arguments. |
| 629 | |
| 630 | A tuple of four things is returned: (args, varargs, varkw, defaults). |
| 631 | 'args' is a list of the argument names (it may contain nested lists). |
| 632 | 'varargs' and 'varkw' are the names of the * and ** arguments or None. |
| 633 | 'defaults' is an n-tuple of the default values of the last n arguments.""" |
| 634 | if not isfunction(func): raise TypeError, 'arg is not a Python function' |
| 635 | args, varargs, varkw = getargs(func.func_code) |
| 636 | return args, varargs, varkw, func.func_defaults |
| 637 | |
| 638 | def getargvalues(frame): |
| 639 | """Get information about arguments passed into a particular frame. |
| 640 | |
| 641 | A tuple of four things is returned: (args, varargs, varkw, locals). |
| 642 | 'args' is a list of the argument names (it may contain nested lists). |
| 643 | 'varargs' and 'varkw' are the names of the * and ** arguments or None. |
| 644 | 'locals' is the locals dictionary of the given frame.""" |
| 645 | args, varargs, varkw = getargs(frame.f_code) |
| 646 | return args, varargs, varkw, frame.f_locals |
| 647 | |
| 648 | def joinseq(seq): |
| 649 | if len(seq) == 1: |
| 650 | return '(' + seq[0] + ',)' |
| 651 | else: |
| 652 | return '(' + string.join(seq, ', ') + ')' |
| 653 | |
| 654 | def strseq(object, convert, join=joinseq): |
| 655 | """Recursively walk a sequence, stringifying each element.""" |
| 656 | if type(object) in [types.ListType, types.TupleType]: |
| 657 | return join(map(lambda o, c=convert, j=join: strseq(o, c, j), object)) |
| 658 | else: |
| 659 | return convert(object) |
| 660 | |
| 661 | def formatargspec(args, varargs=None, varkw=None, defaults=None, |
| 662 | formatarg=str, |
| 663 | formatvarargs=lambda name: '*' + name, |
| 664 | formatvarkw=lambda name: '**' + name, |
| 665 | formatvalue=lambda value: '=' + repr(value), |
| 666 | join=joinseq): |
| 667 | """Format an argument spec from the 4 values returned by getargspec. |
| 668 | |
| 669 | The first four arguments are (args, varargs, varkw, defaults). The |
| 670 | other four arguments are the corresponding optional formatting functions |
| 671 | that are called to turn names and values into strings. The ninth |
| 672 | argument is an optional function to format the sequence of arguments.""" |
| 673 | specs = [] |
| 674 | if defaults: |
| 675 | firstdefault = len(args) - len(defaults) |
| 676 | for i in range(len(args)): |
| 677 | spec = strseq(args[i], formatarg, join) |
| 678 | if defaults and i >= firstdefault: |
| 679 | spec = spec + formatvalue(defaults[i - firstdefault]) |
| 680 | specs.append(spec) |
Raymond Hettinger | 936654b | 2002-06-01 03:06:31 +0000 | [diff] [blame] | 681 | if varargs is not None: |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 682 | specs.append(formatvarargs(varargs)) |
Raymond Hettinger | 936654b | 2002-06-01 03:06:31 +0000 | [diff] [blame] | 683 | if varkw is not None: |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 684 | specs.append(formatvarkw(varkw)) |
| 685 | return '(' + string.join(specs, ', ') + ')' |
| 686 | |
| 687 | def formatargvalues(args, varargs, varkw, locals, |
| 688 | formatarg=str, |
| 689 | formatvarargs=lambda name: '*' + name, |
| 690 | formatvarkw=lambda name: '**' + name, |
| 691 | formatvalue=lambda value: '=' + repr(value), |
| 692 | join=joinseq): |
| 693 | """Format an argument spec from the 4 values returned by getargvalues. |
| 694 | |
| 695 | The first four arguments are (args, varargs, varkw, locals). The |
| 696 | next four arguments are the corresponding optional formatting functions |
| 697 | that are called to turn names and values into strings. The ninth |
| 698 | argument is an optional function to format the sequence of arguments.""" |
| 699 | def convert(name, locals=locals, |
| 700 | formatarg=formatarg, formatvalue=formatvalue): |
| 701 | return formatarg(name) + formatvalue(locals[name]) |
| 702 | specs = [] |
| 703 | for i in range(len(args)): |
| 704 | specs.append(strseq(args[i], convert, join)) |
| 705 | if varargs: |
| 706 | specs.append(formatvarargs(varargs) + formatvalue(locals[varargs])) |
| 707 | if varkw: |
| 708 | specs.append(formatvarkw(varkw) + formatvalue(locals[varkw])) |
| 709 | return '(' + string.join(specs, ', ') + ')' |
| 710 | |
| 711 | # -------------------------------------------------- stack frame extraction |
| 712 | def getframeinfo(frame, context=1): |
| 713 | """Get information about a frame or traceback object. |
| 714 | |
| 715 | A tuple of five things is returned: the filename, the line number of |
| 716 | the current line, the function name, a list of lines of context from |
| 717 | the source code, and the index of the current line within that list. |
| 718 | The optional second argument specifies the number of lines of context |
| 719 | to return, which are centered around the current line.""" |
| 720 | if istraceback(frame): |
| 721 | frame = frame.tb_frame |
| 722 | if not isframe(frame): |
| 723 | raise TypeError, 'arg is not a frame or traceback object' |
| 724 | |
Neil Schemenauer | f06f853 | 2002-03-23 23:51:04 +0000 | [diff] [blame] | 725 | filename = getsourcefile(frame) or getfile(frame) |
Michael W. Hudson | dd32a91 | 2002-08-15 14:59:02 +0000 | [diff] [blame] | 726 | lineno = frame.f_lineno |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 727 | if context > 0: |
Guido van Rossum | 54e54c6 | 2001-09-04 19:14:14 +0000 | [diff] [blame] | 728 | start = lineno - 1 - context//2 |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 729 | try: |
| 730 | lines, lnum = findsource(frame) |
Ka-Ping Yee | 4eb0c00 | 2001-03-02 05:50:34 +0000 | [diff] [blame] | 731 | except IOError: |
| 732 | lines = index = None |
| 733 | else: |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 734 | start = max(start, 1) |
| 735 | start = min(start, len(lines) - context) |
| 736 | lines = lines[start:start+context] |
Ka-Ping Yee | 59ade08 | 2001-03-01 03:55:35 +0000 | [diff] [blame] | 737 | index = lineno - 1 - start |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 738 | else: |
| 739 | lines = index = None |
| 740 | |
Ka-Ping Yee | 59ade08 | 2001-03-01 03:55:35 +0000 | [diff] [blame] | 741 | return (filename, lineno, frame.f_code.co_name, lines, index) |
| 742 | |
| 743 | def getlineno(frame): |
| 744 | """Get the line number from a frame object, allowing for optimization.""" |
Michael W. Hudson | dd32a91 | 2002-08-15 14:59:02 +0000 | [diff] [blame] | 745 | # FrameType.f_lineno is now a descriptor that grovels co_lnotab |
| 746 | return frame.f_lineno |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 747 | |
| 748 | def getouterframes(frame, context=1): |
| 749 | """Get a list of records for a frame and all higher (calling) frames. |
| 750 | |
| 751 | Each record contains a frame object, filename, line number, function |
| 752 | name, a list of lines of context, and index within the context.""" |
| 753 | framelist = [] |
| 754 | while frame: |
| 755 | framelist.append((frame,) + getframeinfo(frame, context)) |
| 756 | frame = frame.f_back |
| 757 | return framelist |
| 758 | |
| 759 | def getinnerframes(tb, context=1): |
| 760 | """Get a list of records for a traceback's frame and all lower frames. |
| 761 | |
| 762 | Each record contains a frame object, filename, line number, function |
| 763 | name, a list of lines of context, and index within the context.""" |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 764 | framelist = [] |
| 765 | while tb: |
| 766 | framelist.append((tb.tb_frame,) + getframeinfo(tb, context)) |
| 767 | tb = tb.tb_next |
| 768 | return framelist |
| 769 | |
| 770 | def currentframe(): |
| 771 | """Return the frame object for the caller's stack frame.""" |
| 772 | try: |
Skip Montanaro | a959a36 | 2002-03-25 21:37:54 +0000 | [diff] [blame] | 773 | 1/0 |
| 774 | except ZeroDivisionError: |
Fred Drake | d451ec1 | 2002-04-26 02:29:55 +0000 | [diff] [blame] | 775 | return sys.exc_info()[2].tb_frame.f_back |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 776 | |
| 777 | if hasattr(sys, '_getframe'): currentframe = sys._getframe |
| 778 | |
| 779 | def stack(context=1): |
| 780 | """Return a list of records for the stack above the caller's frame.""" |
| 781 | return getouterframes(currentframe().f_back, context) |
| 782 | |
| 783 | def trace(context=1): |
Tim Peters | 85ba673 | 2001-02-28 08:26:44 +0000 | [diff] [blame] | 784 | """Return a list of records for the stack below the current exception.""" |
Fred Drake | d451ec1 | 2002-04-26 02:29:55 +0000 | [diff] [blame] | 785 | return getinnerframes(sys.exc_info()[2], context) |