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 |
Raymond Hettinger | 3375fc5 | 2003-12-01 20:12:15 +0000 | [diff] [blame] | 32 | from operator import attrgetter |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 33 | |
| 34 | # ----------------------------------------------------------- type-checking |
| 35 | def ismodule(object): |
| 36 | """Return true if the object is a module. |
| 37 | |
| 38 | Module objects provide these attributes: |
| 39 | __doc__ documentation string |
| 40 | __file__ filename (missing for built-in modules)""" |
Tim Peters | 28bc59f | 2001-09-16 08:40:16 +0000 | [diff] [blame] | 41 | return isinstance(object, types.ModuleType) |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 42 | |
| 43 | def isclass(object): |
| 44 | """Return true if the object is a class. |
| 45 | |
| 46 | Class objects provide these attributes: |
| 47 | __doc__ documentation string |
| 48 | __module__ name of module in which this class was defined""" |
Tim Peters | 28bc59f | 2001-09-16 08:40:16 +0000 | [diff] [blame] | 49 | return isinstance(object, types.ClassType) or hasattr(object, '__bases__') |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 50 | |
| 51 | def ismethod(object): |
| 52 | """Return true if the object is an instance method. |
| 53 | |
| 54 | Instance method objects provide these attributes: |
| 55 | __doc__ documentation string |
| 56 | __name__ name with which this method was defined |
| 57 | im_class class object in which this method belongs |
| 58 | im_func function object containing implementation of method |
| 59 | im_self instance to which this method is bound, or None""" |
Tim Peters | 28bc59f | 2001-09-16 08:40:16 +0000 | [diff] [blame] | 60 | return isinstance(object, types.MethodType) |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 61 | |
Tim Peters | 536d226 | 2001-09-20 05:13:38 +0000 | [diff] [blame] | 62 | def ismethoddescriptor(object): |
Tim Peters | f1d90b9 | 2001-09-20 05:47:55 +0000 | [diff] [blame] | 63 | """Return true if the object is a method descriptor. |
| 64 | |
| 65 | But not if ismethod() or isclass() or isfunction() are true. |
Tim Peters | 536d226 | 2001-09-20 05:13:38 +0000 | [diff] [blame] | 66 | |
| 67 | This is new in Python 2.2, and, for example, is true of int.__add__. |
| 68 | An object passing this test has a __get__ attribute but not a __set__ |
| 69 | attribute, but beyond that the set of attributes varies. __name__ is |
| 70 | usually sensible, and __doc__ often is. |
| 71 | |
Tim Peters | f1d90b9 | 2001-09-20 05:47:55 +0000 | [diff] [blame] | 72 | Methods implemented via descriptors that also pass one of the other |
| 73 | tests return false from the ismethoddescriptor() test, simply because |
| 74 | the other tests promise more -- you can, e.g., count on having the |
| 75 | im_func attribute (etc) when an object passes ismethod().""" |
Tim Peters | 536d226 | 2001-09-20 05:13:38 +0000 | [diff] [blame] | 76 | return (hasattr(object, "__get__") |
| 77 | and not hasattr(object, "__set__") # else it's a data descriptor |
| 78 | and not ismethod(object) # mutual exclusion |
Tim Peters | f1d90b9 | 2001-09-20 05:47:55 +0000 | [diff] [blame] | 79 | and not isfunction(object) |
Tim Peters | 536d226 | 2001-09-20 05:13:38 +0000 | [diff] [blame] | 80 | and not isclass(object)) |
| 81 | |
Martin v. Löwis | e59e2ba | 2003-05-03 09:09:02 +0000 | [diff] [blame] | 82 | def isdatadescriptor(object): |
| 83 | """Return true if the object is a data descriptor. |
| 84 | |
| 85 | Data descriptors have both a __get__ and a __set__ attribute. Examples are |
| 86 | properties (defined in Python) and getsets and members (defined in C). |
| 87 | Typically, data descriptors will also have __name__ and __doc__ attributes |
| 88 | (properties, getsets, and members have both of these attributes), but this |
| 89 | is not guaranteed.""" |
| 90 | return (hasattr(object, "__set__") and hasattr(object, "__get__")) |
| 91 | |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 92 | def isfunction(object): |
| 93 | """Return true if the object is a user-defined function. |
| 94 | |
| 95 | Function objects provide these attributes: |
| 96 | __doc__ documentation string |
| 97 | __name__ name with which this function was defined |
| 98 | func_code code object containing compiled function bytecode |
| 99 | func_defaults tuple of any default values for arguments |
| 100 | func_doc (same as __doc__) |
| 101 | func_globals global namespace in which this function was defined |
| 102 | func_name (same as __name__)""" |
Tim Peters | 28bc59f | 2001-09-16 08:40:16 +0000 | [diff] [blame] | 103 | return isinstance(object, types.FunctionType) |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 104 | |
| 105 | def istraceback(object): |
| 106 | """Return true if the object is a traceback. |
| 107 | |
| 108 | Traceback objects provide these attributes: |
| 109 | tb_frame frame object at this level |
| 110 | tb_lasti index of last attempted instruction in bytecode |
| 111 | tb_lineno current line number in Python source code |
| 112 | tb_next next inner traceback object (called by this level)""" |
Tim Peters | 28bc59f | 2001-09-16 08:40:16 +0000 | [diff] [blame] | 113 | return isinstance(object, types.TracebackType) |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 114 | |
| 115 | def isframe(object): |
| 116 | """Return true if the object is a frame object. |
| 117 | |
| 118 | Frame objects provide these attributes: |
| 119 | f_back next outer frame object (this frame's caller) |
| 120 | f_builtins built-in namespace seen by this frame |
| 121 | f_code code object being executed in this frame |
| 122 | f_exc_traceback traceback if raised in this frame, or None |
| 123 | f_exc_type exception type if raised in this frame, or None |
| 124 | f_exc_value exception value if raised in this frame, or None |
| 125 | f_globals global namespace seen by this frame |
| 126 | f_lasti index of last attempted instruction in bytecode |
| 127 | f_lineno current line number in Python source code |
| 128 | f_locals local namespace seen by this frame |
| 129 | f_restricted 0 or 1 if frame is in restricted execution mode |
| 130 | f_trace tracing function for this frame, or None""" |
Tim Peters | 28bc59f | 2001-09-16 08:40:16 +0000 | [diff] [blame] | 131 | return isinstance(object, types.FrameType) |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 132 | |
| 133 | def iscode(object): |
| 134 | """Return true if the object is a code object. |
| 135 | |
| 136 | Code objects provide these attributes: |
| 137 | co_argcount number of arguments (not including * or ** args) |
| 138 | co_code string of raw compiled bytecode |
| 139 | co_consts tuple of constants used in the bytecode |
| 140 | co_filename name of file in which this code object was created |
| 141 | co_firstlineno number of first line in Python source code |
| 142 | co_flags bitmap: 1=optimized | 2=newlocals | 4=*arg | 8=**arg |
| 143 | co_lnotab encoded mapping of line numbers to bytecode indices |
| 144 | co_name name with which this code object was defined |
| 145 | co_names tuple of names of local variables |
| 146 | co_nlocals number of local variables |
| 147 | co_stacksize virtual machine stack space required |
| 148 | co_varnames tuple of names of arguments and local variables""" |
Tim Peters | 28bc59f | 2001-09-16 08:40:16 +0000 | [diff] [blame] | 149 | return isinstance(object, types.CodeType) |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 150 | |
| 151 | def isbuiltin(object): |
| 152 | """Return true if the object is a built-in function or method. |
| 153 | |
| 154 | Built-in functions and methods provide these attributes: |
| 155 | __doc__ documentation string |
| 156 | __name__ original name of this function or method |
| 157 | __self__ instance to which a method is bound, or None""" |
Tim Peters | 28bc59f | 2001-09-16 08:40:16 +0000 | [diff] [blame] | 158 | return isinstance(object, types.BuiltinFunctionType) |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 159 | |
| 160 | def isroutine(object): |
| 161 | """Return true if the object is any kind of function or method.""" |
Tim Peters | 536d226 | 2001-09-20 05:13:38 +0000 | [diff] [blame] | 162 | return (isbuiltin(object) |
| 163 | or isfunction(object) |
| 164 | or ismethod(object) |
| 165 | or ismethoddescriptor(object)) |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 166 | |
| 167 | def getmembers(object, predicate=None): |
| 168 | """Return all members of an object as (name, value) pairs sorted by name. |
| 169 | Optionally, only return members that satisfy a given predicate.""" |
| 170 | results = [] |
| 171 | for key in dir(object): |
| 172 | value = getattr(object, key) |
| 173 | if not predicate or predicate(value): |
| 174 | results.append((key, value)) |
| 175 | results.sort() |
| 176 | return results |
| 177 | |
Tim Peters | 13b49d3 | 2001-09-23 02:00:29 +0000 | [diff] [blame] | 178 | def classify_class_attrs(cls): |
| 179 | """Return list of attribute-descriptor tuples. |
| 180 | |
| 181 | For each name in dir(cls), the return list contains a 4-tuple |
| 182 | with these elements: |
| 183 | |
| 184 | 0. The name (a string). |
| 185 | |
| 186 | 1. The kind of attribute this is, one of these strings: |
| 187 | 'class method' created via classmethod() |
| 188 | 'static method' created via staticmethod() |
| 189 | 'property' created via property() |
| 190 | 'method' any other flavor of method |
| 191 | 'data' not a method |
| 192 | |
| 193 | 2. The class which defined this attribute (a class). |
| 194 | |
| 195 | 3. The object as obtained directly from the defining class's |
| 196 | __dict__, not via getattr. This is especially important for |
| 197 | data attributes: C.data is just a data object, but |
| 198 | C.__dict__['data'] may be a data descriptor with additional |
| 199 | info, like a __doc__ string. |
| 200 | """ |
| 201 | |
| 202 | mro = getmro(cls) |
| 203 | names = dir(cls) |
| 204 | result = [] |
| 205 | for name in names: |
| 206 | # Get the object associated with the name. |
| 207 | # Getting an obj from the __dict__ sometimes reveals more than |
| 208 | # using getattr. Static and class methods are dramatic examples. |
| 209 | if name in cls.__dict__: |
| 210 | obj = cls.__dict__[name] |
| 211 | else: |
| 212 | obj = getattr(cls, name) |
| 213 | |
| 214 | # Figure out where it was defined. |
Tim Peters | 13b49d3 | 2001-09-23 02:00:29 +0000 | [diff] [blame] | 215 | homecls = getattr(obj, "__objclass__", None) |
| 216 | if homecls is None: |
Guido van Rossum | 687ae00 | 2001-10-15 22:03:32 +0000 | [diff] [blame] | 217 | # search the dicts. |
Tim Peters | 13b49d3 | 2001-09-23 02:00:29 +0000 | [diff] [blame] | 218 | for base in mro: |
| 219 | if name in base.__dict__: |
| 220 | homecls = base |
| 221 | break |
| 222 | |
| 223 | # Get the object again, in order to get it from the defining |
| 224 | # __dict__ instead of via getattr (if possible). |
| 225 | if homecls is not None and name in homecls.__dict__: |
| 226 | obj = homecls.__dict__[name] |
| 227 | |
| 228 | # Also get the object via getattr. |
| 229 | obj_via_getattr = getattr(cls, name) |
| 230 | |
| 231 | # Classify the object. |
| 232 | if isinstance(obj, staticmethod): |
| 233 | kind = "static method" |
| 234 | elif isinstance(obj, classmethod): |
| 235 | kind = "class method" |
| 236 | elif isinstance(obj, property): |
| 237 | kind = "property" |
| 238 | elif (ismethod(obj_via_getattr) or |
| 239 | ismethoddescriptor(obj_via_getattr)): |
| 240 | kind = "method" |
| 241 | else: |
| 242 | kind = "data" |
| 243 | |
| 244 | result.append((name, kind, homecls, obj)) |
| 245 | |
| 246 | return result |
| 247 | |
Tim Peters | e0b2d7a | 2001-09-22 06:10:55 +0000 | [diff] [blame] | 248 | # ----------------------------------------------------------- class helpers |
| 249 | def _searchbases(cls, accum): |
| 250 | # Simulate the "classic class" search order. |
| 251 | if cls in accum: |
| 252 | return |
| 253 | accum.append(cls) |
| 254 | for base in cls.__bases__: |
| 255 | _searchbases(base, accum) |
| 256 | |
| 257 | def getmro(cls): |
| 258 | "Return tuple of base classes (including cls) in method resolution order." |
| 259 | if hasattr(cls, "__mro__"): |
| 260 | return cls.__mro__ |
| 261 | else: |
| 262 | result = [] |
| 263 | _searchbases(cls, result) |
| 264 | return tuple(result) |
| 265 | |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 266 | # -------------------------------------------------- source code extraction |
| 267 | def indentsize(line): |
| 268 | """Return the indent size, in spaces, at the start of a line of text.""" |
| 269 | expline = string.expandtabs(line) |
| 270 | return len(expline) - len(string.lstrip(expline)) |
| 271 | |
| 272 | def getdoc(object): |
| 273 | """Get the documentation string for an object. |
| 274 | |
| 275 | All tabs are expanded to spaces. To clean up docstrings that are |
| 276 | indented to line up with blocks of code, any whitespace than can be |
| 277 | uniformly removed from the second line onwards is removed.""" |
Tim Peters | 2400831 | 2002-03-17 18:56:20 +0000 | [diff] [blame] | 278 | try: |
| 279 | doc = object.__doc__ |
| 280 | except AttributeError: |
| 281 | return None |
Michael W. Hudson | 755f75e | 2002-05-20 17:29:46 +0000 | [diff] [blame] | 282 | if not isinstance(doc, types.StringTypes): |
Tim Peters | 2400831 | 2002-03-17 18:56:20 +0000 | [diff] [blame] | 283 | return None |
| 284 | try: |
| 285 | lines = string.split(string.expandtabs(doc), '\n') |
| 286 | except UnicodeError: |
| 287 | return None |
| 288 | else: |
Ka-Ping Yee | a59ef7b | 2002-11-30 03:53:15 +0000 | [diff] [blame] | 289 | # Find minimum indentation of any non-blank lines after first line. |
| 290 | margin = sys.maxint |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 291 | for line in lines[1:]: |
| 292 | content = len(string.lstrip(line)) |
Ka-Ping Yee | a59ef7b | 2002-11-30 03:53:15 +0000 | [diff] [blame] | 293 | if content: |
| 294 | indent = len(line) - content |
| 295 | margin = min(margin, indent) |
| 296 | # Remove indentation. |
| 297 | if lines: |
| 298 | lines[0] = lines[0].lstrip() |
| 299 | if margin < sys.maxint: |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 300 | 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] | 301 | # Remove any trailing or leading blank lines. |
| 302 | while lines and not lines[-1]: |
| 303 | lines.pop() |
| 304 | while lines and not lines[0]: |
| 305 | lines.pop(0) |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 306 | return string.join(lines, '\n') |
| 307 | |
| 308 | def getfile(object): |
Ka-Ping Yee | c113c24 | 2001-03-02 02:08:53 +0000 | [diff] [blame] | 309 | """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] | 310 | if ismodule(object): |
| 311 | if hasattr(object, '__file__'): |
| 312 | return object.__file__ |
Jeremy Hylton | ab91902 | 2003-06-27 18:41:20 +0000 | [diff] [blame] | 313 | raise TypeError('arg is a built-in module') |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 314 | if isclass(object): |
Ka-Ping Yee | c99e0f1 | 2001-04-13 12:10:40 +0000 | [diff] [blame] | 315 | object = sys.modules.get(object.__module__) |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 316 | if hasattr(object, '__file__'): |
| 317 | return object.__file__ |
Jeremy Hylton | ab91902 | 2003-06-27 18:41:20 +0000 | [diff] [blame] | 318 | raise TypeError('arg is a built-in class') |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 319 | if ismethod(object): |
| 320 | object = object.im_func |
| 321 | if isfunction(object): |
| 322 | object = object.func_code |
| 323 | if istraceback(object): |
| 324 | object = object.tb_frame |
| 325 | if isframe(object): |
| 326 | object = object.f_code |
| 327 | if iscode(object): |
| 328 | return object.co_filename |
Tim Peters | 478c105 | 2003-06-29 05:46:54 +0000 | [diff] [blame] | 329 | raise TypeError('arg is not a module, class, method, ' |
Jeremy Hylton | ab91902 | 2003-06-27 18:41:20 +0000 | [diff] [blame] | 330 | 'function, traceback, frame, or code object') |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 331 | |
Ka-Ping Yee | 4d6fc7f | 2001-04-10 11:43:00 +0000 | [diff] [blame] | 332 | def getmoduleinfo(path): |
| 333 | """Get the module name, suffix, mode, and module type for a given file.""" |
| 334 | filename = os.path.basename(path) |
| 335 | suffixes = map(lambda (suffix, mode, mtype): |
| 336 | (-len(suffix), suffix, mode, mtype), imp.get_suffixes()) |
| 337 | suffixes.sort() # try longest suffixes first, in case they overlap |
| 338 | for neglen, suffix, mode, mtype in suffixes: |
| 339 | if filename[neglen:] == suffix: |
| 340 | return filename[:neglen], suffix, mode, mtype |
| 341 | |
| 342 | def getmodulename(path): |
| 343 | """Return the module name for a given file, or None.""" |
| 344 | info = getmoduleinfo(path) |
| 345 | if info: return info[0] |
| 346 | |
Ka-Ping Yee | c113c24 | 2001-03-02 02:08:53 +0000 | [diff] [blame] | 347 | def getsourcefile(object): |
| 348 | """Return the Python source file an object was defined in, if it exists.""" |
| 349 | filename = getfile(object) |
| 350 | if string.lower(filename[-4:]) in ['.pyc', '.pyo']: |
| 351 | filename = filename[:-4] + '.py' |
Ka-Ping Yee | 4eb0c00 | 2001-03-02 05:50:34 +0000 | [diff] [blame] | 352 | for suffix, mode, kind in imp.get_suffixes(): |
| 353 | if 'b' in mode and string.lower(filename[-len(suffix):]) == suffix: |
| 354 | # Looks like a binary file. We want to only return a text file. |
| 355 | return None |
| 356 | if os.path.exists(filename): |
Ka-Ping Yee | c113c24 | 2001-03-02 02:08:53 +0000 | [diff] [blame] | 357 | return filename |
| 358 | |
| 359 | def getabsfile(object): |
Ka-Ping Yee | 4eb0c00 | 2001-03-02 05:50:34 +0000 | [diff] [blame] | 360 | """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] | 361 | |
Ka-Ping Yee | 4eb0c00 | 2001-03-02 05:50:34 +0000 | [diff] [blame] | 362 | The idea is for each object to have a unique origin, so this routine |
| 363 | normalizes the result as much as possible.""" |
| 364 | return os.path.normcase( |
| 365 | os.path.abspath(getsourcefile(object) or getfile(object))) |
Ka-Ping Yee | c113c24 | 2001-03-02 02:08:53 +0000 | [diff] [blame] | 366 | |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 367 | modulesbyfile = {} |
| 368 | |
| 369 | def getmodule(object): |
Ka-Ping Yee | 4eb0c00 | 2001-03-02 05:50:34 +0000 | [diff] [blame] | 370 | """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] | 371 | if ismodule(object): |
| 372 | return object |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 373 | if isclass(object): |
Ka-Ping Yee | 8b58b84 | 2001-03-01 13:56:16 +0000 | [diff] [blame] | 374 | return sys.modules.get(object.__module__) |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 375 | try: |
Ka-Ping Yee | c113c24 | 2001-03-02 02:08:53 +0000 | [diff] [blame] | 376 | file = getabsfile(object) |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 377 | except TypeError: |
| 378 | return None |
Raymond Hettinger | 54f0222 | 2002-06-01 14:18:47 +0000 | [diff] [blame] | 379 | if file in modulesbyfile: |
Ka-Ping Yee | b38bbbd | 2003-03-28 16:29:50 +0000 | [diff] [blame] | 380 | return sys.modules.get(modulesbyfile[file]) |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 381 | for module in sys.modules.values(): |
| 382 | if hasattr(module, '__file__'): |
Ka-Ping Yee | c113c24 | 2001-03-02 02:08:53 +0000 | [diff] [blame] | 383 | modulesbyfile[getabsfile(module)] = module.__name__ |
Raymond Hettinger | 54f0222 | 2002-06-01 14:18:47 +0000 | [diff] [blame] | 384 | if file in modulesbyfile: |
Ka-Ping Yee | b38bbbd | 2003-03-28 16:29:50 +0000 | [diff] [blame] | 385 | return sys.modules.get(modulesbyfile[file]) |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 386 | main = sys.modules['__main__'] |
Brett Cannon | 4a671fe | 2003-06-15 22:33:28 +0000 | [diff] [blame] | 387 | if not hasattr(object, '__name__'): |
| 388 | return None |
Ka-Ping Yee | 4eb0c00 | 2001-03-02 05:50:34 +0000 | [diff] [blame] | 389 | if hasattr(main, object.__name__): |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 390 | mainobject = getattr(main, object.__name__) |
Ka-Ping Yee | 4eb0c00 | 2001-03-02 05:50:34 +0000 | [diff] [blame] | 391 | if mainobject is object: |
| 392 | return main |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 393 | builtin = sys.modules['__builtin__'] |
Ka-Ping Yee | 4eb0c00 | 2001-03-02 05:50:34 +0000 | [diff] [blame] | 394 | if hasattr(builtin, object.__name__): |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 395 | builtinobject = getattr(builtin, object.__name__) |
Ka-Ping Yee | 4eb0c00 | 2001-03-02 05:50:34 +0000 | [diff] [blame] | 396 | if builtinobject is object: |
| 397 | return builtin |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 398 | |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 399 | def findsource(object): |
| 400 | """Return the entire source file and starting line number for an object. |
| 401 | |
| 402 | The argument may be a module, class, method, function, traceback, frame, |
| 403 | or code object. The source code is returned as a list of all the lines |
| 404 | in the file and the line number indexes a line in that list. An IOError |
| 405 | is raised if the source code cannot be retrieved.""" |
Neil Schemenauer | f06f853 | 2002-03-23 23:51:04 +0000 | [diff] [blame] | 406 | file = getsourcefile(object) or getfile(object) |
| 407 | lines = linecache.getlines(file) |
| 408 | if not lines: |
Jeremy Hylton | ab91902 | 2003-06-27 18:41:20 +0000 | [diff] [blame] | 409 | raise IOError('could not get source code') |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 410 | |
| 411 | if ismodule(object): |
| 412 | return lines, 0 |
| 413 | |
| 414 | if isclass(object): |
| 415 | name = object.__name__ |
Ka-Ping Yee | a6e5971 | 2001-03-10 09:31:55 +0000 | [diff] [blame] | 416 | pat = re.compile(r'^\s*class\s*' + name + r'\b') |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 417 | for i in range(len(lines)): |
Ka-Ping Yee | a6e5971 | 2001-03-10 09:31:55 +0000 | [diff] [blame] | 418 | if pat.match(lines[i]): return lines, i |
Jeremy Hylton | ab91902 | 2003-06-27 18:41:20 +0000 | [diff] [blame] | 419 | else: |
| 420 | raise IOError('could not find class definition') |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 421 | |
| 422 | if ismethod(object): |
| 423 | object = object.im_func |
| 424 | if isfunction(object): |
| 425 | object = object.func_code |
| 426 | if istraceback(object): |
| 427 | object = object.tb_frame |
| 428 | if isframe(object): |
| 429 | object = object.f_code |
| 430 | if iscode(object): |
Ka-Ping Yee | 4eb0c00 | 2001-03-02 05:50:34 +0000 | [diff] [blame] | 431 | if not hasattr(object, 'co_firstlineno'): |
Jeremy Hylton | ab91902 | 2003-06-27 18:41:20 +0000 | [diff] [blame] | 432 | raise IOError('could not find function definition') |
Ka-Ping Yee | 4eb0c00 | 2001-03-02 05:50:34 +0000 | [diff] [blame] | 433 | lnum = object.co_firstlineno - 1 |
Raymond Hettinger | 2d375f7 | 2003-01-14 02:19:36 +0000 | [diff] [blame] | 434 | pat = re.compile(r'^(\s*def\s)|(.*\slambda(:|\s))') |
Ka-Ping Yee | 4eb0c00 | 2001-03-02 05:50:34 +0000 | [diff] [blame] | 435 | while lnum > 0: |
Ka-Ping Yee | a6e5971 | 2001-03-10 09:31:55 +0000 | [diff] [blame] | 436 | if pat.match(lines[lnum]): break |
Ka-Ping Yee | 4eb0c00 | 2001-03-02 05:50:34 +0000 | [diff] [blame] | 437 | lnum = lnum - 1 |
| 438 | return lines, lnum |
Jeremy Hylton | ab91902 | 2003-06-27 18:41:20 +0000 | [diff] [blame] | 439 | raise IOError('could not find code object') |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 440 | |
| 441 | def getcomments(object): |
Jeremy Hylton | b4c17c8 | 2002-03-28 23:01:56 +0000 | [diff] [blame] | 442 | """Get lines of comments immediately preceding an object's source code. |
| 443 | |
| 444 | Returns None when source can't be found. |
| 445 | """ |
| 446 | try: |
| 447 | lines, lnum = findsource(object) |
| 448 | except (IOError, TypeError): |
| 449 | return None |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 450 | |
| 451 | if ismodule(object): |
| 452 | # Look for a comment block at the top of the file. |
| 453 | start = 0 |
Ka-Ping Yee | b910efe | 2001-04-12 13:17:17 +0000 | [diff] [blame] | 454 | if lines and lines[0][:2] == '#!': start = 1 |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 455 | while start < len(lines) and string.strip(lines[start]) in ['', '#']: |
| 456 | start = start + 1 |
Ka-Ping Yee | b910efe | 2001-04-12 13:17:17 +0000 | [diff] [blame] | 457 | if start < len(lines) and lines[start][:1] == '#': |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 458 | comments = [] |
| 459 | end = start |
| 460 | while end < len(lines) and lines[end][:1] == '#': |
| 461 | comments.append(string.expandtabs(lines[end])) |
| 462 | end = end + 1 |
| 463 | return string.join(comments, '') |
| 464 | |
| 465 | # Look for a preceding block of comments at the same indentation. |
| 466 | elif lnum > 0: |
| 467 | indent = indentsize(lines[lnum]) |
| 468 | end = lnum - 1 |
| 469 | if end >= 0 and string.lstrip(lines[end])[:1] == '#' and \ |
| 470 | indentsize(lines[end]) == indent: |
| 471 | comments = [string.lstrip(string.expandtabs(lines[end]))] |
| 472 | if end > 0: |
| 473 | end = end - 1 |
| 474 | comment = string.lstrip(string.expandtabs(lines[end])) |
| 475 | while comment[:1] == '#' and indentsize(lines[end]) == indent: |
| 476 | comments[:0] = [comment] |
| 477 | end = end - 1 |
| 478 | if end < 0: break |
| 479 | comment = string.lstrip(string.expandtabs(lines[end])) |
| 480 | while comments and string.strip(comments[0]) == '#': |
| 481 | comments[:1] = [] |
| 482 | while comments and string.strip(comments[-1]) == '#': |
| 483 | comments[-1:] = [] |
| 484 | return string.join(comments, '') |
| 485 | |
| 486 | class ListReader: |
| 487 | """Provide a readline() method to return lines from a list of strings.""" |
| 488 | def __init__(self, lines): |
| 489 | self.lines = lines |
| 490 | self.index = 0 |
| 491 | |
| 492 | def readline(self): |
| 493 | i = self.index |
| 494 | if i < len(self.lines): |
| 495 | self.index = i + 1 |
| 496 | return self.lines[i] |
| 497 | else: return '' |
| 498 | |
Tim Peters | 4efb6e9 | 2001-06-29 23:51:08 +0000 | [diff] [blame] | 499 | class EndOfBlock(Exception): pass |
| 500 | |
| 501 | class BlockFinder: |
| 502 | """Provide a tokeneater() method to detect the end of a code block.""" |
| 503 | def __init__(self): |
| 504 | self.indent = 0 |
| 505 | self.started = 0 |
| 506 | self.last = 0 |
| 507 | |
| 508 | def tokeneater(self, type, token, (srow, scol), (erow, ecol), line): |
| 509 | if not self.started: |
| 510 | if type == tokenize.NAME: self.started = 1 |
| 511 | elif type == tokenize.NEWLINE: |
| 512 | self.last = srow |
| 513 | elif type == tokenize.INDENT: |
| 514 | self.indent = self.indent + 1 |
| 515 | elif type == tokenize.DEDENT: |
| 516 | self.indent = self.indent - 1 |
Jeremy Hylton | ab91902 | 2003-06-27 18:41:20 +0000 | [diff] [blame] | 517 | if self.indent == 0: |
| 518 | raise EndOfBlock, self.last |
Raymond Hettinger | 2e7b748 | 2003-01-19 13:21:20 +0000 | [diff] [blame] | 519 | elif type == tokenize.NAME and scol == 0: |
| 520 | raise EndOfBlock, self.last |
Tim Peters | 4efb6e9 | 2001-06-29 23:51:08 +0000 | [diff] [blame] | 521 | |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 522 | def getblock(lines): |
| 523 | """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] | 524 | try: |
| 525 | tokenize.tokenize(ListReader(lines).readline, BlockFinder().tokeneater) |
| 526 | except EndOfBlock, eob: |
| 527 | return lines[:eob.args[0]] |
Raymond Hettinger | 2d375f7 | 2003-01-14 02:19:36 +0000 | [diff] [blame] | 528 | # Fooling the indent/dedent logic implies a one-line definition |
| 529 | return lines[:1] |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 530 | |
| 531 | def getsourcelines(object): |
| 532 | """Return a list of source lines and starting line number for an object. |
| 533 | |
| 534 | The argument may be a module, class, method, function, traceback, frame, |
| 535 | or code object. The source code is returned as a list of the lines |
| 536 | corresponding to the object and the line number indicates where in the |
| 537 | original source file the first line of code was found. An IOError is |
| 538 | raised if the source code cannot be retrieved.""" |
| 539 | lines, lnum = findsource(object) |
| 540 | |
| 541 | if ismodule(object): return lines, 0 |
| 542 | else: return getblock(lines[lnum:]), lnum + 1 |
| 543 | |
| 544 | def getsource(object): |
| 545 | """Return the text of the source code for an object. |
| 546 | |
| 547 | The argument may be a module, class, method, function, traceback, frame, |
| 548 | or code object. The source code is returned as a single string. An |
| 549 | IOError is raised if the source code cannot be retrieved.""" |
| 550 | lines, lnum = getsourcelines(object) |
| 551 | return string.join(lines, '') |
| 552 | |
| 553 | # --------------------------------------------------- class tree extraction |
| 554 | def walktree(classes, children, parent): |
| 555 | """Recursive helper function for getclasstree().""" |
| 556 | results = [] |
Raymond Hettinger | 3375fc5 | 2003-12-01 20:12:15 +0000 | [diff] [blame] | 557 | classes.sort(key=attrgetter('__name__')) |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 558 | for c in classes: |
| 559 | results.append((c, c.__bases__)) |
Raymond Hettinger | 54f0222 | 2002-06-01 14:18:47 +0000 | [diff] [blame] | 560 | if c in children: |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 561 | results.append(walktree(children[c], children, c)) |
| 562 | return results |
| 563 | |
| 564 | def getclasstree(classes, unique=0): |
| 565 | """Arrange the given list of classes into a hierarchy of nested lists. |
| 566 | |
| 567 | Where a nested list appears, it contains classes derived from the class |
| 568 | whose entry immediately precedes the list. Each entry is a 2-tuple |
| 569 | containing a class and a tuple of its base classes. If the 'unique' |
| 570 | argument is true, exactly one entry appears in the returned structure |
| 571 | for each class in the given list. Otherwise, classes using multiple |
| 572 | inheritance and their descendants will appear multiple times.""" |
| 573 | children = {} |
| 574 | roots = [] |
| 575 | for c in classes: |
| 576 | if c.__bases__: |
| 577 | for parent in c.__bases__: |
Raymond Hettinger | 54f0222 | 2002-06-01 14:18:47 +0000 | [diff] [blame] | 578 | if not parent in children: |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 579 | children[parent] = [] |
| 580 | children[parent].append(c) |
| 581 | if unique and parent in classes: break |
| 582 | elif c not in roots: |
| 583 | roots.append(c) |
Raymond Hettinger | e0d4972 | 2002-06-02 18:55:56 +0000 | [diff] [blame] | 584 | for parent in children: |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 585 | if parent not in classes: |
| 586 | roots.append(parent) |
| 587 | return walktree(roots, children, None) |
| 588 | |
| 589 | # ------------------------------------------------ argument list extraction |
| 590 | # These constants are from Python's compile.h. |
| 591 | CO_OPTIMIZED, CO_NEWLOCALS, CO_VARARGS, CO_VARKEYWORDS = 1, 2, 4, 8 |
| 592 | |
| 593 | def getargs(co): |
| 594 | """Get information about the arguments accepted by a code object. |
| 595 | |
| 596 | Three things are returned: (args, varargs, varkw), where 'args' is |
| 597 | a list of argument names (possibly containing nested lists), and |
| 598 | 'varargs' and 'varkw' are the names of the * and ** arguments or None.""" |
Jeremy Hylton | 6496788 | 2003-06-27 18:14:39 +0000 | [diff] [blame] | 599 | |
| 600 | if not iscode(co): |
| 601 | raise TypeError('arg is not a code object') |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 602 | |
| 603 | code = co.co_code |
| 604 | nargs = co.co_argcount |
| 605 | names = co.co_varnames |
| 606 | args = list(names[:nargs]) |
| 607 | step = 0 |
| 608 | |
| 609 | # The following acrobatics are for anonymous (tuple) arguments. |
| 610 | for i in range(nargs): |
| 611 | if args[i][:1] in ['', '.']: |
| 612 | stack, remain, count = [], [], [] |
| 613 | while step < len(code): |
| 614 | op = ord(code[step]) |
| 615 | step = step + 1 |
| 616 | if op >= dis.HAVE_ARGUMENT: |
| 617 | opname = dis.opname[op] |
| 618 | value = ord(code[step]) + ord(code[step+1])*256 |
| 619 | step = step + 2 |
| 620 | if opname in ['UNPACK_TUPLE', 'UNPACK_SEQUENCE']: |
| 621 | remain.append(value) |
| 622 | count.append(value) |
| 623 | elif opname == 'STORE_FAST': |
| 624 | stack.append(names[value]) |
| 625 | remain[-1] = remain[-1] - 1 |
| 626 | while remain[-1] == 0: |
| 627 | remain.pop() |
| 628 | size = count.pop() |
| 629 | stack[-size:] = [stack[-size:]] |
| 630 | if not remain: break |
| 631 | remain[-1] = remain[-1] - 1 |
| 632 | if not remain: break |
| 633 | args[i] = stack[0] |
| 634 | |
| 635 | varargs = None |
| 636 | if co.co_flags & CO_VARARGS: |
| 637 | varargs = co.co_varnames[nargs] |
| 638 | nargs = nargs + 1 |
| 639 | varkw = None |
| 640 | if co.co_flags & CO_VARKEYWORDS: |
| 641 | varkw = co.co_varnames[nargs] |
| 642 | return args, varargs, varkw |
| 643 | |
| 644 | def getargspec(func): |
| 645 | """Get the names and default values of a function's arguments. |
| 646 | |
| 647 | A tuple of four things is returned: (args, varargs, varkw, defaults). |
| 648 | 'args' is a list of the argument names (it may contain nested lists). |
| 649 | 'varargs' and 'varkw' are the names of the * and ** arguments or None. |
Jeremy Hylton | 6496788 | 2003-06-27 18:14:39 +0000 | [diff] [blame] | 650 | 'defaults' is an n-tuple of the default values of the last n arguments. |
| 651 | """ |
| 652 | |
| 653 | if ismethod(func): |
| 654 | func = func.im_func |
| 655 | if not isfunction(func): |
| 656 | raise TypeError('arg is not a Python function') |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 657 | args, varargs, varkw = getargs(func.func_code) |
| 658 | return args, varargs, varkw, func.func_defaults |
| 659 | |
| 660 | def getargvalues(frame): |
| 661 | """Get information about arguments passed into a particular frame. |
| 662 | |
| 663 | A tuple of four things is returned: (args, varargs, varkw, locals). |
| 664 | 'args' is a list of the argument names (it may contain nested lists). |
| 665 | 'varargs' and 'varkw' are the names of the * and ** arguments or None. |
| 666 | 'locals' is the locals dictionary of the given frame.""" |
| 667 | args, varargs, varkw = getargs(frame.f_code) |
| 668 | return args, varargs, varkw, frame.f_locals |
| 669 | |
| 670 | def joinseq(seq): |
| 671 | if len(seq) == 1: |
| 672 | return '(' + seq[0] + ',)' |
| 673 | else: |
| 674 | return '(' + string.join(seq, ', ') + ')' |
| 675 | |
| 676 | def strseq(object, convert, join=joinseq): |
| 677 | """Recursively walk a sequence, stringifying each element.""" |
| 678 | if type(object) in [types.ListType, types.TupleType]: |
| 679 | return join(map(lambda o, c=convert, j=join: strseq(o, c, j), object)) |
| 680 | else: |
| 681 | return convert(object) |
| 682 | |
| 683 | def formatargspec(args, varargs=None, varkw=None, defaults=None, |
| 684 | formatarg=str, |
| 685 | formatvarargs=lambda name: '*' + name, |
| 686 | formatvarkw=lambda name: '**' + name, |
| 687 | formatvalue=lambda value: '=' + repr(value), |
| 688 | join=joinseq): |
| 689 | """Format an argument spec from the 4 values returned by getargspec. |
| 690 | |
| 691 | The first four arguments are (args, varargs, varkw, defaults). The |
| 692 | other four arguments are the corresponding optional formatting functions |
| 693 | that are called to turn names and values into strings. The ninth |
| 694 | argument is an optional function to format the sequence of arguments.""" |
| 695 | specs = [] |
| 696 | if defaults: |
| 697 | firstdefault = len(args) - len(defaults) |
| 698 | for i in range(len(args)): |
| 699 | spec = strseq(args[i], formatarg, join) |
| 700 | if defaults and i >= firstdefault: |
| 701 | spec = spec + formatvalue(defaults[i - firstdefault]) |
| 702 | specs.append(spec) |
Raymond Hettinger | 936654b | 2002-06-01 03:06:31 +0000 | [diff] [blame] | 703 | if varargs is not None: |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 704 | specs.append(formatvarargs(varargs)) |
Raymond Hettinger | 936654b | 2002-06-01 03:06:31 +0000 | [diff] [blame] | 705 | if varkw is not None: |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 706 | specs.append(formatvarkw(varkw)) |
| 707 | return '(' + string.join(specs, ', ') + ')' |
| 708 | |
| 709 | def formatargvalues(args, varargs, varkw, locals, |
| 710 | formatarg=str, |
| 711 | formatvarargs=lambda name: '*' + name, |
| 712 | formatvarkw=lambda name: '**' + name, |
| 713 | formatvalue=lambda value: '=' + repr(value), |
| 714 | join=joinseq): |
| 715 | """Format an argument spec from the 4 values returned by getargvalues. |
| 716 | |
| 717 | The first four arguments are (args, varargs, varkw, locals). The |
| 718 | next four arguments are the corresponding optional formatting functions |
| 719 | that are called to turn names and values into strings. The ninth |
| 720 | argument is an optional function to format the sequence of arguments.""" |
| 721 | def convert(name, locals=locals, |
| 722 | formatarg=formatarg, formatvalue=formatvalue): |
| 723 | return formatarg(name) + formatvalue(locals[name]) |
| 724 | specs = [] |
| 725 | for i in range(len(args)): |
| 726 | specs.append(strseq(args[i], convert, join)) |
| 727 | if varargs: |
| 728 | specs.append(formatvarargs(varargs) + formatvalue(locals[varargs])) |
| 729 | if varkw: |
| 730 | specs.append(formatvarkw(varkw) + formatvalue(locals[varkw])) |
| 731 | return '(' + string.join(specs, ', ') + ')' |
| 732 | |
| 733 | # -------------------------------------------------- stack frame extraction |
| 734 | def getframeinfo(frame, context=1): |
| 735 | """Get information about a frame or traceback object. |
| 736 | |
| 737 | A tuple of five things is returned: the filename, the line number of |
| 738 | the current line, the function name, a list of lines of context from |
| 739 | the source code, and the index of the current line within that list. |
| 740 | The optional second argument specifies the number of lines of context |
| 741 | to return, which are centered around the current line.""" |
| 742 | if istraceback(frame): |
Andrew M. Kuchling | ba8b6bc | 2004-06-05 14:11:59 +0000 | [diff] [blame] | 743 | lineno = frame.tb_lineno |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 744 | frame = frame.tb_frame |
Andrew M. Kuchling | ba8b6bc | 2004-06-05 14:11:59 +0000 | [diff] [blame] | 745 | else: |
| 746 | lineno = frame.f_lineno |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 747 | if not isframe(frame): |
Jeremy Hylton | ab91902 | 2003-06-27 18:41:20 +0000 | [diff] [blame] | 748 | raise TypeError('arg is not a frame or traceback object') |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 749 | |
Neil Schemenauer | f06f853 | 2002-03-23 23:51:04 +0000 | [diff] [blame] | 750 | filename = getsourcefile(frame) or getfile(frame) |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 751 | if context > 0: |
Guido van Rossum | 54e54c6 | 2001-09-04 19:14:14 +0000 | [diff] [blame] | 752 | start = lineno - 1 - context//2 |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 753 | try: |
| 754 | lines, lnum = findsource(frame) |
Ka-Ping Yee | 4eb0c00 | 2001-03-02 05:50:34 +0000 | [diff] [blame] | 755 | except IOError: |
| 756 | lines = index = None |
| 757 | else: |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 758 | start = max(start, 1) |
Raymond Hettinger | a050171 | 2004-06-15 11:22:53 +0000 | [diff] [blame] | 759 | start = max(0, min(start, len(lines) - context)) |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 760 | lines = lines[start:start+context] |
Ka-Ping Yee | 59ade08 | 2001-03-01 03:55:35 +0000 | [diff] [blame] | 761 | index = lineno - 1 - start |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 762 | else: |
| 763 | lines = index = None |
| 764 | |
Ka-Ping Yee | 59ade08 | 2001-03-01 03:55:35 +0000 | [diff] [blame] | 765 | return (filename, lineno, frame.f_code.co_name, lines, index) |
| 766 | |
| 767 | def getlineno(frame): |
| 768 | """Get the line number from a frame object, allowing for optimization.""" |
Michael W. Hudson | dd32a91 | 2002-08-15 14:59:02 +0000 | [diff] [blame] | 769 | # FrameType.f_lineno is now a descriptor that grovels co_lnotab |
| 770 | return frame.f_lineno |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 771 | |
| 772 | def getouterframes(frame, context=1): |
| 773 | """Get a list of records for a frame and all higher (calling) frames. |
| 774 | |
| 775 | Each record contains a frame object, filename, line number, function |
| 776 | name, a list of lines of context, and index within the context.""" |
| 777 | framelist = [] |
| 778 | while frame: |
| 779 | framelist.append((frame,) + getframeinfo(frame, context)) |
| 780 | frame = frame.f_back |
| 781 | return framelist |
| 782 | |
| 783 | def getinnerframes(tb, context=1): |
| 784 | """Get a list of records for a traceback's frame and all lower frames. |
| 785 | |
| 786 | Each record contains a frame object, filename, line number, function |
| 787 | 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] | 788 | framelist = [] |
| 789 | while tb: |
| 790 | framelist.append((tb.tb_frame,) + getframeinfo(tb, context)) |
| 791 | tb = tb.tb_next |
| 792 | return framelist |
| 793 | |
Jeremy Hylton | ab91902 | 2003-06-27 18:41:20 +0000 | [diff] [blame] | 794 | currentframe = sys._getframe |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 795 | |
| 796 | def stack(context=1): |
| 797 | """Return a list of records for the stack above the caller's frame.""" |
Jeremy Hylton | ab91902 | 2003-06-27 18:41:20 +0000 | [diff] [blame] | 798 | return getouterframes(sys._getframe(1), context) |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 799 | |
| 800 | def trace(context=1): |
Tim Peters | 85ba673 | 2001-02-28 08:26:44 +0000 | [diff] [blame] | 801 | """Return a list of records for the stack below the current exception.""" |
Fred Drake | d451ec1 | 2002-04-26 02:29:55 +0000 | [diff] [blame] | 802 | return getinnerframes(sys.exc_info()[2], context) |