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