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 |
Neal Norwitz | 221085d | 2007-02-25 20:55:47 +0000 | [diff] [blame] | 4 | attributes (co_*, im_*, tb_*, etc.) in a friendlier fashion. |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 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 | |
Christian Heimes | 7131fd9 | 2008-02-19 14:21:46 +0000 | [diff] [blame] | 9 | ismodule(), isclass(), ismethod(), isfunction(), isgeneratorfunction(), |
| 10 | isgenerator(), istraceback(), isframe(), iscode(), isbuiltin(), |
| 11 | isroutine() - check object types |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 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 | |
Benjamin Peterson | 25cd7eb | 2010-03-30 18:42:32 +0000 | [diff] [blame] | 19 | getargspec(), getargvalues(), getcallargs() - get info about function arguments |
Guido van Rossum | 2e65f89 | 2007-02-28 22:03:49 +0000 | [diff] [blame] | 20 | getfullargspec() - same, with support for Python-3000 features |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 21 | formatargspec(), formatargvalues() - format an argument spec |
| 22 | getouterframes(), getinnerframes() - get info about frames |
| 23 | currentframe() - get the current stack frame |
| 24 | stack(), trace() - get info about frames on the stack or in a traceback |
Larry Hastings | 7c7cbfc | 2012-06-22 15:19:35 -0700 | [diff] [blame] | 25 | |
| 26 | signature() - get a Signature object for the callable |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 27 | """ |
| 28 | |
| 29 | # This module is in the public domain. No warranties. |
| 30 | |
Larry Hastings | 7c7cbfc | 2012-06-22 15:19:35 -0700 | [diff] [blame] | 31 | __author__ = ('Ka-Ping Yee <ping@lfw.org>', |
| 32 | 'Yury Selivanov <yselivanov@sprymix.com>') |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 33 | |
Christian Heimes | 7131fd9 | 2008-02-19 14:21:46 +0000 | [diff] [blame] | 34 | import imp |
Brett Cannon | cb66eb0 | 2012-05-11 12:58:42 -0400 | [diff] [blame] | 35 | import importlib.machinery |
| 36 | import itertools |
Christian Heimes | 7131fd9 | 2008-02-19 14:21:46 +0000 | [diff] [blame] | 37 | import linecache |
Brett Cannon | cb66eb0 | 2012-05-11 12:58:42 -0400 | [diff] [blame] | 38 | import os |
| 39 | import re |
| 40 | import sys |
| 41 | import tokenize |
| 42 | import types |
Brett Cannon | 2b88fcf | 2012-06-02 22:28:42 -0400 | [diff] [blame] | 43 | import warnings |
Larry Hastings | 7c7cbfc | 2012-06-22 15:19:35 -0700 | [diff] [blame] | 44 | import functools |
Nick Coghlan | 2f92e54 | 2012-06-23 19:39:55 +1000 | [diff] [blame] | 45 | import builtins |
Raymond Hettinger | a1a992c | 2005-03-11 06:46:45 +0000 | [diff] [blame] | 46 | from operator import attrgetter |
Larry Hastings | 7c7cbfc | 2012-06-22 15:19:35 -0700 | [diff] [blame] | 47 | from collections import namedtuple, OrderedDict |
Nick Coghlan | 09c8123 | 2010-08-17 10:18:16 +0000 | [diff] [blame] | 48 | |
| 49 | # Create constants for the compiler flags in Include/code.h |
| 50 | # We try to get them from dis to avoid duplication, but fall |
Ezio Melotti | 30b9d5d | 2013-08-17 15:50:46 +0300 | [diff] [blame] | 51 | # back to hardcoding so the dependency is optional |
Nick Coghlan | 09c8123 | 2010-08-17 10:18:16 +0000 | [diff] [blame] | 52 | try: |
| 53 | from dis import COMPILER_FLAG_NAMES as _flag_names |
| 54 | except ImportError: |
| 55 | CO_OPTIMIZED, CO_NEWLOCALS = 0x1, 0x2 |
| 56 | CO_VARARGS, CO_VARKEYWORDS = 0x4, 0x8 |
| 57 | CO_NESTED, CO_GENERATOR, CO_NOFREE = 0x10, 0x20, 0x40 |
| 58 | else: |
| 59 | mod_dict = globals() |
| 60 | for k, v in _flag_names.items(): |
| 61 | mod_dict["CO_" + v] = k |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 62 | |
Christian Heimes | be5b30b | 2008-03-03 19:18:51 +0000 | [diff] [blame] | 63 | # See Include/object.h |
| 64 | TPFLAGS_IS_ABSTRACT = 1 << 20 |
| 65 | |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 66 | # ----------------------------------------------------------- type-checking |
| 67 | def ismodule(object): |
| 68 | """Return true if the object is a module. |
| 69 | |
| 70 | Module objects provide these attributes: |
Barry Warsaw | 28a691b | 2010-04-17 00:19:56 +0000 | [diff] [blame] | 71 | __cached__ pathname to byte compiled file |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 72 | __doc__ documentation string |
| 73 | __file__ filename (missing for built-in modules)""" |
Tim Peters | 28bc59f | 2001-09-16 08:40:16 +0000 | [diff] [blame] | 74 | return isinstance(object, types.ModuleType) |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 75 | |
| 76 | def isclass(object): |
| 77 | """Return true if the object is a class. |
| 78 | |
| 79 | Class objects provide these attributes: |
| 80 | __doc__ documentation string |
| 81 | __module__ name of module in which this class was defined""" |
Benjamin Peterson | c465600 | 2009-01-17 22:41:18 +0000 | [diff] [blame] | 82 | return isinstance(object, type) |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 83 | |
| 84 | def ismethod(object): |
| 85 | """Return true if the object is an instance method. |
| 86 | |
| 87 | Instance method objects provide these attributes: |
| 88 | __doc__ documentation string |
| 89 | __name__ name with which this method was defined |
Christian Heimes | ff73795 | 2007-11-27 10:40:20 +0000 | [diff] [blame] | 90 | __func__ function object containing implementation of method |
| 91 | __self__ instance to which this method is bound""" |
Tim Peters | 28bc59f | 2001-09-16 08:40:16 +0000 | [diff] [blame] | 92 | return isinstance(object, types.MethodType) |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 93 | |
Tim Peters | 536d226 | 2001-09-20 05:13:38 +0000 | [diff] [blame] | 94 | def ismethoddescriptor(object): |
Tim Peters | f1d90b9 | 2001-09-20 05:47:55 +0000 | [diff] [blame] | 95 | """Return true if the object is a method descriptor. |
| 96 | |
| 97 | But not if ismethod() or isclass() or isfunction() are true. |
Tim Peters | 536d226 | 2001-09-20 05:13:38 +0000 | [diff] [blame] | 98 | |
| 99 | This is new in Python 2.2, and, for example, is true of int.__add__. |
| 100 | An object passing this test has a __get__ attribute but not a __set__ |
| 101 | attribute, but beyond that the set of attributes varies. __name__ is |
| 102 | usually sensible, and __doc__ often is. |
| 103 | |
Tim Peters | f1d90b9 | 2001-09-20 05:47:55 +0000 | [diff] [blame] | 104 | Methods implemented via descriptors that also pass one of the other |
| 105 | tests return false from the ismethoddescriptor() test, simply because |
| 106 | the other tests promise more -- you can, e.g., count on having the |
Christian Heimes | ff73795 | 2007-11-27 10:40:20 +0000 | [diff] [blame] | 107 | __func__ attribute (etc) when an object passes ismethod().""" |
Antoine Pitrou | 86a8a9a | 2011-12-21 09:57:40 +0100 | [diff] [blame] | 108 | if isclass(object) or ismethod(object) or isfunction(object): |
| 109 | # mutual exclusion |
| 110 | return False |
| 111 | tp = type(object) |
| 112 | return hasattr(tp, "__get__") and not hasattr(tp, "__set__") |
Tim Peters | 536d226 | 2001-09-20 05:13:38 +0000 | [diff] [blame] | 113 | |
Martin v. Löwis | e59e2ba | 2003-05-03 09:09:02 +0000 | [diff] [blame] | 114 | def isdatadescriptor(object): |
| 115 | """Return true if the object is a data descriptor. |
| 116 | |
| 117 | Data descriptors have both a __get__ and a __set__ attribute. Examples are |
| 118 | properties (defined in Python) and getsets and members (defined in C). |
| 119 | Typically, data descriptors will also have __name__ and __doc__ attributes |
| 120 | (properties, getsets, and members have both of these attributes), but this |
| 121 | is not guaranteed.""" |
Antoine Pitrou | 86a8a9a | 2011-12-21 09:57:40 +0100 | [diff] [blame] | 122 | if isclass(object) or ismethod(object) or isfunction(object): |
| 123 | # mutual exclusion |
| 124 | return False |
| 125 | tp = type(object) |
| 126 | return hasattr(tp, "__set__") and hasattr(tp, "__get__") |
Martin v. Löwis | e59e2ba | 2003-05-03 09:09:02 +0000 | [diff] [blame] | 127 | |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 128 | if hasattr(types, 'MemberDescriptorType'): |
| 129 | # CPython and equivalent |
| 130 | def ismemberdescriptor(object): |
| 131 | """Return true if the object is a member descriptor. |
| 132 | |
| 133 | Member descriptors are specialized descriptors defined in extension |
| 134 | modules.""" |
| 135 | return isinstance(object, types.MemberDescriptorType) |
| 136 | else: |
| 137 | # Other implementations |
| 138 | def ismemberdescriptor(object): |
| 139 | """Return true if the object is a member descriptor. |
| 140 | |
| 141 | Member descriptors are specialized descriptors defined in extension |
| 142 | modules.""" |
| 143 | return False |
| 144 | |
| 145 | if hasattr(types, 'GetSetDescriptorType'): |
| 146 | # CPython and equivalent |
| 147 | def isgetsetdescriptor(object): |
| 148 | """Return true if the object is a getset descriptor. |
| 149 | |
| 150 | getset descriptors are specialized descriptors defined in extension |
| 151 | modules.""" |
| 152 | return isinstance(object, types.GetSetDescriptorType) |
| 153 | else: |
| 154 | # Other implementations |
| 155 | def isgetsetdescriptor(object): |
| 156 | """Return true if the object is a getset descriptor. |
| 157 | |
| 158 | getset descriptors are specialized descriptors defined in extension |
| 159 | modules.""" |
| 160 | return False |
| 161 | |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 162 | def isfunction(object): |
| 163 | """Return true if the object is a user-defined function. |
| 164 | |
| 165 | Function objects provide these attributes: |
| 166 | __doc__ documentation string |
| 167 | __name__ name with which this function was defined |
Neal Norwitz | 221085d | 2007-02-25 20:55:47 +0000 | [diff] [blame] | 168 | __code__ code object containing compiled function bytecode |
| 169 | __defaults__ tuple of any default values for arguments |
| 170 | __globals__ global namespace in which this function was defined |
| 171 | __annotations__ dict of parameter annotations |
| 172 | __kwdefaults__ dict of keyword only parameters with defaults""" |
Tim Peters | 28bc59f | 2001-09-16 08:40:16 +0000 | [diff] [blame] | 173 | return isinstance(object, types.FunctionType) |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 174 | |
Christian Heimes | 7131fd9 | 2008-02-19 14:21:46 +0000 | [diff] [blame] | 175 | def isgeneratorfunction(object): |
| 176 | """Return true if the object is a user-defined generator function. |
| 177 | |
| 178 | Generator function objects provides same attributes as functions. |
| 179 | |
Alexander Belopolsky | 977a684 | 2010-08-16 20:17:07 +0000 | [diff] [blame] | 180 | See help(isfunction) for attributes listing.""" |
Georg Brandl | b1441c7 | 2009-01-03 22:33:39 +0000 | [diff] [blame] | 181 | return bool((isfunction(object) or ismethod(object)) and |
| 182 | object.__code__.co_flags & CO_GENERATOR) |
Christian Heimes | 7131fd9 | 2008-02-19 14:21:46 +0000 | [diff] [blame] | 183 | |
| 184 | def isgenerator(object): |
| 185 | """Return true if the object is a generator. |
| 186 | |
| 187 | Generator objects provide these attributes: |
Ezio Melotti | 30b9d5d | 2013-08-17 15:50:46 +0300 | [diff] [blame] | 188 | __iter__ defined to support iteration over container |
Christian Heimes | 7131fd9 | 2008-02-19 14:21:46 +0000 | [diff] [blame] | 189 | close raises a new GeneratorExit exception inside the |
| 190 | generator to terminate the iteration |
| 191 | gi_code code object |
| 192 | gi_frame frame object or possibly None once the generator has |
| 193 | been exhausted |
| 194 | gi_running set to 1 when generator is executing, 0 otherwise |
| 195 | next return the next item from the container |
| 196 | send resumes the generator and "sends" a value that becomes |
| 197 | the result of the current yield-expression |
| 198 | throw used to raise an exception inside the generator""" |
| 199 | return isinstance(object, types.GeneratorType) |
| 200 | |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 201 | def istraceback(object): |
| 202 | """Return true if the object is a traceback. |
| 203 | |
| 204 | Traceback objects provide these attributes: |
| 205 | tb_frame frame object at this level |
| 206 | tb_lasti index of last attempted instruction in bytecode |
| 207 | tb_lineno current line number in Python source code |
| 208 | tb_next next inner traceback object (called by this level)""" |
Tim Peters | 28bc59f | 2001-09-16 08:40:16 +0000 | [diff] [blame] | 209 | return isinstance(object, types.TracebackType) |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 210 | |
| 211 | def isframe(object): |
| 212 | """Return true if the object is a frame object. |
| 213 | |
| 214 | Frame objects provide these attributes: |
| 215 | f_back next outer frame object (this frame's caller) |
| 216 | f_builtins built-in namespace seen by this frame |
| 217 | f_code code object being executed in this frame |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 218 | f_globals global namespace seen by this frame |
| 219 | f_lasti index of last attempted instruction in bytecode |
| 220 | f_lineno current line number in Python source code |
| 221 | f_locals local namespace seen by this frame |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 222 | f_trace tracing function for this frame, or None""" |
Tim Peters | 28bc59f | 2001-09-16 08:40:16 +0000 | [diff] [blame] | 223 | return isinstance(object, types.FrameType) |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 224 | |
| 225 | def iscode(object): |
| 226 | """Return true if the object is a code object. |
| 227 | |
| 228 | Code objects provide these attributes: |
| 229 | co_argcount number of arguments (not including * or ** args) |
| 230 | co_code string of raw compiled bytecode |
| 231 | co_consts tuple of constants used in the bytecode |
| 232 | co_filename name of file in which this code object was created |
| 233 | co_firstlineno number of first line in Python source code |
| 234 | co_flags bitmap: 1=optimized | 2=newlocals | 4=*arg | 8=**arg |
| 235 | co_lnotab encoded mapping of line numbers to bytecode indices |
| 236 | co_name name with which this code object was defined |
| 237 | co_names tuple of names of local variables |
| 238 | co_nlocals number of local variables |
| 239 | co_stacksize virtual machine stack space required |
| 240 | co_varnames tuple of names of arguments and local variables""" |
Tim Peters | 28bc59f | 2001-09-16 08:40:16 +0000 | [diff] [blame] | 241 | return isinstance(object, types.CodeType) |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 242 | |
| 243 | def isbuiltin(object): |
| 244 | """Return true if the object is a built-in function or method. |
| 245 | |
| 246 | Built-in functions and methods provide these attributes: |
| 247 | __doc__ documentation string |
| 248 | __name__ original name of this function or method |
| 249 | __self__ instance to which a method is bound, or None""" |
Tim Peters | 28bc59f | 2001-09-16 08:40:16 +0000 | [diff] [blame] | 250 | return isinstance(object, types.BuiltinFunctionType) |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 251 | |
| 252 | def isroutine(object): |
| 253 | """Return true if the object is any kind of function or method.""" |
Tim Peters | 536d226 | 2001-09-20 05:13:38 +0000 | [diff] [blame] | 254 | return (isbuiltin(object) |
| 255 | or isfunction(object) |
| 256 | or ismethod(object) |
| 257 | or ismethoddescriptor(object)) |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 258 | |
Christian Heimes | be5b30b | 2008-03-03 19:18:51 +0000 | [diff] [blame] | 259 | def isabstract(object): |
| 260 | """Return true if the object is an abstract base class (ABC).""" |
Benjamin Peterson | a0dfa82 | 2009-11-13 02:25:08 +0000 | [diff] [blame] | 261 | return bool(isinstance(object, type) and object.__flags__ & TPFLAGS_IS_ABSTRACT) |
Christian Heimes | be5b30b | 2008-03-03 19:18:51 +0000 | [diff] [blame] | 262 | |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 263 | def getmembers(object, predicate=None): |
| 264 | """Return all members of an object as (name, value) pairs sorted by name. |
| 265 | Optionally, only return members that satisfy a given predicate.""" |
Antoine Pitrou | 86a8a9a | 2011-12-21 09:57:40 +0100 | [diff] [blame] | 266 | if isclass(object): |
| 267 | mro = (object,) + getmro(object) |
| 268 | else: |
| 269 | mro = () |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 270 | results = [] |
| 271 | for key in dir(object): |
Antoine Pitrou | 86a8a9a | 2011-12-21 09:57:40 +0100 | [diff] [blame] | 272 | # First try to get the value via __dict__. Some descriptors don't |
| 273 | # like calling their __get__ (see bug #1785). |
| 274 | for base in mro: |
| 275 | if key in base.__dict__: |
| 276 | value = base.__dict__[key] |
| 277 | break |
| 278 | else: |
| 279 | try: |
| 280 | value = getattr(object, key) |
| 281 | except AttributeError: |
| 282 | continue |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 283 | if not predicate or predicate(value): |
| 284 | results.append((key, value)) |
| 285 | results.sort() |
| 286 | return results |
| 287 | |
Christian Heimes | 25bb783 | 2008-01-11 16:17:00 +0000 | [diff] [blame] | 288 | Attribute = namedtuple('Attribute', 'name kind defining_class object') |
| 289 | |
Tim Peters | 13b49d3 | 2001-09-23 02:00:29 +0000 | [diff] [blame] | 290 | def classify_class_attrs(cls): |
| 291 | """Return list of attribute-descriptor tuples. |
| 292 | |
| 293 | For each name in dir(cls), the return list contains a 4-tuple |
| 294 | with these elements: |
| 295 | |
| 296 | 0. The name (a string). |
| 297 | |
| 298 | 1. The kind of attribute this is, one of these strings: |
| 299 | 'class method' created via classmethod() |
| 300 | 'static method' created via staticmethod() |
| 301 | 'property' created via property() |
| 302 | 'method' any other flavor of method |
| 303 | 'data' not a method |
| 304 | |
| 305 | 2. The class which defined this attribute (a class). |
| 306 | |
| 307 | 3. The object as obtained directly from the defining class's |
| 308 | __dict__, not via getattr. This is especially important for |
| 309 | data attributes: C.data is just a data object, but |
| 310 | C.__dict__['data'] may be a data descriptor with additional |
| 311 | info, like a __doc__ string. |
| 312 | """ |
| 313 | |
| 314 | mro = getmro(cls) |
| 315 | names = dir(cls) |
| 316 | result = [] |
| 317 | for name in names: |
Antoine Pitrou | 86a8a9a | 2011-12-21 09:57:40 +0100 | [diff] [blame] | 318 | # Get the object associated with the name, and where it was defined. |
Tim Peters | 13b49d3 | 2001-09-23 02:00:29 +0000 | [diff] [blame] | 319 | # Getting an obj from the __dict__ sometimes reveals more than |
| 320 | # using getattr. Static and class methods are dramatic examples. |
Antoine Pitrou | 86a8a9a | 2011-12-21 09:57:40 +0100 | [diff] [blame] | 321 | # Furthermore, some objects may raise an Exception when fetched with |
| 322 | # getattr(). This is the case with some descriptors (bug #1785). |
| 323 | # Thus, we only use getattr() as a last resort. |
| 324 | homecls = None |
| 325 | for base in (cls,) + mro: |
| 326 | if name in base.__dict__: |
| 327 | obj = base.__dict__[name] |
| 328 | homecls = base |
| 329 | break |
Tim Peters | 13b49d3 | 2001-09-23 02:00:29 +0000 | [diff] [blame] | 330 | else: |
| 331 | obj = getattr(cls, name) |
Antoine Pitrou | 86a8a9a | 2011-12-21 09:57:40 +0100 | [diff] [blame] | 332 | homecls = getattr(obj, "__objclass__", homecls) |
Tim Peters | 13b49d3 | 2001-09-23 02:00:29 +0000 | [diff] [blame] | 333 | |
| 334 | # Classify the object. |
| 335 | if isinstance(obj, staticmethod): |
| 336 | kind = "static method" |
| 337 | elif isinstance(obj, classmethod): |
| 338 | kind = "class method" |
| 339 | elif isinstance(obj, property): |
| 340 | kind = "property" |
Antoine Pitrou | 86a8a9a | 2011-12-21 09:57:40 +0100 | [diff] [blame] | 341 | elif ismethoddescriptor(obj): |
Tim Peters | 13b49d3 | 2001-09-23 02:00:29 +0000 | [diff] [blame] | 342 | kind = "method" |
Antoine Pitrou | 86a8a9a | 2011-12-21 09:57:40 +0100 | [diff] [blame] | 343 | elif isdatadescriptor(obj): |
Tim Peters | 13b49d3 | 2001-09-23 02:00:29 +0000 | [diff] [blame] | 344 | kind = "data" |
Antoine Pitrou | 86a8a9a | 2011-12-21 09:57:40 +0100 | [diff] [blame] | 345 | else: |
| 346 | obj_via_getattr = getattr(cls, name) |
| 347 | if (isfunction(obj_via_getattr) or |
| 348 | ismethoddescriptor(obj_via_getattr)): |
| 349 | kind = "method" |
| 350 | else: |
| 351 | kind = "data" |
| 352 | obj = obj_via_getattr |
Tim Peters | 13b49d3 | 2001-09-23 02:00:29 +0000 | [diff] [blame] | 353 | |
Christian Heimes | 25bb783 | 2008-01-11 16:17:00 +0000 | [diff] [blame] | 354 | result.append(Attribute(name, kind, homecls, obj)) |
Tim Peters | 13b49d3 | 2001-09-23 02:00:29 +0000 | [diff] [blame] | 355 | |
| 356 | return result |
| 357 | |
Tim Peters | e0b2d7a | 2001-09-22 06:10:55 +0000 | [diff] [blame] | 358 | # ----------------------------------------------------------- class helpers |
Tim Peters | e0b2d7a | 2001-09-22 06:10:55 +0000 | [diff] [blame] | 359 | |
| 360 | def getmro(cls): |
| 361 | "Return tuple of base classes (including cls) in method resolution order." |
Benjamin Peterson | b82c8e5 | 2010-11-04 00:38:49 +0000 | [diff] [blame] | 362 | return cls.__mro__ |
Tim Peters | e0b2d7a | 2001-09-22 06:10:55 +0000 | [diff] [blame] | 363 | |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 364 | # -------------------------------------------------- source code extraction |
| 365 | def indentsize(line): |
| 366 | """Return the indent size, in spaces, at the start of a line of text.""" |
Neal Norwitz | 9d72bb4 | 2007-04-17 08:48:32 +0000 | [diff] [blame] | 367 | expline = line.expandtabs() |
| 368 | return len(expline) - len(expline.lstrip()) |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 369 | |
| 370 | def getdoc(object): |
| 371 | """Get the documentation string for an object. |
| 372 | |
| 373 | All tabs are expanded to spaces. To clean up docstrings that are |
| 374 | indented to line up with blocks of code, any whitespace than can be |
| 375 | uniformly removed from the second line onwards is removed.""" |
Tim Peters | 2400831 | 2002-03-17 18:56:20 +0000 | [diff] [blame] | 376 | try: |
| 377 | doc = object.__doc__ |
| 378 | except AttributeError: |
| 379 | return None |
Guido van Rossum | 3172c5d | 2007-10-16 18:12:55 +0000 | [diff] [blame] | 380 | if not isinstance(doc, str): |
Tim Peters | 2400831 | 2002-03-17 18:56:20 +0000 | [diff] [blame] | 381 | return None |
Georg Brandl | 0c77a82 | 2008-06-10 16:37:50 +0000 | [diff] [blame] | 382 | return cleandoc(doc) |
| 383 | |
| 384 | def cleandoc(doc): |
| 385 | """Clean up indentation from docstrings. |
| 386 | |
| 387 | Any whitespace that can be uniformly removed from the second line |
| 388 | onwards is removed.""" |
Tim Peters | 2400831 | 2002-03-17 18:56:20 +0000 | [diff] [blame] | 389 | try: |
Neal Norwitz | 9d72bb4 | 2007-04-17 08:48:32 +0000 | [diff] [blame] | 390 | lines = doc.expandtabs().split('\n') |
Tim Peters | 2400831 | 2002-03-17 18:56:20 +0000 | [diff] [blame] | 391 | except UnicodeError: |
| 392 | return None |
| 393 | else: |
Ka-Ping Yee | a59ef7b | 2002-11-30 03:53:15 +0000 | [diff] [blame] | 394 | # Find minimum indentation of any non-blank lines after first line. |
Christian Heimes | a37d4c6 | 2007-12-04 23:02:19 +0000 | [diff] [blame] | 395 | margin = sys.maxsize |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 396 | for line in lines[1:]: |
Neal Norwitz | 9d72bb4 | 2007-04-17 08:48:32 +0000 | [diff] [blame] | 397 | content = len(line.lstrip()) |
Ka-Ping Yee | a59ef7b | 2002-11-30 03:53:15 +0000 | [diff] [blame] | 398 | if content: |
| 399 | indent = len(line) - content |
| 400 | margin = min(margin, indent) |
| 401 | # Remove indentation. |
| 402 | if lines: |
| 403 | lines[0] = lines[0].lstrip() |
Christian Heimes | a37d4c6 | 2007-12-04 23:02:19 +0000 | [diff] [blame] | 404 | if margin < sys.maxsize: |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 405 | 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] | 406 | # Remove any trailing or leading blank lines. |
| 407 | while lines and not lines[-1]: |
| 408 | lines.pop() |
| 409 | while lines and not lines[0]: |
| 410 | lines.pop(0) |
Neal Norwitz | 9d72bb4 | 2007-04-17 08:48:32 +0000 | [diff] [blame] | 411 | return '\n'.join(lines) |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 412 | |
| 413 | def getfile(object): |
Ka-Ping Yee | c113c24 | 2001-03-02 02:08:53 +0000 | [diff] [blame] | 414 | """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] | 415 | if ismodule(object): |
| 416 | if hasattr(object, '__file__'): |
| 417 | return object.__file__ |
Benjamin Peterson | 4ac9ce4 | 2009-10-04 14:49:41 +0000 | [diff] [blame] | 418 | raise TypeError('{!r} is a built-in module'.format(object)) |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 419 | if isclass(object): |
Ka-Ping Yee | c99e0f1 | 2001-04-13 12:10:40 +0000 | [diff] [blame] | 420 | object = sys.modules.get(object.__module__) |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 421 | if hasattr(object, '__file__'): |
| 422 | return object.__file__ |
Benjamin Peterson | 4ac9ce4 | 2009-10-04 14:49:41 +0000 | [diff] [blame] | 423 | raise TypeError('{!r} is a built-in class'.format(object)) |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 424 | if ismethod(object): |
Christian Heimes | ff73795 | 2007-11-27 10:40:20 +0000 | [diff] [blame] | 425 | object = object.__func__ |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 426 | if isfunction(object): |
Neal Norwitz | 221085d | 2007-02-25 20:55:47 +0000 | [diff] [blame] | 427 | object = object.__code__ |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 428 | if istraceback(object): |
| 429 | object = object.tb_frame |
| 430 | if isframe(object): |
| 431 | object = object.f_code |
| 432 | if iscode(object): |
| 433 | return object.co_filename |
Benjamin Peterson | 4ac9ce4 | 2009-10-04 14:49:41 +0000 | [diff] [blame] | 434 | raise TypeError('{!r} is not a module, class, method, ' |
| 435 | 'function, traceback, frame, or code object'.format(object)) |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 436 | |
Christian Heimes | 25bb783 | 2008-01-11 16:17:00 +0000 | [diff] [blame] | 437 | ModuleInfo = namedtuple('ModuleInfo', 'name suffix mode module_type') |
| 438 | |
Ka-Ping Yee | 4d6fc7f | 2001-04-10 11:43:00 +0000 | [diff] [blame] | 439 | def getmoduleinfo(path): |
| 440 | """Get the module name, suffix, mode, and module type for a given file.""" |
Brett Cannon | cb66eb0 | 2012-05-11 12:58:42 -0400 | [diff] [blame] | 441 | warnings.warn('inspect.getmoduleinfo() is deprecated', DeprecationWarning, |
| 442 | 2) |
Ka-Ping Yee | 4d6fc7f | 2001-04-10 11:43:00 +0000 | [diff] [blame] | 443 | filename = os.path.basename(path) |
Guido van Rossum | 1bc535d | 2007-05-15 18:46:22 +0000 | [diff] [blame] | 444 | suffixes = [(-len(suffix), suffix, mode, mtype) |
| 445 | for suffix, mode, mtype in imp.get_suffixes()] |
Ka-Ping Yee | 4d6fc7f | 2001-04-10 11:43:00 +0000 | [diff] [blame] | 446 | suffixes.sort() # try longest suffixes first, in case they overlap |
| 447 | for neglen, suffix, mode, mtype in suffixes: |
| 448 | if filename[neglen:] == suffix: |
Christian Heimes | 25bb783 | 2008-01-11 16:17:00 +0000 | [diff] [blame] | 449 | return ModuleInfo(filename[:neglen], suffix, mode, mtype) |
Ka-Ping Yee | 4d6fc7f | 2001-04-10 11:43:00 +0000 | [diff] [blame] | 450 | |
| 451 | def getmodulename(path): |
| 452 | """Return the module name for a given file, or None.""" |
Nick Coghlan | 76e0770 | 2012-07-18 23:14:57 +1000 | [diff] [blame] | 453 | fname = os.path.basename(path) |
| 454 | # Check for paths that look like an actual module file |
| 455 | suffixes = [(-len(suffix), suffix) |
| 456 | for suffix in importlib.machinery.all_suffixes()] |
| 457 | suffixes.sort() # try longest suffixes first, in case they overlap |
| 458 | for neglen, suffix in suffixes: |
| 459 | if fname.endswith(suffix): |
| 460 | return fname[:neglen] |
| 461 | return None |
Ka-Ping Yee | 4d6fc7f | 2001-04-10 11:43:00 +0000 | [diff] [blame] | 462 | |
Ka-Ping Yee | c113c24 | 2001-03-02 02:08:53 +0000 | [diff] [blame] | 463 | def getsourcefile(object): |
R. David Murray | a1b3740 | 2010-06-17 02:04:29 +0000 | [diff] [blame] | 464 | """Return the filename that can be used to locate an object's source. |
| 465 | Return None if no way can be identified to get the source. |
| 466 | """ |
Ka-Ping Yee | c113c24 | 2001-03-02 02:08:53 +0000 | [diff] [blame] | 467 | filename = getfile(object) |
Brett Cannon | cb66eb0 | 2012-05-11 12:58:42 -0400 | [diff] [blame] | 468 | all_bytecode_suffixes = importlib.machinery.DEBUG_BYTECODE_SUFFIXES[:] |
| 469 | all_bytecode_suffixes += importlib.machinery.OPTIMIZED_BYTECODE_SUFFIXES[:] |
| 470 | if any(filename.endswith(s) for s in all_bytecode_suffixes): |
| 471 | filename = (os.path.splitext(filename)[0] + |
| 472 | importlib.machinery.SOURCE_SUFFIXES[0]) |
| 473 | elif any(filename.endswith(s) for s in |
| 474 | importlib.machinery.EXTENSION_SUFFIXES): |
| 475 | return None |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 476 | if os.path.exists(filename): |
| 477 | return filename |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 478 | # only return a non-existent filename if the module has a PEP 302 loader |
| 479 | if hasattr(getmodule(object, filename), '__loader__'): |
Ka-Ping Yee | c113c24 | 2001-03-02 02:08:53 +0000 | [diff] [blame] | 480 | return filename |
R. David Murray | a1b3740 | 2010-06-17 02:04:29 +0000 | [diff] [blame] | 481 | # or it is in the linecache |
| 482 | if filename in linecache.cache: |
| 483 | return filename |
Ka-Ping Yee | c113c24 | 2001-03-02 02:08:53 +0000 | [diff] [blame] | 484 | |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 485 | def getabsfile(object, _filename=None): |
Ka-Ping Yee | 4eb0c00 | 2001-03-02 05:50:34 +0000 | [diff] [blame] | 486 | """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] | 487 | |
Ka-Ping Yee | 4eb0c00 | 2001-03-02 05:50:34 +0000 | [diff] [blame] | 488 | The idea is for each object to have a unique origin, so this routine |
| 489 | normalizes the result as much as possible.""" |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 490 | if _filename is None: |
| 491 | _filename = getsourcefile(object) or getfile(object) |
| 492 | return os.path.normcase(os.path.abspath(_filename)) |
Ka-Ping Yee | c113c24 | 2001-03-02 02:08:53 +0000 | [diff] [blame] | 493 | |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 494 | modulesbyfile = {} |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 495 | _filesbymodname = {} |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 496 | |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 497 | def getmodule(object, _filename=None): |
Ka-Ping Yee | 4eb0c00 | 2001-03-02 05:50:34 +0000 | [diff] [blame] | 498 | """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] | 499 | if ismodule(object): |
| 500 | return object |
Johannes Gijsbers | 9324526 | 2004-09-11 15:53:22 +0000 | [diff] [blame] | 501 | if hasattr(object, '__module__'): |
Ka-Ping Yee | 8b58b84 | 2001-03-01 13:56:16 +0000 | [diff] [blame] | 502 | return sys.modules.get(object.__module__) |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 503 | # Try the filename to modulename cache |
| 504 | if _filename is not None and _filename in modulesbyfile: |
| 505 | return sys.modules.get(modulesbyfile[_filename]) |
| 506 | # Try the cache again with the absolute file name |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 507 | try: |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 508 | file = getabsfile(object, _filename) |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 509 | except TypeError: |
| 510 | return None |
Raymond Hettinger | 54f0222 | 2002-06-01 14:18:47 +0000 | [diff] [blame] | 511 | if file in modulesbyfile: |
Ka-Ping Yee | b38bbbd | 2003-03-28 16:29:50 +0000 | [diff] [blame] | 512 | return sys.modules.get(modulesbyfile[file]) |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 513 | # Update the filename to module name cache and check yet again |
| 514 | # Copy sys.modules in order to cope with changes while iterating |
Éric Araujo | a74f8ef | 2011-11-29 16:58:53 +0100 | [diff] [blame] | 515 | for modname, module in list(sys.modules.items()): |
Thomas Wouters | 49fd7fa | 2006-04-21 10:40:58 +0000 | [diff] [blame] | 516 | if ismodule(module) and hasattr(module, '__file__'): |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 517 | f = module.__file__ |
| 518 | if f == _filesbymodname.get(modname, None): |
| 519 | # Have already mapped this module, so skip it |
| 520 | continue |
| 521 | _filesbymodname[modname] = f |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 522 | f = getabsfile(module) |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 523 | # Always map to the name the module knows itself by |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 524 | modulesbyfile[f] = modulesbyfile[ |
| 525 | os.path.realpath(f)] = module.__name__ |
Raymond Hettinger | 54f0222 | 2002-06-01 14:18:47 +0000 | [diff] [blame] | 526 | if file in modulesbyfile: |
Ka-Ping Yee | b38bbbd | 2003-03-28 16:29:50 +0000 | [diff] [blame] | 527 | return sys.modules.get(modulesbyfile[file]) |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 528 | # Check the main module |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 529 | main = sys.modules['__main__'] |
Brett Cannon | 4a671fe | 2003-06-15 22:33:28 +0000 | [diff] [blame] | 530 | if not hasattr(object, '__name__'): |
| 531 | return None |
Ka-Ping Yee | 4eb0c00 | 2001-03-02 05:50:34 +0000 | [diff] [blame] | 532 | if hasattr(main, object.__name__): |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 533 | mainobject = getattr(main, object.__name__) |
Ka-Ping Yee | 4eb0c00 | 2001-03-02 05:50:34 +0000 | [diff] [blame] | 534 | if mainobject is object: |
| 535 | return main |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 536 | # Check builtins |
Georg Brandl | 1a3284e | 2007-12-02 09:40:06 +0000 | [diff] [blame] | 537 | builtin = sys.modules['builtins'] |
Ka-Ping Yee | 4eb0c00 | 2001-03-02 05:50:34 +0000 | [diff] [blame] | 538 | if hasattr(builtin, object.__name__): |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 539 | builtinobject = getattr(builtin, object.__name__) |
Ka-Ping Yee | 4eb0c00 | 2001-03-02 05:50:34 +0000 | [diff] [blame] | 540 | if builtinobject is object: |
| 541 | return builtin |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 542 | |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 543 | def findsource(object): |
| 544 | """Return the entire source file and starting line number for an object. |
| 545 | |
| 546 | The argument may be a module, class, method, function, traceback, frame, |
| 547 | or code object. The source code is returned as a list of all the lines |
| 548 | in the file and the line number indexes a line in that list. An IOError |
| 549 | is raised if the source code cannot be retrieved.""" |
Benjamin Peterson | 9620cc0 | 2011-06-11 15:53:11 -0500 | [diff] [blame] | 550 | |
| 551 | file = getfile(object) |
| 552 | sourcefile = getsourcefile(object) |
Ezio Melotti | 1b14592 | 2013-03-30 05:17:24 +0200 | [diff] [blame] | 553 | if not sourcefile and file[:1] + file[-1:] != '<>': |
R. David Murray | 74b8924 | 2009-05-13 17:33:03 +0000 | [diff] [blame] | 554 | raise IOError('source code not available') |
Benjamin Peterson | 9620cc0 | 2011-06-11 15:53:11 -0500 | [diff] [blame] | 555 | file = sourcefile if sourcefile else file |
| 556 | |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 557 | module = getmodule(object, file) |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 558 | if module: |
| 559 | lines = linecache.getlines(file, module.__dict__) |
| 560 | else: |
| 561 | lines = linecache.getlines(file) |
Neil Schemenauer | f06f853 | 2002-03-23 23:51:04 +0000 | [diff] [blame] | 562 | if not lines: |
Jeremy Hylton | ab91902 | 2003-06-27 18:41:20 +0000 | [diff] [blame] | 563 | raise IOError('could not get source code') |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 564 | |
| 565 | if ismodule(object): |
| 566 | return lines, 0 |
| 567 | |
| 568 | if isclass(object): |
| 569 | name = object.__name__ |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 570 | pat = re.compile(r'^(\s*)class\s*' + name + r'\b') |
| 571 | # make some effort to find the best matching class definition: |
| 572 | # use the one with the least indentation, which is the one |
| 573 | # that's most probably not inside a function definition. |
| 574 | candidates = [] |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 575 | for i in range(len(lines)): |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 576 | match = pat.match(lines[i]) |
| 577 | if match: |
| 578 | # if it's at toplevel, it's already the best one |
| 579 | if lines[i][0] == 'c': |
| 580 | return lines, i |
| 581 | # else add whitespace to candidate list |
| 582 | candidates.append((match.group(1), i)) |
| 583 | if candidates: |
| 584 | # this will sort by whitespace, and by line number, |
| 585 | # less whitespace first |
| 586 | candidates.sort() |
| 587 | return lines, candidates[0][1] |
Jeremy Hylton | ab91902 | 2003-06-27 18:41:20 +0000 | [diff] [blame] | 588 | else: |
| 589 | raise IOError('could not find class definition') |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 590 | |
| 591 | if ismethod(object): |
Christian Heimes | ff73795 | 2007-11-27 10:40:20 +0000 | [diff] [blame] | 592 | object = object.__func__ |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 593 | if isfunction(object): |
Neal Norwitz | 221085d | 2007-02-25 20:55:47 +0000 | [diff] [blame] | 594 | object = object.__code__ |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 595 | if istraceback(object): |
| 596 | object = object.tb_frame |
| 597 | if isframe(object): |
| 598 | object = object.f_code |
| 599 | if iscode(object): |
Ka-Ping Yee | 4eb0c00 | 2001-03-02 05:50:34 +0000 | [diff] [blame] | 600 | if not hasattr(object, 'co_firstlineno'): |
Jeremy Hylton | ab91902 | 2003-06-27 18:41:20 +0000 | [diff] [blame] | 601 | raise IOError('could not find function definition') |
Ka-Ping Yee | 4eb0c00 | 2001-03-02 05:50:34 +0000 | [diff] [blame] | 602 | lnum = object.co_firstlineno - 1 |
Johannes Gijsbers | 1542f34 | 2004-12-12 16:46:28 +0000 | [diff] [blame] | 603 | pat = re.compile(r'^(\s*def\s)|(.*(?<!\w)lambda(:|\s))|^(\s*@)') |
Ka-Ping Yee | 4eb0c00 | 2001-03-02 05:50:34 +0000 | [diff] [blame] | 604 | while lnum > 0: |
Ka-Ping Yee | a6e5971 | 2001-03-10 09:31:55 +0000 | [diff] [blame] | 605 | if pat.match(lines[lnum]): break |
Ka-Ping Yee | 4eb0c00 | 2001-03-02 05:50:34 +0000 | [diff] [blame] | 606 | lnum = lnum - 1 |
| 607 | return lines, lnum |
Jeremy Hylton | ab91902 | 2003-06-27 18:41:20 +0000 | [diff] [blame] | 608 | raise IOError('could not find code object') |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 609 | |
| 610 | def getcomments(object): |
Jeremy Hylton | b4c17c8 | 2002-03-28 23:01:56 +0000 | [diff] [blame] | 611 | """Get lines of comments immediately preceding an object's source code. |
| 612 | |
| 613 | Returns None when source can't be found. |
| 614 | """ |
| 615 | try: |
| 616 | lines, lnum = findsource(object) |
| 617 | except (IOError, TypeError): |
| 618 | return None |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 619 | |
| 620 | if ismodule(object): |
| 621 | # Look for a comment block at the top of the file. |
| 622 | start = 0 |
Ka-Ping Yee | b910efe | 2001-04-12 13:17:17 +0000 | [diff] [blame] | 623 | if lines and lines[0][:2] == '#!': start = 1 |
Neal Norwitz | 9d72bb4 | 2007-04-17 08:48:32 +0000 | [diff] [blame] | 624 | while start < len(lines) and lines[start].strip() in ('', '#'): |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 625 | start = start + 1 |
Ka-Ping Yee | b910efe | 2001-04-12 13:17:17 +0000 | [diff] [blame] | 626 | if start < len(lines) and lines[start][:1] == '#': |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 627 | comments = [] |
| 628 | end = start |
| 629 | while end < len(lines) and lines[end][:1] == '#': |
Neal Norwitz | 9d72bb4 | 2007-04-17 08:48:32 +0000 | [diff] [blame] | 630 | comments.append(lines[end].expandtabs()) |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 631 | end = end + 1 |
Neal Norwitz | 9d72bb4 | 2007-04-17 08:48:32 +0000 | [diff] [blame] | 632 | return ''.join(comments) |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 633 | |
| 634 | # Look for a preceding block of comments at the same indentation. |
| 635 | elif lnum > 0: |
| 636 | indent = indentsize(lines[lnum]) |
| 637 | end = lnum - 1 |
Neal Norwitz | 9d72bb4 | 2007-04-17 08:48:32 +0000 | [diff] [blame] | 638 | if end >= 0 and lines[end].lstrip()[:1] == '#' and \ |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 639 | indentsize(lines[end]) == indent: |
Neal Norwitz | 9d72bb4 | 2007-04-17 08:48:32 +0000 | [diff] [blame] | 640 | comments = [lines[end].expandtabs().lstrip()] |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 641 | if end > 0: |
| 642 | end = end - 1 |
Neal Norwitz | 9d72bb4 | 2007-04-17 08:48:32 +0000 | [diff] [blame] | 643 | comment = lines[end].expandtabs().lstrip() |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 644 | while comment[:1] == '#' and indentsize(lines[end]) == indent: |
| 645 | comments[:0] = [comment] |
| 646 | end = end - 1 |
| 647 | if end < 0: break |
Neal Norwitz | 9d72bb4 | 2007-04-17 08:48:32 +0000 | [diff] [blame] | 648 | comment = lines[end].expandtabs().lstrip() |
| 649 | while comments and comments[0].strip() == '#': |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 650 | comments[:1] = [] |
Neal Norwitz | 9d72bb4 | 2007-04-17 08:48:32 +0000 | [diff] [blame] | 651 | while comments and comments[-1].strip() == '#': |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 652 | comments[-1:] = [] |
Neal Norwitz | 9d72bb4 | 2007-04-17 08:48:32 +0000 | [diff] [blame] | 653 | return ''.join(comments) |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 654 | |
Tim Peters | 4efb6e9 | 2001-06-29 23:51:08 +0000 | [diff] [blame] | 655 | class EndOfBlock(Exception): pass |
| 656 | |
| 657 | class BlockFinder: |
| 658 | """Provide a tokeneater() method to detect the end of a code block.""" |
| 659 | def __init__(self): |
| 660 | self.indent = 0 |
Johannes Gijsbers | a5855d5 | 2005-03-12 16:37:11 +0000 | [diff] [blame] | 661 | self.islambda = False |
Johannes Gijsbers | 1542f34 | 2004-12-12 16:46:28 +0000 | [diff] [blame] | 662 | self.started = False |
| 663 | self.passline = False |
Armin Rigo | dd5c023 | 2005-09-25 11:45:45 +0000 | [diff] [blame] | 664 | self.last = 1 |
Tim Peters | 4efb6e9 | 2001-06-29 23:51:08 +0000 | [diff] [blame] | 665 | |
Guido van Rossum | 1bc535d | 2007-05-15 18:46:22 +0000 | [diff] [blame] | 666 | def tokeneater(self, type, token, srowcol, erowcol, line): |
Tim Peters | 4efb6e9 | 2001-06-29 23:51:08 +0000 | [diff] [blame] | 667 | if not self.started: |
Armin Rigo | dd5c023 | 2005-09-25 11:45:45 +0000 | [diff] [blame] | 668 | # look for the first "def", "class" or "lambda" |
Johannes Gijsbers | 1542f34 | 2004-12-12 16:46:28 +0000 | [diff] [blame] | 669 | if token in ("def", "class", "lambda"): |
Johannes Gijsbers | a5855d5 | 2005-03-12 16:37:11 +0000 | [diff] [blame] | 670 | if token == "lambda": |
| 671 | self.islambda = True |
Johannes Gijsbers | 1542f34 | 2004-12-12 16:46:28 +0000 | [diff] [blame] | 672 | self.started = True |
Armin Rigo | dd5c023 | 2005-09-25 11:45:45 +0000 | [diff] [blame] | 673 | self.passline = True # skip to the end of the line |
Tim Peters | 4efb6e9 | 2001-06-29 23:51:08 +0000 | [diff] [blame] | 674 | elif type == tokenize.NEWLINE: |
Armin Rigo | dd5c023 | 2005-09-25 11:45:45 +0000 | [diff] [blame] | 675 | self.passline = False # stop skipping when a NEWLINE is seen |
Guido van Rossum | 1bc535d | 2007-05-15 18:46:22 +0000 | [diff] [blame] | 676 | self.last = srowcol[0] |
Armin Rigo | dd5c023 | 2005-09-25 11:45:45 +0000 | [diff] [blame] | 677 | if self.islambda: # lambdas always end at the first NEWLINE |
| 678 | raise EndOfBlock |
Johannes Gijsbers | 1542f34 | 2004-12-12 16:46:28 +0000 | [diff] [blame] | 679 | elif self.passline: |
| 680 | pass |
Tim Peters | 4efb6e9 | 2001-06-29 23:51:08 +0000 | [diff] [blame] | 681 | elif type == tokenize.INDENT: |
| 682 | self.indent = self.indent + 1 |
Johannes Gijsbers | 1542f34 | 2004-12-12 16:46:28 +0000 | [diff] [blame] | 683 | self.passline = True |
Tim Peters | 4efb6e9 | 2001-06-29 23:51:08 +0000 | [diff] [blame] | 684 | elif type == tokenize.DEDENT: |
| 685 | self.indent = self.indent - 1 |
Armin Rigo | dd5c023 | 2005-09-25 11:45:45 +0000 | [diff] [blame] | 686 | # the end of matching indent/dedent pairs end a block |
| 687 | # (note that this only works for "def"/"class" blocks, |
| 688 | # not e.g. for "if: else:" or "try: finally:" blocks) |
| 689 | if self.indent <= 0: |
| 690 | raise EndOfBlock |
| 691 | elif self.indent == 0 and type not in (tokenize.COMMENT, tokenize.NL): |
| 692 | # any other token on the same indentation level end the previous |
| 693 | # block as well, except the pseudo-tokens COMMENT and NL. |
| 694 | raise EndOfBlock |
Tim Peters | 4efb6e9 | 2001-06-29 23:51:08 +0000 | [diff] [blame] | 695 | |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 696 | def getblock(lines): |
| 697 | """Extract the block of code at the top of the given list of lines.""" |
Armin Rigo | dd5c023 | 2005-09-25 11:45:45 +0000 | [diff] [blame] | 698 | blockfinder = BlockFinder() |
Tim Peters | 4efb6e9 | 2001-06-29 23:51:08 +0000 | [diff] [blame] | 699 | try: |
Trent Nelson | 428de65 | 2008-03-18 22:41:35 +0000 | [diff] [blame] | 700 | tokens = tokenize.generate_tokens(iter(lines).__next__) |
| 701 | for _token in tokens: |
| 702 | blockfinder.tokeneater(*_token) |
Armin Rigo | dd5c023 | 2005-09-25 11:45:45 +0000 | [diff] [blame] | 703 | except (EndOfBlock, IndentationError): |
| 704 | pass |
| 705 | return lines[:blockfinder.last] |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 706 | |
| 707 | def getsourcelines(object): |
| 708 | """Return a list of source lines and starting line number for an object. |
| 709 | |
| 710 | The argument may be a module, class, method, function, traceback, frame, |
| 711 | or code object. The source code is returned as a list of the lines |
| 712 | corresponding to the object and the line number indicates where in the |
| 713 | original source file the first line of code was found. An IOError is |
| 714 | raised if the source code cannot be retrieved.""" |
| 715 | lines, lnum = findsource(object) |
| 716 | |
| 717 | if ismodule(object): return lines, 0 |
| 718 | else: return getblock(lines[lnum:]), lnum + 1 |
| 719 | |
| 720 | def getsource(object): |
| 721 | """Return the text of the source code for an object. |
| 722 | |
| 723 | The argument may be a module, class, method, function, traceback, frame, |
| 724 | or code object. The source code is returned as a single string. An |
| 725 | IOError is raised if the source code cannot be retrieved.""" |
| 726 | lines, lnum = getsourcelines(object) |
Neal Norwitz | 9d72bb4 | 2007-04-17 08:48:32 +0000 | [diff] [blame] | 727 | return ''.join(lines) |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 728 | |
| 729 | # --------------------------------------------------- class tree extraction |
| 730 | def walktree(classes, children, parent): |
| 731 | """Recursive helper function for getclasstree().""" |
| 732 | results = [] |
Raymond Hettinger | a1a992c | 2005-03-11 06:46:45 +0000 | [diff] [blame] | 733 | classes.sort(key=attrgetter('__module__', '__name__')) |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 734 | for c in classes: |
| 735 | results.append((c, c.__bases__)) |
Raymond Hettinger | 54f0222 | 2002-06-01 14:18:47 +0000 | [diff] [blame] | 736 | if c in children: |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 737 | results.append(walktree(children[c], children, c)) |
| 738 | return results |
| 739 | |
Georg Brandl | 5ce83a0 | 2009-06-01 17:23:51 +0000 | [diff] [blame] | 740 | def getclasstree(classes, unique=False): |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 741 | """Arrange the given list of classes into a hierarchy of nested lists. |
| 742 | |
| 743 | Where a nested list appears, it contains classes derived from the class |
| 744 | whose entry immediately precedes the list. Each entry is a 2-tuple |
| 745 | containing a class and a tuple of its base classes. If the 'unique' |
| 746 | argument is true, exactly one entry appears in the returned structure |
| 747 | for each class in the given list. Otherwise, classes using multiple |
| 748 | inheritance and their descendants will appear multiple times.""" |
| 749 | children = {} |
| 750 | roots = [] |
| 751 | for c in classes: |
| 752 | if c.__bases__: |
| 753 | for parent in c.__bases__: |
Raymond Hettinger | 54f0222 | 2002-06-01 14:18:47 +0000 | [diff] [blame] | 754 | if not parent in children: |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 755 | children[parent] = [] |
Serhiy Storchaka | 362c1b5 | 2013-09-05 17:14:32 +0300 | [diff] [blame] | 756 | if c not in children[parent]: |
| 757 | children[parent].append(c) |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 758 | if unique and parent in classes: break |
| 759 | elif c not in roots: |
| 760 | roots.append(c) |
Raymond Hettinger | e0d4972 | 2002-06-02 18:55:56 +0000 | [diff] [blame] | 761 | for parent in children: |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 762 | if parent not in classes: |
| 763 | roots.append(parent) |
| 764 | return walktree(roots, children, None) |
| 765 | |
| 766 | # ------------------------------------------------ argument list extraction |
Christian Heimes | 25bb783 | 2008-01-11 16:17:00 +0000 | [diff] [blame] | 767 | Arguments = namedtuple('Arguments', 'args, varargs, varkw') |
| 768 | |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 769 | def getargs(co): |
| 770 | """Get information about the arguments accepted by a code object. |
| 771 | |
Guido van Rossum | 2e65f89 | 2007-02-28 22:03:49 +0000 | [diff] [blame] | 772 | Three things are returned: (args, varargs, varkw), where |
Georg Brandl | c1c4bf8 | 2010-10-15 16:07:41 +0000 | [diff] [blame] | 773 | 'args' is the list of argument names. Keyword-only arguments are |
| 774 | appended. 'varargs' and 'varkw' are the names of the * and ** |
| 775 | arguments or None.""" |
Guido van Rossum | 2e65f89 | 2007-02-28 22:03:49 +0000 | [diff] [blame] | 776 | args, varargs, kwonlyargs, varkw = _getfullargs(co) |
Christian Heimes | 25bb783 | 2008-01-11 16:17:00 +0000 | [diff] [blame] | 777 | return Arguments(args + kwonlyargs, varargs, varkw) |
Guido van Rossum | 2e65f89 | 2007-02-28 22:03:49 +0000 | [diff] [blame] | 778 | |
| 779 | def _getfullargs(co): |
| 780 | """Get information about the arguments accepted by a code object. |
| 781 | |
| 782 | Four things are returned: (args, varargs, kwonlyargs, varkw), where |
Georg Brandl | c1c4bf8 | 2010-10-15 16:07:41 +0000 | [diff] [blame] | 783 | 'args' and 'kwonlyargs' are lists of argument names, and 'varargs' |
| 784 | and 'varkw' are the names of the * and ** arguments or None.""" |
Jeremy Hylton | 6496788 | 2003-06-27 18:14:39 +0000 | [diff] [blame] | 785 | |
| 786 | if not iscode(co): |
Benjamin Peterson | 4ac9ce4 | 2009-10-04 14:49:41 +0000 | [diff] [blame] | 787 | raise TypeError('{!r} is not a code object'.format(co)) |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 788 | |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 789 | nargs = co.co_argcount |
| 790 | names = co.co_varnames |
Guido van Rossum | 2e65f89 | 2007-02-28 22:03:49 +0000 | [diff] [blame] | 791 | nkwargs = co.co_kwonlyargcount |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 792 | args = list(names[:nargs]) |
Guido van Rossum | 2e65f89 | 2007-02-28 22:03:49 +0000 | [diff] [blame] | 793 | kwonlyargs = list(names[nargs:nargs+nkwargs]) |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 794 | step = 0 |
| 795 | |
Guido van Rossum | 2e65f89 | 2007-02-28 22:03:49 +0000 | [diff] [blame] | 796 | nargs += nkwargs |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 797 | varargs = None |
| 798 | if co.co_flags & CO_VARARGS: |
| 799 | varargs = co.co_varnames[nargs] |
| 800 | nargs = nargs + 1 |
| 801 | varkw = None |
| 802 | if co.co_flags & CO_VARKEYWORDS: |
| 803 | varkw = co.co_varnames[nargs] |
Guido van Rossum | 2e65f89 | 2007-02-28 22:03:49 +0000 | [diff] [blame] | 804 | return args, varargs, kwonlyargs, varkw |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 805 | |
Christian Heimes | 25bb783 | 2008-01-11 16:17:00 +0000 | [diff] [blame] | 806 | |
| 807 | ArgSpec = namedtuple('ArgSpec', 'args varargs keywords defaults') |
| 808 | |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 809 | def getargspec(func): |
| 810 | """Get the names and default values of a function's arguments. |
| 811 | |
| 812 | A tuple of four things is returned: (args, varargs, varkw, defaults). |
Georg Brandl | c1c4bf8 | 2010-10-15 16:07:41 +0000 | [diff] [blame] | 813 | 'args' is a list of the argument names. |
Guido van Rossum | 2e65f89 | 2007-02-28 22:03:49 +0000 | [diff] [blame] | 814 | 'args' will include keyword-only argument names. |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 815 | 'varargs' and 'varkw' are the names of the * and ** arguments or None. |
Jeremy Hylton | 6496788 | 2003-06-27 18:14:39 +0000 | [diff] [blame] | 816 | 'defaults' is an n-tuple of the default values of the last n arguments. |
Guido van Rossum | a8add0e | 2007-05-14 22:03:55 +0000 | [diff] [blame] | 817 | |
Guido van Rossum | 2e65f89 | 2007-02-28 22:03:49 +0000 | [diff] [blame] | 818 | Use the getfullargspec() API for Python-3000 code, as annotations |
| 819 | and keyword arguments are supported. getargspec() will raise ValueError |
| 820 | if the func has either annotations or keyword arguments. |
| 821 | """ |
| 822 | |
| 823 | args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults, ann = \ |
| 824 | getfullargspec(func) |
| 825 | if kwonlyargs or ann: |
Collin Winter | ce36ad8 | 2007-08-30 01:19:48 +0000 | [diff] [blame] | 826 | raise ValueError("Function has keyword-only arguments or annotations" |
| 827 | ", use getfullargspec() API which can support them") |
Christian Heimes | 25bb783 | 2008-01-11 16:17:00 +0000 | [diff] [blame] | 828 | return ArgSpec(args, varargs, varkw, defaults) |
| 829 | |
| 830 | FullArgSpec = namedtuple('FullArgSpec', |
Benjamin Peterson | 3d4ca74 | 2008-11-12 21:39:01 +0000 | [diff] [blame] | 831 | 'args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults, annotations') |
Guido van Rossum | 2e65f89 | 2007-02-28 22:03:49 +0000 | [diff] [blame] | 832 | |
| 833 | def getfullargspec(func): |
| 834 | """Get the names and default values of a function's arguments. |
| 835 | |
Brett Cannon | 504d885 | 2007-09-07 02:12:14 +0000 | [diff] [blame] | 836 | A tuple of seven things is returned: |
| 837 | (args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults annotations). |
Georg Brandl | c1c4bf8 | 2010-10-15 16:07:41 +0000 | [diff] [blame] | 838 | 'args' is a list of the argument names. |
Guido van Rossum | 2e65f89 | 2007-02-28 22:03:49 +0000 | [diff] [blame] | 839 | 'varargs' and 'varkw' are the names of the * and ** arguments or None. |
| 840 | 'defaults' is an n-tuple of the default values of the last n arguments. |
| 841 | 'kwonlyargs' is a list of keyword-only argument names. |
| 842 | 'kwonlydefaults' is a dictionary mapping names from kwonlyargs to defaults. |
| 843 | 'annotations' is a dictionary mapping argument names to annotations. |
Guido van Rossum | a8add0e | 2007-05-14 22:03:55 +0000 | [diff] [blame] | 844 | |
Guido van Rossum | 2e65f89 | 2007-02-28 22:03:49 +0000 | [diff] [blame] | 845 | The first four items in the tuple correspond to getargspec(). |
Jeremy Hylton | 6496788 | 2003-06-27 18:14:39 +0000 | [diff] [blame] | 846 | """ |
| 847 | |
| 848 | if ismethod(func): |
Christian Heimes | ff73795 | 2007-11-27 10:40:20 +0000 | [diff] [blame] | 849 | func = func.__func__ |
Jeremy Hylton | 6496788 | 2003-06-27 18:14:39 +0000 | [diff] [blame] | 850 | if not isfunction(func): |
Benjamin Peterson | 4ac9ce4 | 2009-10-04 14:49:41 +0000 | [diff] [blame] | 851 | raise TypeError('{!r} is not a Python function'.format(func)) |
Guido van Rossum | 2e65f89 | 2007-02-28 22:03:49 +0000 | [diff] [blame] | 852 | args, varargs, kwonlyargs, varkw = _getfullargs(func.__code__) |
Christian Heimes | 25bb783 | 2008-01-11 16:17:00 +0000 | [diff] [blame] | 853 | return FullArgSpec(args, varargs, varkw, func.__defaults__, |
Guido van Rossum | 2e65f89 | 2007-02-28 22:03:49 +0000 | [diff] [blame] | 854 | kwonlyargs, func.__kwdefaults__, func.__annotations__) |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 855 | |
Christian Heimes | 25bb783 | 2008-01-11 16:17:00 +0000 | [diff] [blame] | 856 | ArgInfo = namedtuple('ArgInfo', 'args varargs keywords locals') |
| 857 | |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 858 | def getargvalues(frame): |
| 859 | """Get information about arguments passed into a particular frame. |
| 860 | |
| 861 | A tuple of four things is returned: (args, varargs, varkw, locals). |
Georg Brandl | c1c4bf8 | 2010-10-15 16:07:41 +0000 | [diff] [blame] | 862 | 'args' is a list of the argument names. |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 863 | 'varargs' and 'varkw' are the names of the * and ** arguments or None. |
| 864 | 'locals' is the locals dictionary of the given frame.""" |
| 865 | args, varargs, varkw = getargs(frame.f_code) |
Benjamin Peterson | 1a6e0d0 | 2008-10-25 15:49:17 +0000 | [diff] [blame] | 866 | return ArgInfo(args, varargs, varkw, frame.f_locals) |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 867 | |
Guido van Rossum | 2e65f89 | 2007-02-28 22:03:49 +0000 | [diff] [blame] | 868 | def formatannotation(annotation, base_module=None): |
| 869 | if isinstance(annotation, type): |
Georg Brandl | 1a3284e | 2007-12-02 09:40:06 +0000 | [diff] [blame] | 870 | if annotation.__module__ in ('builtins', base_module): |
Guido van Rossum | 2e65f89 | 2007-02-28 22:03:49 +0000 | [diff] [blame] | 871 | return annotation.__name__ |
| 872 | return annotation.__module__+'.'+annotation.__name__ |
| 873 | return repr(annotation) |
Guido van Rossum | a8add0e | 2007-05-14 22:03:55 +0000 | [diff] [blame] | 874 | |
Guido van Rossum | 2e65f89 | 2007-02-28 22:03:49 +0000 | [diff] [blame] | 875 | def formatannotationrelativeto(object): |
Guido van Rossum | a8add0e | 2007-05-14 22:03:55 +0000 | [diff] [blame] | 876 | module = getattr(object, '__module__', None) |
| 877 | def _formatannotation(annotation): |
| 878 | return formatannotation(annotation, module) |
| 879 | return _formatannotation |
Guido van Rossum | 2e65f89 | 2007-02-28 22:03:49 +0000 | [diff] [blame] | 880 | |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 881 | def formatargspec(args, varargs=None, varkw=None, defaults=None, |
Guido van Rossum | 2e65f89 | 2007-02-28 22:03:49 +0000 | [diff] [blame] | 882 | kwonlyargs=(), kwonlydefaults={}, annotations={}, |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 883 | formatarg=str, |
| 884 | formatvarargs=lambda name: '*' + name, |
| 885 | formatvarkw=lambda name: '**' + name, |
| 886 | formatvalue=lambda value: '=' + repr(value), |
Guido van Rossum | 2e65f89 | 2007-02-28 22:03:49 +0000 | [diff] [blame] | 887 | formatreturns=lambda text: ' -> ' + text, |
Georg Brandl | c1c4bf8 | 2010-10-15 16:07:41 +0000 | [diff] [blame] | 888 | formatannotation=formatannotation): |
Guido van Rossum | a8add0e | 2007-05-14 22:03:55 +0000 | [diff] [blame] | 889 | """Format an argument spec from the values returned by getargspec |
Guido van Rossum | 2e65f89 | 2007-02-28 22:03:49 +0000 | [diff] [blame] | 890 | or getfullargspec. |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 891 | |
Guido van Rossum | 2e65f89 | 2007-02-28 22:03:49 +0000 | [diff] [blame] | 892 | The first seven arguments are (args, varargs, varkw, defaults, |
| 893 | kwonlyargs, kwonlydefaults, annotations). The other five arguments |
| 894 | are the corresponding optional formatting functions that are called to |
| 895 | turn names and values into strings. The last argument is an optional |
| 896 | function to format the sequence of arguments.""" |
| 897 | def formatargandannotation(arg): |
| 898 | result = formatarg(arg) |
| 899 | if arg in annotations: |
| 900 | result += ': ' + formatannotation(annotations[arg]) |
| 901 | return result |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 902 | specs = [] |
| 903 | if defaults: |
| 904 | firstdefault = len(args) - len(defaults) |
Benjamin Peterson | b58dda7 | 2009-01-18 22:27:04 +0000 | [diff] [blame] | 905 | for i, arg in enumerate(args): |
Georg Brandl | c1c4bf8 | 2010-10-15 16:07:41 +0000 | [diff] [blame] | 906 | spec = formatargandannotation(arg) |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 907 | if defaults and i >= firstdefault: |
| 908 | spec = spec + formatvalue(defaults[i - firstdefault]) |
| 909 | specs.append(spec) |
Raymond Hettinger | 936654b | 2002-06-01 03:06:31 +0000 | [diff] [blame] | 910 | if varargs is not None: |
Guido van Rossum | 2e65f89 | 2007-02-28 22:03:49 +0000 | [diff] [blame] | 911 | specs.append(formatvarargs(formatargandannotation(varargs))) |
| 912 | else: |
| 913 | if kwonlyargs: |
| 914 | specs.append('*') |
| 915 | if kwonlyargs: |
| 916 | for kwonlyarg in kwonlyargs: |
| 917 | spec = formatargandannotation(kwonlyarg) |
Benjamin Peterson | 9953a8d | 2009-01-17 04:15:01 +0000 | [diff] [blame] | 918 | if kwonlydefaults and kwonlyarg in kwonlydefaults: |
Guido van Rossum | 2e65f89 | 2007-02-28 22:03:49 +0000 | [diff] [blame] | 919 | spec += formatvalue(kwonlydefaults[kwonlyarg]) |
| 920 | specs.append(spec) |
Raymond Hettinger | 936654b | 2002-06-01 03:06:31 +0000 | [diff] [blame] | 921 | if varkw is not None: |
Guido van Rossum | 2e65f89 | 2007-02-28 22:03:49 +0000 | [diff] [blame] | 922 | specs.append(formatvarkw(formatargandannotation(varkw))) |
Neal Norwitz | 9d72bb4 | 2007-04-17 08:48:32 +0000 | [diff] [blame] | 923 | result = '(' + ', '.join(specs) + ')' |
Guido van Rossum | 2e65f89 | 2007-02-28 22:03:49 +0000 | [diff] [blame] | 924 | if 'return' in annotations: |
| 925 | result += formatreturns(formatannotation(annotations['return'])) |
| 926 | return result |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 927 | |
| 928 | def formatargvalues(args, varargs, varkw, locals, |
| 929 | formatarg=str, |
| 930 | formatvarargs=lambda name: '*' + name, |
| 931 | formatvarkw=lambda name: '**' + name, |
Georg Brandl | c1c4bf8 | 2010-10-15 16:07:41 +0000 | [diff] [blame] | 932 | formatvalue=lambda value: '=' + repr(value)): |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 933 | """Format an argument spec from the 4 values returned by getargvalues. |
| 934 | |
| 935 | The first four arguments are (args, varargs, varkw, locals). The |
| 936 | next four arguments are the corresponding optional formatting functions |
| 937 | that are called to turn names and values into strings. The ninth |
| 938 | argument is an optional function to format the sequence of arguments.""" |
| 939 | def convert(name, locals=locals, |
| 940 | formatarg=formatarg, formatvalue=formatvalue): |
| 941 | return formatarg(name) + formatvalue(locals[name]) |
| 942 | specs = [] |
| 943 | for i in range(len(args)): |
Georg Brandl | c1c4bf8 | 2010-10-15 16:07:41 +0000 | [diff] [blame] | 944 | specs.append(convert(args[i])) |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 945 | if varargs: |
| 946 | specs.append(formatvarargs(varargs) + formatvalue(locals[varargs])) |
| 947 | if varkw: |
| 948 | specs.append(formatvarkw(varkw) + formatvalue(locals[varkw])) |
Neal Norwitz | 9d72bb4 | 2007-04-17 08:48:32 +0000 | [diff] [blame] | 949 | return '(' + ', '.join(specs) + ')' |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 950 | |
Benjamin Peterson | e109c70 | 2011-06-24 09:37:26 -0500 | [diff] [blame] | 951 | def _missing_arguments(f_name, argnames, pos, values): |
| 952 | names = [repr(name) for name in argnames if name not in values] |
| 953 | missing = len(names) |
| 954 | if missing == 1: |
| 955 | s = names[0] |
| 956 | elif missing == 2: |
| 957 | s = "{} and {}".format(*names) |
| 958 | else: |
| 959 | tail = ", {} and {}".format(names[-2:]) |
| 960 | del names[-2:] |
| 961 | s = ", ".join(names) + tail |
| 962 | raise TypeError("%s() missing %i required %s argument%s: %s" % |
| 963 | (f_name, missing, |
| 964 | "positional" if pos else "keyword-only", |
| 965 | "" if missing == 1 else "s", s)) |
| 966 | |
| 967 | def _too_many(f_name, args, kwonly, varargs, defcount, given, values): |
Benjamin Peterson | b204a42 | 2011-06-05 22:04:07 -0500 | [diff] [blame] | 968 | atleast = len(args) - defcount |
Benjamin Peterson | b204a42 | 2011-06-05 22:04:07 -0500 | [diff] [blame] | 969 | kwonly_given = len([arg for arg in kwonly if arg in values]) |
| 970 | if varargs: |
| 971 | plural = atleast != 1 |
| 972 | sig = "at least %d" % (atleast,) |
| 973 | elif defcount: |
| 974 | plural = True |
| 975 | sig = "from %d to %d" % (atleast, len(args)) |
| 976 | else: |
| 977 | plural = len(args) != 1 |
| 978 | sig = str(len(args)) |
| 979 | kwonly_sig = "" |
| 980 | if kwonly_given: |
| 981 | msg = " positional argument%s (and %d keyword-only argument%s)" |
| 982 | kwonly_sig = (msg % ("s" if given != 1 else "", kwonly_given, |
| 983 | "s" if kwonly_given != 1 else "")) |
| 984 | raise TypeError("%s() takes %s positional argument%s but %d%s %s given" % |
| 985 | (f_name, sig, "s" if plural else "", given, kwonly_sig, |
| 986 | "was" if given == 1 and not kwonly_given else "were")) |
| 987 | |
Benjamin Peterson | 25cd7eb | 2010-03-30 18:42:32 +0000 | [diff] [blame] | 988 | def getcallargs(func, *positional, **named): |
| 989 | """Get the mapping of arguments to values. |
| 990 | |
| 991 | A dict is returned, with keys the function argument names (including the |
| 992 | names of the * and ** arguments, if any), and values the respective bound |
| 993 | values from 'positional' and 'named'.""" |
| 994 | spec = getfullargspec(func) |
| 995 | args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults, ann = spec |
| 996 | f_name = func.__name__ |
| 997 | arg2value = {} |
| 998 | |
Benjamin Peterson | b204a42 | 2011-06-05 22:04:07 -0500 | [diff] [blame] | 999 | |
Benjamin Peterson | 25cd7eb | 2010-03-30 18:42:32 +0000 | [diff] [blame] | 1000 | if ismethod(func) and func.__self__ is not None: |
| 1001 | # implicit 'self' (or 'cls' for classmethods) argument |
| 1002 | positional = (func.__self__,) + positional |
| 1003 | num_pos = len(positional) |
Benjamin Peterson | 25cd7eb | 2010-03-30 18:42:32 +0000 | [diff] [blame] | 1004 | num_args = len(args) |
| 1005 | num_defaults = len(defaults) if defaults else 0 |
Benjamin Peterson | 25cd7eb | 2010-03-30 18:42:32 +0000 | [diff] [blame] | 1006 | |
Benjamin Peterson | b204a42 | 2011-06-05 22:04:07 -0500 | [diff] [blame] | 1007 | n = min(num_pos, num_args) |
| 1008 | for i in range(n): |
| 1009 | arg2value[args[i]] = positional[i] |
| 1010 | if varargs: |
| 1011 | arg2value[varargs] = tuple(positional[n:]) |
| 1012 | possible_kwargs = set(args + kwonlyargs) |
Benjamin Peterson | 25cd7eb | 2010-03-30 18:42:32 +0000 | [diff] [blame] | 1013 | if varkw: |
Benjamin Peterson | b204a42 | 2011-06-05 22:04:07 -0500 | [diff] [blame] | 1014 | arg2value[varkw] = {} |
| 1015 | for kw, value in named.items(): |
| 1016 | if kw not in possible_kwargs: |
| 1017 | if not varkw: |
| 1018 | raise TypeError("%s() got an unexpected keyword argument %r" % |
| 1019 | (f_name, kw)) |
| 1020 | arg2value[varkw][kw] = value |
| 1021 | continue |
| 1022 | if kw in arg2value: |
| 1023 | raise TypeError("%s() got multiple values for argument %r" % |
| 1024 | (f_name, kw)) |
| 1025 | arg2value[kw] = value |
| 1026 | if num_pos > num_args and not varargs: |
Benjamin Peterson | e109c70 | 2011-06-24 09:37:26 -0500 | [diff] [blame] | 1027 | _too_many(f_name, args, kwonlyargs, varargs, num_defaults, |
| 1028 | num_pos, arg2value) |
Benjamin Peterson | b204a42 | 2011-06-05 22:04:07 -0500 | [diff] [blame] | 1029 | if num_pos < num_args: |
Benjamin Peterson | e109c70 | 2011-06-24 09:37:26 -0500 | [diff] [blame] | 1030 | req = args[:num_args - num_defaults] |
| 1031 | for arg in req: |
Benjamin Peterson | b204a42 | 2011-06-05 22:04:07 -0500 | [diff] [blame] | 1032 | if arg not in arg2value: |
Benjamin Peterson | e109c70 | 2011-06-24 09:37:26 -0500 | [diff] [blame] | 1033 | _missing_arguments(f_name, req, True, arg2value) |
Benjamin Peterson | b204a42 | 2011-06-05 22:04:07 -0500 | [diff] [blame] | 1034 | for i, arg in enumerate(args[num_args - num_defaults:]): |
| 1035 | if arg not in arg2value: |
| 1036 | arg2value[arg] = defaults[i] |
Benjamin Peterson | e109c70 | 2011-06-24 09:37:26 -0500 | [diff] [blame] | 1037 | missing = 0 |
Benjamin Peterson | b204a42 | 2011-06-05 22:04:07 -0500 | [diff] [blame] | 1038 | for kwarg in kwonlyargs: |
| 1039 | if kwarg not in arg2value: |
Benjamin Peterson | e109c70 | 2011-06-24 09:37:26 -0500 | [diff] [blame] | 1040 | if kwarg in kwonlydefaults: |
| 1041 | arg2value[kwarg] = kwonlydefaults[kwarg] |
| 1042 | else: |
| 1043 | missing += 1 |
| 1044 | if missing: |
| 1045 | _missing_arguments(f_name, kwonlyargs, False, arg2value) |
Benjamin Peterson | 25cd7eb | 2010-03-30 18:42:32 +0000 | [diff] [blame] | 1046 | return arg2value |
| 1047 | |
Nick Coghlan | 2f92e54 | 2012-06-23 19:39:55 +1000 | [diff] [blame] | 1048 | ClosureVars = namedtuple('ClosureVars', 'nonlocals globals builtins unbound') |
| 1049 | |
| 1050 | def getclosurevars(func): |
| 1051 | """ |
| 1052 | Get the mapping of free variables to their current values. |
| 1053 | |
Meador Inge | 8fda359 | 2012-07-19 21:33:21 -0500 | [diff] [blame] | 1054 | Returns a named tuple of dicts mapping the current nonlocal, global |
Nick Coghlan | 2f92e54 | 2012-06-23 19:39:55 +1000 | [diff] [blame] | 1055 | and builtin references as seen by the body of the function. A final |
| 1056 | set of unbound names that could not be resolved is also provided. |
| 1057 | """ |
| 1058 | |
| 1059 | if ismethod(func): |
| 1060 | func = func.__func__ |
| 1061 | |
| 1062 | if not isfunction(func): |
| 1063 | raise TypeError("'{!r}' is not a Python function".format(func)) |
| 1064 | |
| 1065 | code = func.__code__ |
| 1066 | # Nonlocal references are named in co_freevars and resolved |
| 1067 | # by looking them up in __closure__ by positional index |
| 1068 | if func.__closure__ is None: |
| 1069 | nonlocal_vars = {} |
| 1070 | else: |
| 1071 | nonlocal_vars = { |
| 1072 | var : cell.cell_contents |
| 1073 | for var, cell in zip(code.co_freevars, func.__closure__) |
| 1074 | } |
| 1075 | |
| 1076 | # Global and builtin references are named in co_names and resolved |
| 1077 | # by looking them up in __globals__ or __builtins__ |
| 1078 | global_ns = func.__globals__ |
| 1079 | builtin_ns = global_ns.get("__builtins__", builtins.__dict__) |
| 1080 | if ismodule(builtin_ns): |
| 1081 | builtin_ns = builtin_ns.__dict__ |
| 1082 | global_vars = {} |
| 1083 | builtin_vars = {} |
| 1084 | unbound_names = set() |
| 1085 | for name in code.co_names: |
| 1086 | if name in ("None", "True", "False"): |
| 1087 | # Because these used to be builtins instead of keywords, they |
| 1088 | # may still show up as name references. We ignore them. |
| 1089 | continue |
| 1090 | try: |
| 1091 | global_vars[name] = global_ns[name] |
| 1092 | except KeyError: |
| 1093 | try: |
| 1094 | builtin_vars[name] = builtin_ns[name] |
| 1095 | except KeyError: |
| 1096 | unbound_names.add(name) |
| 1097 | |
| 1098 | return ClosureVars(nonlocal_vars, global_vars, |
| 1099 | builtin_vars, unbound_names) |
| 1100 | |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 1101 | # -------------------------------------------------- stack frame extraction |
Christian Heimes | 25bb783 | 2008-01-11 16:17:00 +0000 | [diff] [blame] | 1102 | |
| 1103 | Traceback = namedtuple('Traceback', 'filename lineno function code_context index') |
| 1104 | |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 1105 | def getframeinfo(frame, context=1): |
| 1106 | """Get information about a frame or traceback object. |
| 1107 | |
| 1108 | A tuple of five things is returned: the filename, the line number of |
| 1109 | the current line, the function name, a list of lines of context from |
| 1110 | the source code, and the index of the current line within that list. |
| 1111 | The optional second argument specifies the number of lines of context |
| 1112 | to return, which are centered around the current line.""" |
| 1113 | if istraceback(frame): |
Andrew M. Kuchling | ba8b6bc | 2004-06-05 14:11:59 +0000 | [diff] [blame] | 1114 | lineno = frame.tb_lineno |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 1115 | frame = frame.tb_frame |
Andrew M. Kuchling | ba8b6bc | 2004-06-05 14:11:59 +0000 | [diff] [blame] | 1116 | else: |
| 1117 | lineno = frame.f_lineno |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 1118 | if not isframe(frame): |
Benjamin Peterson | 4ac9ce4 | 2009-10-04 14:49:41 +0000 | [diff] [blame] | 1119 | raise TypeError('{!r} is not a frame or traceback object'.format(frame)) |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 1120 | |
Neil Schemenauer | f06f853 | 2002-03-23 23:51:04 +0000 | [diff] [blame] | 1121 | filename = getsourcefile(frame) or getfile(frame) |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 1122 | if context > 0: |
Guido van Rossum | 54e54c6 | 2001-09-04 19:14:14 +0000 | [diff] [blame] | 1123 | start = lineno - 1 - context//2 |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 1124 | try: |
| 1125 | lines, lnum = findsource(frame) |
Ka-Ping Yee | 4eb0c00 | 2001-03-02 05:50:34 +0000 | [diff] [blame] | 1126 | except IOError: |
| 1127 | lines = index = None |
| 1128 | else: |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 1129 | start = max(start, 1) |
Raymond Hettinger | a050171 | 2004-06-15 11:22:53 +0000 | [diff] [blame] | 1130 | start = max(0, min(start, len(lines) - context)) |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 1131 | lines = lines[start:start+context] |
Ka-Ping Yee | 59ade08 | 2001-03-01 03:55:35 +0000 | [diff] [blame] | 1132 | index = lineno - 1 - start |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 1133 | else: |
| 1134 | lines = index = None |
| 1135 | |
Christian Heimes | 25bb783 | 2008-01-11 16:17:00 +0000 | [diff] [blame] | 1136 | return Traceback(filename, lineno, frame.f_code.co_name, lines, index) |
Ka-Ping Yee | 59ade08 | 2001-03-01 03:55:35 +0000 | [diff] [blame] | 1137 | |
| 1138 | def getlineno(frame): |
| 1139 | """Get the line number from a frame object, allowing for optimization.""" |
Michael W. Hudson | dd32a91 | 2002-08-15 14:59:02 +0000 | [diff] [blame] | 1140 | # FrameType.f_lineno is now a descriptor that grovels co_lnotab |
| 1141 | return frame.f_lineno |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 1142 | |
| 1143 | def getouterframes(frame, context=1): |
| 1144 | """Get a list of records for a frame and all higher (calling) frames. |
| 1145 | |
| 1146 | Each record contains a frame object, filename, line number, function |
| 1147 | name, a list of lines of context, and index within the context.""" |
| 1148 | framelist = [] |
| 1149 | while frame: |
| 1150 | framelist.append((frame,) + getframeinfo(frame, context)) |
| 1151 | frame = frame.f_back |
| 1152 | return framelist |
| 1153 | |
| 1154 | def getinnerframes(tb, context=1): |
| 1155 | """Get a list of records for a traceback's frame and all lower frames. |
| 1156 | |
| 1157 | Each record contains a frame object, filename, line number, function |
| 1158 | 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] | 1159 | framelist = [] |
| 1160 | while tb: |
| 1161 | framelist.append((tb.tb_frame,) + getframeinfo(tb, context)) |
| 1162 | tb = tb.tb_next |
| 1163 | return framelist |
| 1164 | |
Benjamin Peterson | 42ac475 | 2010-08-09 13:05:35 +0000 | [diff] [blame] | 1165 | def currentframe(): |
Benjamin Peterson | a3a3fc6 | 2010-08-09 15:49:56 +0000 | [diff] [blame] | 1166 | """Return the frame of the caller or None if this is not possible.""" |
Benjamin Peterson | 42ac475 | 2010-08-09 13:05:35 +0000 | [diff] [blame] | 1167 | return sys._getframe(1) if hasattr(sys, "_getframe") else None |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 1168 | |
| 1169 | def stack(context=1): |
| 1170 | """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] | 1171 | return getouterframes(sys._getframe(1), context) |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 1172 | |
| 1173 | def trace(context=1): |
Tim Peters | 85ba673 | 2001-02-28 08:26:44 +0000 | [diff] [blame] | 1174 | """Return a list of records for the stack below the current exception.""" |
Fred Drake | d451ec1 | 2002-04-26 02:29:55 +0000 | [diff] [blame] | 1175 | return getinnerframes(sys.exc_info()[2], context) |
Michael Foord | 95fc51d | 2010-11-20 15:07:30 +0000 | [diff] [blame] | 1176 | |
| 1177 | |
| 1178 | # ------------------------------------------------ static version of getattr |
| 1179 | |
| 1180 | _sentinel = object() |
| 1181 | |
Michael Foord | e516265 | 2010-11-20 16:40:44 +0000 | [diff] [blame] | 1182 | def _static_getmro(klass): |
| 1183 | return type.__dict__['__mro__'].__get__(klass) |
| 1184 | |
Michael Foord | 95fc51d | 2010-11-20 15:07:30 +0000 | [diff] [blame] | 1185 | def _check_instance(obj, attr): |
| 1186 | instance_dict = {} |
| 1187 | try: |
| 1188 | instance_dict = object.__getattribute__(obj, "__dict__") |
| 1189 | except AttributeError: |
| 1190 | pass |
Michael Foord | dcebe0f | 2011-03-15 19:20:44 -0400 | [diff] [blame] | 1191 | return dict.get(instance_dict, attr, _sentinel) |
Michael Foord | 95fc51d | 2010-11-20 15:07:30 +0000 | [diff] [blame] | 1192 | |
| 1193 | |
| 1194 | def _check_class(klass, attr): |
Michael Foord | e516265 | 2010-11-20 16:40:44 +0000 | [diff] [blame] | 1195 | for entry in _static_getmro(klass): |
Michael Foord | a51623b | 2011-12-18 22:01:40 +0000 | [diff] [blame] | 1196 | if _shadowed_dict(type(entry)) is _sentinel: |
Michael Foord | dcebe0f | 2011-03-15 19:20:44 -0400 | [diff] [blame] | 1197 | try: |
| 1198 | return entry.__dict__[attr] |
| 1199 | except KeyError: |
| 1200 | pass |
Michael Foord | 95fc51d | 2010-11-20 15:07:30 +0000 | [diff] [blame] | 1201 | return _sentinel |
| 1202 | |
Michael Foord | 35184ed | 2010-11-20 16:58:30 +0000 | [diff] [blame] | 1203 | def _is_type(obj): |
| 1204 | try: |
| 1205 | _static_getmro(obj) |
| 1206 | except TypeError: |
| 1207 | return False |
| 1208 | return True |
| 1209 | |
Michael Foord | dcebe0f | 2011-03-15 19:20:44 -0400 | [diff] [blame] | 1210 | def _shadowed_dict(klass): |
| 1211 | dict_attr = type.__dict__["__dict__"] |
| 1212 | for entry in _static_getmro(klass): |
| 1213 | try: |
| 1214 | class_dict = dict_attr.__get__(entry)["__dict__"] |
| 1215 | except KeyError: |
| 1216 | pass |
| 1217 | else: |
| 1218 | if not (type(class_dict) is types.GetSetDescriptorType and |
| 1219 | class_dict.__name__ == "__dict__" and |
| 1220 | class_dict.__objclass__ is entry): |
Michael Foord | a51623b | 2011-12-18 22:01:40 +0000 | [diff] [blame] | 1221 | return class_dict |
| 1222 | return _sentinel |
Michael Foord | 95fc51d | 2010-11-20 15:07:30 +0000 | [diff] [blame] | 1223 | |
| 1224 | def getattr_static(obj, attr, default=_sentinel): |
| 1225 | """Retrieve attributes without triggering dynamic lookup via the |
| 1226 | descriptor protocol, __getattr__ or __getattribute__. |
| 1227 | |
| 1228 | Note: this function may not be able to retrieve all attributes |
| 1229 | that getattr can fetch (like dynamically created attributes) |
| 1230 | and may find attributes that getattr can't (like descriptors |
| 1231 | that raise AttributeError). It can also return descriptor objects |
| 1232 | instead of instance members in some cases. See the |
| 1233 | documentation for details. |
| 1234 | """ |
| 1235 | instance_result = _sentinel |
Michael Foord | 35184ed | 2010-11-20 16:58:30 +0000 | [diff] [blame] | 1236 | if not _is_type(obj): |
Michael Foord | cc7ebb8 | 2010-11-20 16:20:16 +0000 | [diff] [blame] | 1237 | klass = type(obj) |
Michael Foord | a51623b | 2011-12-18 22:01:40 +0000 | [diff] [blame] | 1238 | dict_attr = _shadowed_dict(klass) |
| 1239 | if (dict_attr is _sentinel or |
| 1240 | type(dict_attr) is types.MemberDescriptorType): |
Michael Foord | dcebe0f | 2011-03-15 19:20:44 -0400 | [diff] [blame] | 1241 | instance_result = _check_instance(obj, attr) |
Michael Foord | 95fc51d | 2010-11-20 15:07:30 +0000 | [diff] [blame] | 1242 | else: |
| 1243 | klass = obj |
| 1244 | |
| 1245 | klass_result = _check_class(klass, attr) |
| 1246 | |
| 1247 | if instance_result is not _sentinel and klass_result is not _sentinel: |
| 1248 | if (_check_class(type(klass_result), '__get__') is not _sentinel and |
| 1249 | _check_class(type(klass_result), '__set__') is not _sentinel): |
| 1250 | return klass_result |
| 1251 | |
| 1252 | if instance_result is not _sentinel: |
| 1253 | return instance_result |
| 1254 | if klass_result is not _sentinel: |
| 1255 | return klass_result |
| 1256 | |
| 1257 | if obj is klass: |
| 1258 | # for types we check the metaclass too |
Michael Foord | e516265 | 2010-11-20 16:40:44 +0000 | [diff] [blame] | 1259 | for entry in _static_getmro(type(klass)): |
Michael Foord | 3ba95f8 | 2011-12-22 01:13:37 +0000 | [diff] [blame] | 1260 | if _shadowed_dict(type(entry)) is _sentinel: |
| 1261 | try: |
| 1262 | return entry.__dict__[attr] |
| 1263 | except KeyError: |
| 1264 | pass |
Michael Foord | 95fc51d | 2010-11-20 15:07:30 +0000 | [diff] [blame] | 1265 | if default is not _sentinel: |
| 1266 | return default |
| 1267 | raise AttributeError(attr) |
Nick Coghlan | e0f0465 | 2010-11-21 03:44:04 +0000 | [diff] [blame] | 1268 | |
| 1269 | |
Nick Coghlan | 04e2e3f | 2012-06-23 19:52:05 +1000 | [diff] [blame] | 1270 | # ------------------------------------------------ generator introspection |
| 1271 | |
Nick Coghlan | 7921b9f | 2010-11-30 06:36:04 +0000 | [diff] [blame] | 1272 | GEN_CREATED = 'GEN_CREATED' |
| 1273 | GEN_RUNNING = 'GEN_RUNNING' |
| 1274 | GEN_SUSPENDED = 'GEN_SUSPENDED' |
| 1275 | GEN_CLOSED = 'GEN_CLOSED' |
Nick Coghlan | e0f0465 | 2010-11-21 03:44:04 +0000 | [diff] [blame] | 1276 | |
| 1277 | def getgeneratorstate(generator): |
| 1278 | """Get current state of a generator-iterator. |
| 1279 | |
| 1280 | Possible states are: |
| 1281 | GEN_CREATED: Waiting to start execution. |
| 1282 | GEN_RUNNING: Currently being executed by the interpreter. |
| 1283 | GEN_SUSPENDED: Currently suspended at a yield expression. |
| 1284 | GEN_CLOSED: Execution has completed. |
| 1285 | """ |
| 1286 | if generator.gi_running: |
| 1287 | return GEN_RUNNING |
| 1288 | if generator.gi_frame is None: |
| 1289 | return GEN_CLOSED |
| 1290 | if generator.gi_frame.f_lasti == -1: |
| 1291 | return GEN_CREATED |
| 1292 | return GEN_SUSPENDED |
Larry Hastings | 7c7cbfc | 2012-06-22 15:19:35 -0700 | [diff] [blame] | 1293 | |
| 1294 | |
Nick Coghlan | 04e2e3f | 2012-06-23 19:52:05 +1000 | [diff] [blame] | 1295 | def getgeneratorlocals(generator): |
| 1296 | """ |
| 1297 | Get the mapping of generator local variables to their current values. |
| 1298 | |
| 1299 | A dict is returned, with the keys the local variable names and values the |
| 1300 | bound values.""" |
| 1301 | |
| 1302 | if not isgenerator(generator): |
| 1303 | raise TypeError("'{!r}' is not a Python generator".format(generator)) |
| 1304 | |
| 1305 | frame = getattr(generator, "gi_frame", None) |
| 1306 | if frame is not None: |
| 1307 | return generator.gi_frame.f_locals |
| 1308 | else: |
| 1309 | return {} |
| 1310 | |
Larry Hastings | 7c7cbfc | 2012-06-22 15:19:35 -0700 | [diff] [blame] | 1311 | ############################################################################### |
| 1312 | ### Function Signature Object (PEP 362) |
| 1313 | ############################################################################### |
| 1314 | |
| 1315 | |
| 1316 | _WrapperDescriptor = type(type.__call__) |
| 1317 | _MethodWrapper = type(all.__call__) |
| 1318 | |
| 1319 | _NonUserDefinedCallables = (_WrapperDescriptor, |
| 1320 | _MethodWrapper, |
| 1321 | types.BuiltinFunctionType) |
| 1322 | |
| 1323 | |
| 1324 | def _get_user_defined_method(cls, method_name): |
| 1325 | try: |
| 1326 | meth = getattr(cls, method_name) |
| 1327 | except AttributeError: |
| 1328 | return |
| 1329 | else: |
| 1330 | if not isinstance(meth, _NonUserDefinedCallables): |
| 1331 | # Once '__signature__' will be added to 'C'-level |
| 1332 | # callables, this check won't be necessary |
| 1333 | return meth |
| 1334 | |
| 1335 | |
| 1336 | def signature(obj): |
| 1337 | '''Get a signature object for the passed callable.''' |
| 1338 | |
| 1339 | if not callable(obj): |
| 1340 | raise TypeError('{!r} is not a callable object'.format(obj)) |
| 1341 | |
| 1342 | if isinstance(obj, types.MethodType): |
| 1343 | # In this case we skip the first parameter of the underlying |
| 1344 | # function (usually `self` or `cls`). |
| 1345 | sig = signature(obj.__func__) |
| 1346 | return sig.replace(parameters=tuple(sig.parameters.values())[1:]) |
| 1347 | |
| 1348 | try: |
| 1349 | sig = obj.__signature__ |
| 1350 | except AttributeError: |
| 1351 | pass |
| 1352 | else: |
| 1353 | if sig is not None: |
| 1354 | return sig |
| 1355 | |
| 1356 | try: |
| 1357 | # Was this function wrapped by a decorator? |
| 1358 | wrapped = obj.__wrapped__ |
| 1359 | except AttributeError: |
| 1360 | pass |
| 1361 | else: |
| 1362 | return signature(wrapped) |
| 1363 | |
| 1364 | if isinstance(obj, types.FunctionType): |
| 1365 | return Signature.from_function(obj) |
| 1366 | |
| 1367 | if isinstance(obj, functools.partial): |
| 1368 | sig = signature(obj.func) |
| 1369 | |
| 1370 | new_params = OrderedDict(sig.parameters.items()) |
| 1371 | |
| 1372 | partial_args = obj.args or () |
| 1373 | partial_keywords = obj.keywords or {} |
| 1374 | try: |
| 1375 | ba = sig.bind_partial(*partial_args, **partial_keywords) |
| 1376 | except TypeError as ex: |
| 1377 | msg = 'partial object {!r} has incorrect arguments'.format(obj) |
| 1378 | raise ValueError(msg) from ex |
| 1379 | |
| 1380 | for arg_name, arg_value in ba.arguments.items(): |
| 1381 | param = new_params[arg_name] |
| 1382 | if arg_name in partial_keywords: |
| 1383 | # We set a new default value, because the following code |
| 1384 | # is correct: |
| 1385 | # |
| 1386 | # >>> def foo(a): print(a) |
| 1387 | # >>> print(partial(partial(foo, a=10), a=20)()) |
| 1388 | # 20 |
| 1389 | # >>> print(partial(partial(foo, a=10), a=20)(a=30)) |
| 1390 | # 30 |
| 1391 | # |
| 1392 | # So, with 'partial' objects, passing a keyword argument is |
| 1393 | # like setting a new default value for the corresponding |
| 1394 | # parameter |
| 1395 | # |
| 1396 | # We also mark this parameter with '_partial_kwarg' |
| 1397 | # flag. Later, in '_bind', the 'default' value of this |
| 1398 | # parameter will be added to 'kwargs', to simulate |
| 1399 | # the 'functools.partial' real call. |
| 1400 | new_params[arg_name] = param.replace(default=arg_value, |
| 1401 | _partial_kwarg=True) |
| 1402 | |
| 1403 | elif (param.kind not in (_VAR_KEYWORD, _VAR_POSITIONAL) and |
| 1404 | not param._partial_kwarg): |
| 1405 | new_params.pop(arg_name) |
| 1406 | |
| 1407 | return sig.replace(parameters=new_params.values()) |
| 1408 | |
| 1409 | sig = None |
| 1410 | if isinstance(obj, type): |
| 1411 | # obj is a class or a metaclass |
| 1412 | |
| 1413 | # First, let's see if it has an overloaded __call__ defined |
| 1414 | # in its metaclass |
| 1415 | call = _get_user_defined_method(type(obj), '__call__') |
| 1416 | if call is not None: |
| 1417 | sig = signature(call) |
| 1418 | else: |
| 1419 | # Now we check if the 'obj' class has a '__new__' method |
| 1420 | new = _get_user_defined_method(obj, '__new__') |
| 1421 | if new is not None: |
| 1422 | sig = signature(new) |
| 1423 | else: |
| 1424 | # Finally, we should have at least __init__ implemented |
| 1425 | init = _get_user_defined_method(obj, '__init__') |
| 1426 | if init is not None: |
| 1427 | sig = signature(init) |
| 1428 | elif not isinstance(obj, _NonUserDefinedCallables): |
| 1429 | # An object with __call__ |
| 1430 | # We also check that the 'obj' is not an instance of |
| 1431 | # _WrapperDescriptor or _MethodWrapper to avoid |
| 1432 | # infinite recursion (and even potential segfault) |
| 1433 | call = _get_user_defined_method(type(obj), '__call__') |
| 1434 | if call is not None: |
| 1435 | sig = signature(call) |
| 1436 | |
| 1437 | if sig is not None: |
| 1438 | # For classes and objects we skip the first parameter of their |
| 1439 | # __call__, __new__, or __init__ methods |
| 1440 | return sig.replace(parameters=tuple(sig.parameters.values())[1:]) |
| 1441 | |
| 1442 | if isinstance(obj, types.BuiltinFunctionType): |
| 1443 | # Raise a nicer error message for builtins |
| 1444 | msg = 'no signature found for builtin function {!r}'.format(obj) |
| 1445 | raise ValueError(msg) |
| 1446 | |
| 1447 | raise ValueError('callable {!r} is not supported by signature'.format(obj)) |
| 1448 | |
| 1449 | |
| 1450 | class _void: |
| 1451 | '''A private marker - used in Parameter & Signature''' |
| 1452 | |
| 1453 | |
| 1454 | class _empty: |
| 1455 | pass |
| 1456 | |
| 1457 | |
| 1458 | class _ParameterKind(int): |
| 1459 | def __new__(self, *args, name): |
| 1460 | obj = int.__new__(self, *args) |
| 1461 | obj._name = name |
| 1462 | return obj |
| 1463 | |
| 1464 | def __str__(self): |
| 1465 | return self._name |
| 1466 | |
| 1467 | def __repr__(self): |
| 1468 | return '<_ParameterKind: {!r}>'.format(self._name) |
| 1469 | |
| 1470 | |
| 1471 | _POSITIONAL_ONLY = _ParameterKind(0, name='POSITIONAL_ONLY') |
| 1472 | _POSITIONAL_OR_KEYWORD = _ParameterKind(1, name='POSITIONAL_OR_KEYWORD') |
| 1473 | _VAR_POSITIONAL = _ParameterKind(2, name='VAR_POSITIONAL') |
| 1474 | _KEYWORD_ONLY = _ParameterKind(3, name='KEYWORD_ONLY') |
| 1475 | _VAR_KEYWORD = _ParameterKind(4, name='VAR_KEYWORD') |
| 1476 | |
| 1477 | |
| 1478 | class Parameter: |
| 1479 | '''Represents a parameter in a function signature. |
| 1480 | |
| 1481 | Has the following public attributes: |
| 1482 | |
| 1483 | * name : str |
| 1484 | The name of the parameter as a string. |
| 1485 | * default : object |
| 1486 | The default value for the parameter if specified. If the |
| 1487 | parameter has no default value, this attribute is not set. |
| 1488 | * annotation |
| 1489 | The annotation for the parameter if specified. If the |
| 1490 | parameter has no annotation, this attribute is not set. |
| 1491 | * kind : str |
| 1492 | Describes how argument values are bound to the parameter. |
| 1493 | Possible values: `Parameter.POSITIONAL_ONLY`, |
| 1494 | `Parameter.POSITIONAL_OR_KEYWORD`, `Parameter.VAR_POSITIONAL`, |
| 1495 | `Parameter.KEYWORD_ONLY`, `Parameter.VAR_KEYWORD`. |
| 1496 | ''' |
| 1497 | |
| 1498 | __slots__ = ('_name', '_kind', '_default', '_annotation', '_partial_kwarg') |
| 1499 | |
| 1500 | POSITIONAL_ONLY = _POSITIONAL_ONLY |
| 1501 | POSITIONAL_OR_KEYWORD = _POSITIONAL_OR_KEYWORD |
| 1502 | VAR_POSITIONAL = _VAR_POSITIONAL |
| 1503 | KEYWORD_ONLY = _KEYWORD_ONLY |
| 1504 | VAR_KEYWORD = _VAR_KEYWORD |
| 1505 | |
| 1506 | empty = _empty |
| 1507 | |
| 1508 | def __init__(self, name, kind, *, default=_empty, annotation=_empty, |
| 1509 | _partial_kwarg=False): |
| 1510 | |
| 1511 | if kind not in (_POSITIONAL_ONLY, _POSITIONAL_OR_KEYWORD, |
| 1512 | _VAR_POSITIONAL, _KEYWORD_ONLY, _VAR_KEYWORD): |
| 1513 | raise ValueError("invalid value for 'Parameter.kind' attribute") |
| 1514 | self._kind = kind |
| 1515 | |
| 1516 | if default is not _empty: |
| 1517 | if kind in (_VAR_POSITIONAL, _VAR_KEYWORD): |
| 1518 | msg = '{} parameters cannot have default values'.format(kind) |
| 1519 | raise ValueError(msg) |
| 1520 | self._default = default |
| 1521 | self._annotation = annotation |
| 1522 | |
| 1523 | if name is None: |
| 1524 | if kind != _POSITIONAL_ONLY: |
| 1525 | raise ValueError("None is not a valid name for a " |
| 1526 | "non-positional-only parameter") |
| 1527 | self._name = name |
| 1528 | else: |
| 1529 | name = str(name) |
| 1530 | if kind != _POSITIONAL_ONLY and not name.isidentifier(): |
| 1531 | msg = '{!r} is not a valid parameter name'.format(name) |
| 1532 | raise ValueError(msg) |
| 1533 | self._name = name |
| 1534 | |
| 1535 | self._partial_kwarg = _partial_kwarg |
| 1536 | |
| 1537 | @property |
| 1538 | def name(self): |
| 1539 | return self._name |
| 1540 | |
| 1541 | @property |
| 1542 | def default(self): |
| 1543 | return self._default |
| 1544 | |
| 1545 | @property |
| 1546 | def annotation(self): |
| 1547 | return self._annotation |
| 1548 | |
| 1549 | @property |
| 1550 | def kind(self): |
| 1551 | return self._kind |
| 1552 | |
| 1553 | def replace(self, *, name=_void, kind=_void, annotation=_void, |
| 1554 | default=_void, _partial_kwarg=_void): |
| 1555 | '''Creates a customized copy of the Parameter.''' |
| 1556 | |
| 1557 | if name is _void: |
| 1558 | name = self._name |
| 1559 | |
| 1560 | if kind is _void: |
| 1561 | kind = self._kind |
| 1562 | |
| 1563 | if annotation is _void: |
| 1564 | annotation = self._annotation |
| 1565 | |
| 1566 | if default is _void: |
| 1567 | default = self._default |
| 1568 | |
| 1569 | if _partial_kwarg is _void: |
| 1570 | _partial_kwarg = self._partial_kwarg |
| 1571 | |
| 1572 | return type(self)(name, kind, default=default, annotation=annotation, |
| 1573 | _partial_kwarg=_partial_kwarg) |
| 1574 | |
| 1575 | def __str__(self): |
| 1576 | kind = self.kind |
| 1577 | |
| 1578 | formatted = self._name |
| 1579 | if kind == _POSITIONAL_ONLY: |
| 1580 | if formatted is None: |
| 1581 | formatted = '' |
| 1582 | formatted = '<{}>'.format(formatted) |
| 1583 | |
| 1584 | # Add annotation and default value |
| 1585 | if self._annotation is not _empty: |
| 1586 | formatted = '{}:{}'.format(formatted, |
| 1587 | formatannotation(self._annotation)) |
| 1588 | |
| 1589 | if self._default is not _empty: |
| 1590 | formatted = '{}={}'.format(formatted, repr(self._default)) |
| 1591 | |
| 1592 | if kind == _VAR_POSITIONAL: |
| 1593 | formatted = '*' + formatted |
| 1594 | elif kind == _VAR_KEYWORD: |
| 1595 | formatted = '**' + formatted |
| 1596 | |
| 1597 | return formatted |
| 1598 | |
| 1599 | def __repr__(self): |
| 1600 | return '<{} at {:#x} {!r}>'.format(self.__class__.__name__, |
| 1601 | id(self), self.name) |
| 1602 | |
| 1603 | def __eq__(self, other): |
| 1604 | return (issubclass(other.__class__, Parameter) and |
| 1605 | self._name == other._name and |
| 1606 | self._kind == other._kind and |
| 1607 | self._default == other._default and |
| 1608 | self._annotation == other._annotation) |
| 1609 | |
| 1610 | def __ne__(self, other): |
| 1611 | return not self.__eq__(other) |
| 1612 | |
| 1613 | |
| 1614 | class BoundArguments: |
| 1615 | '''Result of `Signature.bind` call. Holds the mapping of arguments |
| 1616 | to the function's parameters. |
| 1617 | |
| 1618 | Has the following public attributes: |
| 1619 | |
| 1620 | * arguments : OrderedDict |
| 1621 | An ordered mutable mapping of parameters' names to arguments' values. |
| 1622 | Does not contain arguments' default values. |
| 1623 | * signature : Signature |
| 1624 | The Signature object that created this instance. |
| 1625 | * args : tuple |
| 1626 | Tuple of positional arguments values. |
| 1627 | * kwargs : dict |
| 1628 | Dict of keyword arguments values. |
| 1629 | ''' |
| 1630 | |
| 1631 | def __init__(self, signature, arguments): |
| 1632 | self.arguments = arguments |
| 1633 | self._signature = signature |
| 1634 | |
| 1635 | @property |
| 1636 | def signature(self): |
| 1637 | return self._signature |
| 1638 | |
| 1639 | @property |
| 1640 | def args(self): |
| 1641 | args = [] |
| 1642 | for param_name, param in self._signature.parameters.items(): |
| 1643 | if (param.kind in (_VAR_KEYWORD, _KEYWORD_ONLY) or |
| 1644 | param._partial_kwarg): |
| 1645 | # Keyword arguments mapped by 'functools.partial' |
| 1646 | # (Parameter._partial_kwarg is True) are mapped |
| 1647 | # in 'BoundArguments.kwargs', along with VAR_KEYWORD & |
| 1648 | # KEYWORD_ONLY |
| 1649 | break |
| 1650 | |
| 1651 | try: |
| 1652 | arg = self.arguments[param_name] |
| 1653 | except KeyError: |
| 1654 | # We're done here. Other arguments |
| 1655 | # will be mapped in 'BoundArguments.kwargs' |
| 1656 | break |
| 1657 | else: |
| 1658 | if param.kind == _VAR_POSITIONAL: |
| 1659 | # *args |
| 1660 | args.extend(arg) |
| 1661 | else: |
| 1662 | # plain argument |
| 1663 | args.append(arg) |
| 1664 | |
| 1665 | return tuple(args) |
| 1666 | |
| 1667 | @property |
| 1668 | def kwargs(self): |
| 1669 | kwargs = {} |
| 1670 | kwargs_started = False |
| 1671 | for param_name, param in self._signature.parameters.items(): |
| 1672 | if not kwargs_started: |
| 1673 | if (param.kind in (_VAR_KEYWORD, _KEYWORD_ONLY) or |
| 1674 | param._partial_kwarg): |
| 1675 | kwargs_started = True |
| 1676 | else: |
| 1677 | if param_name not in self.arguments: |
| 1678 | kwargs_started = True |
| 1679 | continue |
| 1680 | |
| 1681 | if not kwargs_started: |
| 1682 | continue |
| 1683 | |
| 1684 | try: |
| 1685 | arg = self.arguments[param_name] |
| 1686 | except KeyError: |
| 1687 | pass |
| 1688 | else: |
| 1689 | if param.kind == _VAR_KEYWORD: |
| 1690 | # **kwargs |
| 1691 | kwargs.update(arg) |
| 1692 | else: |
| 1693 | # plain keyword argument |
| 1694 | kwargs[param_name] = arg |
| 1695 | |
| 1696 | return kwargs |
| 1697 | |
| 1698 | def __eq__(self, other): |
| 1699 | return (issubclass(other.__class__, BoundArguments) and |
| 1700 | self.signature == other.signature and |
| 1701 | self.arguments == other.arguments) |
| 1702 | |
| 1703 | def __ne__(self, other): |
| 1704 | return not self.__eq__(other) |
| 1705 | |
| 1706 | |
| 1707 | class Signature: |
| 1708 | '''A Signature object represents the overall signature of a function. |
| 1709 | It stores a Parameter object for each parameter accepted by the |
| 1710 | function, as well as information specific to the function itself. |
| 1711 | |
| 1712 | A Signature object has the following public attributes and methods: |
| 1713 | |
| 1714 | * parameters : OrderedDict |
| 1715 | An ordered mapping of parameters' names to the corresponding |
| 1716 | Parameter objects (keyword-only arguments are in the same order |
| 1717 | as listed in `code.co_varnames`). |
| 1718 | * return_annotation : object |
| 1719 | The annotation for the return type of the function if specified. |
| 1720 | If the function has no annotation for its return type, this |
| 1721 | attribute is not set. |
| 1722 | * bind(*args, **kwargs) -> BoundArguments |
| 1723 | Creates a mapping from positional and keyword arguments to |
| 1724 | parameters. |
| 1725 | * bind_partial(*args, **kwargs) -> BoundArguments |
| 1726 | Creates a partial mapping from positional and keyword arguments |
| 1727 | to parameters (simulating 'functools.partial' behavior.) |
| 1728 | ''' |
| 1729 | |
| 1730 | __slots__ = ('_return_annotation', '_parameters') |
| 1731 | |
| 1732 | _parameter_cls = Parameter |
| 1733 | _bound_arguments_cls = BoundArguments |
| 1734 | |
| 1735 | empty = _empty |
| 1736 | |
| 1737 | def __init__(self, parameters=None, *, return_annotation=_empty, |
| 1738 | __validate_parameters__=True): |
| 1739 | '''Constructs Signature from the given list of Parameter |
| 1740 | objects and 'return_annotation'. All arguments are optional. |
| 1741 | ''' |
| 1742 | |
| 1743 | if parameters is None: |
| 1744 | params = OrderedDict() |
| 1745 | else: |
| 1746 | if __validate_parameters__: |
| 1747 | params = OrderedDict() |
| 1748 | top_kind = _POSITIONAL_ONLY |
| 1749 | |
| 1750 | for idx, param in enumerate(parameters): |
| 1751 | kind = param.kind |
| 1752 | if kind < top_kind: |
| 1753 | msg = 'wrong parameter order: {} before {}' |
| 1754 | msg = msg.format(top_kind, param.kind) |
| 1755 | raise ValueError(msg) |
| 1756 | else: |
| 1757 | top_kind = kind |
| 1758 | |
| 1759 | name = param.name |
| 1760 | if name is None: |
| 1761 | name = str(idx) |
| 1762 | param = param.replace(name=name) |
| 1763 | |
| 1764 | if name in params: |
| 1765 | msg = 'duplicate parameter name: {!r}'.format(name) |
| 1766 | raise ValueError(msg) |
| 1767 | params[name] = param |
| 1768 | else: |
| 1769 | params = OrderedDict(((param.name, param) |
| 1770 | for param in parameters)) |
| 1771 | |
| 1772 | self._parameters = types.MappingProxyType(params) |
| 1773 | self._return_annotation = return_annotation |
| 1774 | |
| 1775 | @classmethod |
| 1776 | def from_function(cls, func): |
| 1777 | '''Constructs Signature for the given python function''' |
| 1778 | |
| 1779 | if not isinstance(func, types.FunctionType): |
| 1780 | raise TypeError('{!r} is not a Python function'.format(func)) |
| 1781 | |
| 1782 | Parameter = cls._parameter_cls |
| 1783 | |
| 1784 | # Parameter information. |
| 1785 | func_code = func.__code__ |
| 1786 | pos_count = func_code.co_argcount |
| 1787 | arg_names = func_code.co_varnames |
| 1788 | positional = tuple(arg_names[:pos_count]) |
| 1789 | keyword_only_count = func_code.co_kwonlyargcount |
| 1790 | keyword_only = arg_names[pos_count:(pos_count + keyword_only_count)] |
| 1791 | annotations = func.__annotations__ |
| 1792 | defaults = func.__defaults__ |
| 1793 | kwdefaults = func.__kwdefaults__ |
| 1794 | |
| 1795 | if defaults: |
| 1796 | pos_default_count = len(defaults) |
| 1797 | else: |
| 1798 | pos_default_count = 0 |
| 1799 | |
| 1800 | parameters = [] |
| 1801 | |
| 1802 | # Non-keyword-only parameters w/o defaults. |
| 1803 | non_default_count = pos_count - pos_default_count |
| 1804 | for name in positional[:non_default_count]: |
| 1805 | annotation = annotations.get(name, _empty) |
| 1806 | parameters.append(Parameter(name, annotation=annotation, |
| 1807 | kind=_POSITIONAL_OR_KEYWORD)) |
| 1808 | |
| 1809 | # ... w/ defaults. |
| 1810 | for offset, name in enumerate(positional[non_default_count:]): |
| 1811 | annotation = annotations.get(name, _empty) |
| 1812 | parameters.append(Parameter(name, annotation=annotation, |
| 1813 | kind=_POSITIONAL_OR_KEYWORD, |
| 1814 | default=defaults[offset])) |
| 1815 | |
| 1816 | # *args |
| 1817 | if func_code.co_flags & 0x04: |
| 1818 | name = arg_names[pos_count + keyword_only_count] |
| 1819 | annotation = annotations.get(name, _empty) |
| 1820 | parameters.append(Parameter(name, annotation=annotation, |
| 1821 | kind=_VAR_POSITIONAL)) |
| 1822 | |
| 1823 | # Keyword-only parameters. |
| 1824 | for name in keyword_only: |
| 1825 | default = _empty |
| 1826 | if kwdefaults is not None: |
| 1827 | default = kwdefaults.get(name, _empty) |
| 1828 | |
| 1829 | annotation = annotations.get(name, _empty) |
| 1830 | parameters.append(Parameter(name, annotation=annotation, |
| 1831 | kind=_KEYWORD_ONLY, |
| 1832 | default=default)) |
| 1833 | # **kwargs |
| 1834 | if func_code.co_flags & 0x08: |
| 1835 | index = pos_count + keyword_only_count |
| 1836 | if func_code.co_flags & 0x04: |
| 1837 | index += 1 |
| 1838 | |
| 1839 | name = arg_names[index] |
| 1840 | annotation = annotations.get(name, _empty) |
| 1841 | parameters.append(Parameter(name, annotation=annotation, |
| 1842 | kind=_VAR_KEYWORD)) |
| 1843 | |
| 1844 | return cls(parameters, |
| 1845 | return_annotation=annotations.get('return', _empty), |
| 1846 | __validate_parameters__=False) |
| 1847 | |
| 1848 | @property |
| 1849 | def parameters(self): |
| 1850 | return self._parameters |
| 1851 | |
| 1852 | @property |
| 1853 | def return_annotation(self): |
| 1854 | return self._return_annotation |
| 1855 | |
| 1856 | def replace(self, *, parameters=_void, return_annotation=_void): |
| 1857 | '''Creates a customized copy of the Signature. |
| 1858 | Pass 'parameters' and/or 'return_annotation' arguments |
| 1859 | to override them in the new copy. |
| 1860 | ''' |
| 1861 | |
| 1862 | if parameters is _void: |
| 1863 | parameters = self.parameters.values() |
| 1864 | |
| 1865 | if return_annotation is _void: |
| 1866 | return_annotation = self._return_annotation |
| 1867 | |
| 1868 | return type(self)(parameters, |
| 1869 | return_annotation=return_annotation) |
| 1870 | |
| 1871 | def __eq__(self, other): |
| 1872 | if (not issubclass(type(other), Signature) or |
| 1873 | self.return_annotation != other.return_annotation or |
| 1874 | len(self.parameters) != len(other.parameters)): |
| 1875 | return False |
| 1876 | |
| 1877 | other_positions = {param: idx |
| 1878 | for idx, param in enumerate(other.parameters.keys())} |
| 1879 | |
| 1880 | for idx, (param_name, param) in enumerate(self.parameters.items()): |
| 1881 | if param.kind == _KEYWORD_ONLY: |
| 1882 | try: |
| 1883 | other_param = other.parameters[param_name] |
| 1884 | except KeyError: |
| 1885 | return False |
| 1886 | else: |
| 1887 | if param != other_param: |
| 1888 | return False |
| 1889 | else: |
| 1890 | try: |
| 1891 | other_idx = other_positions[param_name] |
| 1892 | except KeyError: |
| 1893 | return False |
| 1894 | else: |
| 1895 | if (idx != other_idx or |
| 1896 | param != other.parameters[param_name]): |
| 1897 | return False |
| 1898 | |
| 1899 | return True |
| 1900 | |
| 1901 | def __ne__(self, other): |
| 1902 | return not self.__eq__(other) |
| 1903 | |
| 1904 | def _bind(self, args, kwargs, *, partial=False): |
| 1905 | '''Private method. Don't use directly.''' |
| 1906 | |
| 1907 | arguments = OrderedDict() |
| 1908 | |
| 1909 | parameters = iter(self.parameters.values()) |
| 1910 | parameters_ex = () |
| 1911 | arg_vals = iter(args) |
| 1912 | |
| 1913 | if partial: |
| 1914 | # Support for binding arguments to 'functools.partial' objects. |
| 1915 | # See 'functools.partial' case in 'signature()' implementation |
| 1916 | # for details. |
| 1917 | for param_name, param in self.parameters.items(): |
| 1918 | if (param._partial_kwarg and param_name not in kwargs): |
| 1919 | # Simulating 'functools.partial' behavior |
| 1920 | kwargs[param_name] = param.default |
| 1921 | |
| 1922 | while True: |
| 1923 | # Let's iterate through the positional arguments and corresponding |
| 1924 | # parameters |
| 1925 | try: |
| 1926 | arg_val = next(arg_vals) |
| 1927 | except StopIteration: |
| 1928 | # No more positional arguments |
| 1929 | try: |
| 1930 | param = next(parameters) |
| 1931 | except StopIteration: |
| 1932 | # No more parameters. That's it. Just need to check that |
| 1933 | # we have no `kwargs` after this while loop |
| 1934 | break |
| 1935 | else: |
| 1936 | if param.kind == _VAR_POSITIONAL: |
| 1937 | # That's OK, just empty *args. Let's start parsing |
| 1938 | # kwargs |
| 1939 | break |
| 1940 | elif param.name in kwargs: |
| 1941 | if param.kind == _POSITIONAL_ONLY: |
| 1942 | msg = '{arg!r} parameter is positional only, ' \ |
| 1943 | 'but was passed as a keyword' |
| 1944 | msg = msg.format(arg=param.name) |
| 1945 | raise TypeError(msg) from None |
| 1946 | parameters_ex = (param,) |
| 1947 | break |
| 1948 | elif (param.kind == _VAR_KEYWORD or |
| 1949 | param.default is not _empty): |
| 1950 | # That's fine too - we have a default value for this |
| 1951 | # parameter. So, lets start parsing `kwargs`, starting |
| 1952 | # with the current parameter |
| 1953 | parameters_ex = (param,) |
| 1954 | break |
| 1955 | else: |
| 1956 | if partial: |
| 1957 | parameters_ex = (param,) |
| 1958 | break |
| 1959 | else: |
| 1960 | msg = '{arg!r} parameter lacking default value' |
| 1961 | msg = msg.format(arg=param.name) |
| 1962 | raise TypeError(msg) from None |
| 1963 | else: |
| 1964 | # We have a positional argument to process |
| 1965 | try: |
| 1966 | param = next(parameters) |
| 1967 | except StopIteration: |
| 1968 | raise TypeError('too many positional arguments') from None |
| 1969 | else: |
| 1970 | if param.kind in (_VAR_KEYWORD, _KEYWORD_ONLY): |
| 1971 | # Looks like we have no parameter for this positional |
| 1972 | # argument |
| 1973 | raise TypeError('too many positional arguments') |
| 1974 | |
| 1975 | if param.kind == _VAR_POSITIONAL: |
| 1976 | # We have an '*args'-like argument, let's fill it with |
| 1977 | # all positional arguments we have left and move on to |
| 1978 | # the next phase |
| 1979 | values = [arg_val] |
| 1980 | values.extend(arg_vals) |
| 1981 | arguments[param.name] = tuple(values) |
| 1982 | break |
| 1983 | |
| 1984 | if param.name in kwargs: |
| 1985 | raise TypeError('multiple values for argument ' |
| 1986 | '{arg!r}'.format(arg=param.name)) |
| 1987 | |
| 1988 | arguments[param.name] = arg_val |
| 1989 | |
| 1990 | # Now, we iterate through the remaining parameters to process |
| 1991 | # keyword arguments |
| 1992 | kwargs_param = None |
| 1993 | for param in itertools.chain(parameters_ex, parameters): |
| 1994 | if param.kind == _POSITIONAL_ONLY: |
| 1995 | # This should never happen in case of a properly built |
| 1996 | # Signature object (but let's have this check here |
| 1997 | # to ensure correct behaviour just in case) |
| 1998 | raise TypeError('{arg!r} parameter is positional only, ' |
| 1999 | 'but was passed as a keyword'. \ |
| 2000 | format(arg=param.name)) |
| 2001 | |
| 2002 | if param.kind == _VAR_KEYWORD: |
| 2003 | # Memorize that we have a '**kwargs'-like parameter |
| 2004 | kwargs_param = param |
| 2005 | continue |
| 2006 | |
| 2007 | param_name = param.name |
| 2008 | try: |
| 2009 | arg_val = kwargs.pop(param_name) |
| 2010 | except KeyError: |
| 2011 | # We have no value for this parameter. It's fine though, |
| 2012 | # if it has a default value, or it is an '*args'-like |
| 2013 | # parameter, left alone by the processing of positional |
| 2014 | # arguments. |
| 2015 | if (not partial and param.kind != _VAR_POSITIONAL and |
| 2016 | param.default is _empty): |
| 2017 | raise TypeError('{arg!r} parameter lacking default value'. \ |
| 2018 | format(arg=param_name)) from None |
| 2019 | |
| 2020 | else: |
| 2021 | arguments[param_name] = arg_val |
| 2022 | |
| 2023 | if kwargs: |
| 2024 | if kwargs_param is not None: |
| 2025 | # Process our '**kwargs'-like parameter |
| 2026 | arguments[kwargs_param.name] = kwargs |
| 2027 | else: |
| 2028 | raise TypeError('too many keyword arguments') |
| 2029 | |
| 2030 | return self._bound_arguments_cls(self, arguments) |
| 2031 | |
Antoine Pitrou | bd41d1b | 2013-01-29 21:20:57 +0100 | [diff] [blame] | 2032 | def bind(__bind_self, *args, **kwargs): |
Larry Hastings | 7c7cbfc | 2012-06-22 15:19:35 -0700 | [diff] [blame] | 2033 | '''Get a BoundArguments object, that maps the passed `args` |
| 2034 | and `kwargs` to the function's signature. Raises `TypeError` |
| 2035 | if the passed arguments can not be bound. |
| 2036 | ''' |
Antoine Pitrou | bd41d1b | 2013-01-29 21:20:57 +0100 | [diff] [blame] | 2037 | return __bind_self._bind(args, kwargs) |
Larry Hastings | 7c7cbfc | 2012-06-22 15:19:35 -0700 | [diff] [blame] | 2038 | |
Antoine Pitrou | bd41d1b | 2013-01-29 21:20:57 +0100 | [diff] [blame] | 2039 | def bind_partial(__bind_self, *args, **kwargs): |
Larry Hastings | 7c7cbfc | 2012-06-22 15:19:35 -0700 | [diff] [blame] | 2040 | '''Get a BoundArguments object, that partially maps the |
| 2041 | passed `args` and `kwargs` to the function's signature. |
| 2042 | Raises `TypeError` if the passed arguments can not be bound. |
| 2043 | ''' |
Antoine Pitrou | bd41d1b | 2013-01-29 21:20:57 +0100 | [diff] [blame] | 2044 | return __bind_self._bind(args, kwargs, partial=True) |
Larry Hastings | 7c7cbfc | 2012-06-22 15:19:35 -0700 | [diff] [blame] | 2045 | |
| 2046 | def __str__(self): |
| 2047 | result = [] |
| 2048 | render_kw_only_separator = True |
| 2049 | for idx, param in enumerate(self.parameters.values()): |
| 2050 | formatted = str(param) |
| 2051 | |
| 2052 | kind = param.kind |
| 2053 | if kind == _VAR_POSITIONAL: |
| 2054 | # OK, we have an '*args'-like parameter, so we won't need |
| 2055 | # a '*' to separate keyword-only arguments |
| 2056 | render_kw_only_separator = False |
| 2057 | elif kind == _KEYWORD_ONLY and render_kw_only_separator: |
| 2058 | # We have a keyword-only parameter to render and we haven't |
| 2059 | # rendered an '*args'-like parameter before, so add a '*' |
| 2060 | # separator to the parameters list ("foo(arg1, *, arg2)" case) |
| 2061 | result.append('*') |
| 2062 | # This condition should be only triggered once, so |
| 2063 | # reset the flag |
| 2064 | render_kw_only_separator = False |
| 2065 | |
| 2066 | result.append(formatted) |
| 2067 | |
| 2068 | rendered = '({})'.format(', '.join(result)) |
| 2069 | |
| 2070 | if self.return_annotation is not _empty: |
| 2071 | anno = formatannotation(self.return_annotation) |
| 2072 | rendered += ' -> {}'.format(anno) |
| 2073 | |
| 2074 | return rendered |