| 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 | 
| Yury Selivanov | 0cf3ed6 | 2014-04-01 10:17:08 -0400 | [diff] [blame] | 20 |     getfullargspec() - same, with support for Python 3 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 |  | 
| Larry Hastings | 44e2eaa | 2013-11-23 15:37:55 -0800 | [diff] [blame] | 34 | import ast | 
| Antoine Pitrou | a8723a0 | 2015-04-15 00:41:29 +0200 | [diff] [blame] | 35 | import dis | 
| Yury Selivanov | 7544508 | 2015-05-11 22:57:16 -0400 | [diff] [blame] | 36 | import collections.abc | 
| Yury Selivanov | 21e83a5 | 2014-03-27 11:23:13 -0400 | [diff] [blame] | 37 | import enum | 
| Brett Cannon | cb66eb0 | 2012-05-11 12:58:42 -0400 | [diff] [blame] | 38 | import importlib.machinery | 
 | 39 | import itertools | 
| Christian Heimes | 7131fd9 | 2008-02-19 14:21:46 +0000 | [diff] [blame] | 40 | import linecache | 
| Brett Cannon | cb66eb0 | 2012-05-11 12:58:42 -0400 | [diff] [blame] | 41 | import os | 
 | 42 | import re | 
 | 43 | import sys | 
 | 44 | import tokenize | 
| Larry Hastings | 2623c8c | 2014-02-08 22:15:29 -0800 | [diff] [blame] | 45 | import token | 
| Brett Cannon | cb66eb0 | 2012-05-11 12:58:42 -0400 | [diff] [blame] | 46 | import types | 
| Brett Cannon | 2b88fcf | 2012-06-02 22:28:42 -0400 | [diff] [blame] | 47 | import warnings | 
| Larry Hastings | 7c7cbfc | 2012-06-22 15:19:35 -0700 | [diff] [blame] | 48 | import functools | 
| Nick Coghlan | 2f92e54 | 2012-06-23 19:39:55 +1000 | [diff] [blame] | 49 | import builtins | 
| Raymond Hettinger | a1a992c | 2005-03-11 06:46:45 +0000 | [diff] [blame] | 50 | from operator import attrgetter | 
| Larry Hastings | 7c7cbfc | 2012-06-22 15:19:35 -0700 | [diff] [blame] | 51 | from collections import namedtuple, OrderedDict | 
| Nick Coghlan | 09c8123 | 2010-08-17 10:18:16 +0000 | [diff] [blame] | 52 |  | 
 | 53 | # Create constants for the compiler flags in Include/code.h | 
| Antoine Pitrou | a8723a0 | 2015-04-15 00:41:29 +0200 | [diff] [blame] | 54 | # We try to get them from dis to avoid duplication | 
 | 55 | mod_dict = globals() | 
 | 56 | for k, v in dis.COMPILER_FLAG_NAMES.items(): | 
 | 57 |     mod_dict["CO_" + v] = k | 
| Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 58 |  | 
| Christian Heimes | be5b30b | 2008-03-03 19:18:51 +0000 | [diff] [blame] | 59 | # See Include/object.h | 
 | 60 | TPFLAGS_IS_ABSTRACT = 1 << 20 | 
 | 61 |  | 
| Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 62 | # ----------------------------------------------------------- type-checking | 
 | 63 | def ismodule(object): | 
 | 64 |     """Return true if the object is a module. | 
 | 65 |  | 
 | 66 |     Module objects provide these attributes: | 
| Barry Warsaw | 28a691b | 2010-04-17 00:19:56 +0000 | [diff] [blame] | 67 |         __cached__      pathname to byte compiled file | 
| Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 68 |         __doc__         documentation string | 
 | 69 |         __file__        filename (missing for built-in modules)""" | 
| Tim Peters | 28bc59f | 2001-09-16 08:40:16 +0000 | [diff] [blame] | 70 |     return isinstance(object, types.ModuleType) | 
| Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 71 |  | 
 | 72 | def isclass(object): | 
 | 73 |     """Return true if the object is a class. | 
 | 74 |  | 
 | 75 |     Class objects provide these attributes: | 
 | 76 |         __doc__         documentation string | 
 | 77 |         __module__      name of module in which this class was defined""" | 
| Benjamin Peterson | c465600 | 2009-01-17 22:41:18 +0000 | [diff] [blame] | 78 |     return isinstance(object, type) | 
| Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 79 |  | 
 | 80 | def ismethod(object): | 
 | 81 |     """Return true if the object is an instance method. | 
 | 82 |  | 
 | 83 |     Instance method objects provide these attributes: | 
 | 84 |         __doc__         documentation string | 
 | 85 |         __name__        name with which this method was defined | 
| Christian Heimes | ff73795 | 2007-11-27 10:40:20 +0000 | [diff] [blame] | 86 |         __func__        function object containing implementation of method | 
 | 87 |         __self__        instance to which this method is bound""" | 
| Tim Peters | 28bc59f | 2001-09-16 08:40:16 +0000 | [diff] [blame] | 88 |     return isinstance(object, types.MethodType) | 
| Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 89 |  | 
| Tim Peters | 536d226 | 2001-09-20 05:13:38 +0000 | [diff] [blame] | 90 | def ismethoddescriptor(object): | 
| Tim Peters | f1d90b9 | 2001-09-20 05:47:55 +0000 | [diff] [blame] | 91 |     """Return true if the object is a method descriptor. | 
 | 92 |  | 
 | 93 |     But not if ismethod() or isclass() or isfunction() are true. | 
| Tim Peters | 536d226 | 2001-09-20 05:13:38 +0000 | [diff] [blame] | 94 |  | 
 | 95 |     This is new in Python 2.2, and, for example, is true of int.__add__. | 
 | 96 |     An object passing this test has a __get__ attribute but not a __set__ | 
 | 97 |     attribute, but beyond that the set of attributes varies.  __name__ is | 
 | 98 |     usually sensible, and __doc__ often is. | 
 | 99 |  | 
| Tim Peters | f1d90b9 | 2001-09-20 05:47:55 +0000 | [diff] [blame] | 100 |     Methods implemented via descriptors that also pass one of the other | 
 | 101 |     tests return false from the ismethoddescriptor() test, simply because | 
 | 102 |     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] | 103 |     __func__ attribute (etc) when an object passes ismethod().""" | 
| Antoine Pitrou | 86a8a9a | 2011-12-21 09:57:40 +0100 | [diff] [blame] | 104 |     if isclass(object) or ismethod(object) or isfunction(object): | 
 | 105 |         # mutual exclusion | 
 | 106 |         return False | 
 | 107 |     tp = type(object) | 
 | 108 |     return hasattr(tp, "__get__") and not hasattr(tp, "__set__") | 
| Tim Peters | 536d226 | 2001-09-20 05:13:38 +0000 | [diff] [blame] | 109 |  | 
| Martin v. Löwis | e59e2ba | 2003-05-03 09:09:02 +0000 | [diff] [blame] | 110 | def isdatadescriptor(object): | 
 | 111 |     """Return true if the object is a data descriptor. | 
 | 112 |  | 
 | 113 |     Data descriptors have both a __get__ and a __set__ attribute.  Examples are | 
 | 114 |     properties (defined in Python) and getsets and members (defined in C). | 
 | 115 |     Typically, data descriptors will also have __name__ and __doc__ attributes | 
 | 116 |     (properties, getsets, and members have both of these attributes), but this | 
 | 117 |     is not guaranteed.""" | 
| Antoine Pitrou | 86a8a9a | 2011-12-21 09:57:40 +0100 | [diff] [blame] | 118 |     if isclass(object) or ismethod(object) or isfunction(object): | 
 | 119 |         # mutual exclusion | 
 | 120 |         return False | 
 | 121 |     tp = type(object) | 
 | 122 |     return hasattr(tp, "__set__") and hasattr(tp, "__get__") | 
| Martin v. Löwis | e59e2ba | 2003-05-03 09:09:02 +0000 | [diff] [blame] | 123 |  | 
| Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 124 | if hasattr(types, 'MemberDescriptorType'): | 
 | 125 |     # CPython and equivalent | 
 | 126 |     def ismemberdescriptor(object): | 
 | 127 |         """Return true if the object is a member descriptor. | 
 | 128 |  | 
 | 129 |         Member descriptors are specialized descriptors defined in extension | 
 | 130 |         modules.""" | 
 | 131 |         return isinstance(object, types.MemberDescriptorType) | 
 | 132 | else: | 
 | 133 |     # Other implementations | 
 | 134 |     def ismemberdescriptor(object): | 
 | 135 |         """Return true if the object is a member descriptor. | 
 | 136 |  | 
 | 137 |         Member descriptors are specialized descriptors defined in extension | 
 | 138 |         modules.""" | 
 | 139 |         return False | 
 | 140 |  | 
 | 141 | if hasattr(types, 'GetSetDescriptorType'): | 
 | 142 |     # CPython and equivalent | 
 | 143 |     def isgetsetdescriptor(object): | 
 | 144 |         """Return true if the object is a getset descriptor. | 
 | 145 |  | 
 | 146 |         getset descriptors are specialized descriptors defined in extension | 
 | 147 |         modules.""" | 
 | 148 |         return isinstance(object, types.GetSetDescriptorType) | 
 | 149 | else: | 
 | 150 |     # Other implementations | 
 | 151 |     def isgetsetdescriptor(object): | 
 | 152 |         """Return true if the object is a getset descriptor. | 
 | 153 |  | 
 | 154 |         getset descriptors are specialized descriptors defined in extension | 
 | 155 |         modules.""" | 
 | 156 |         return False | 
 | 157 |  | 
| Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 158 | def isfunction(object): | 
 | 159 |     """Return true if the object is a user-defined function. | 
 | 160 |  | 
 | 161 |     Function objects provide these attributes: | 
 | 162 |         __doc__         documentation string | 
 | 163 |         __name__        name with which this function was defined | 
| Neal Norwitz | 221085d | 2007-02-25 20:55:47 +0000 | [diff] [blame] | 164 |         __code__        code object containing compiled function bytecode | 
 | 165 |         __defaults__    tuple of any default values for arguments | 
 | 166 |         __globals__     global namespace in which this function was defined | 
 | 167 |         __annotations__ dict of parameter annotations | 
 | 168 |         __kwdefaults__  dict of keyword only parameters with defaults""" | 
| Tim Peters | 28bc59f | 2001-09-16 08:40:16 +0000 | [diff] [blame] | 169 |     return isinstance(object, types.FunctionType) | 
| Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 170 |  | 
| Christian Heimes | 7131fd9 | 2008-02-19 14:21:46 +0000 | [diff] [blame] | 171 | def isgeneratorfunction(object): | 
 | 172 |     """Return true if the object is a user-defined generator function. | 
 | 173 |  | 
 | 174 |     Generator function objects provides same attributes as functions. | 
 | 175 |  | 
| Alexander Belopolsky | 977a684 | 2010-08-16 20:17:07 +0000 | [diff] [blame] | 176 |     See help(isfunction) for attributes listing.""" | 
| Georg Brandl | b1441c7 | 2009-01-03 22:33:39 +0000 | [diff] [blame] | 177 |     return bool((isfunction(object) or ismethod(object)) and | 
| Yury Selivanov | 5376ba9 | 2015-06-22 12:19:30 -0400 | [diff] [blame] | 178 |                 object.__code__.co_flags & CO_GENERATOR) | 
| Yury Selivanov | 7544508 | 2015-05-11 22:57:16 -0400 | [diff] [blame] | 179 |  | 
 | 180 | def iscoroutinefunction(object): | 
 | 181 |     """Return true if the object is a coroutine function. | 
 | 182 |  | 
 | 183 |     Coroutine functions are defined with "async def" syntax, | 
 | 184 |     or generators decorated with "types.coroutine". | 
 | 185 |     """ | 
 | 186 |     return bool((isfunction(object) or ismethod(object)) and | 
| Yury Selivanov | 5376ba9 | 2015-06-22 12:19:30 -0400 | [diff] [blame] | 187 |                 object.__code__.co_flags & CO_COROUTINE) | 
| Yury Selivanov | 7544508 | 2015-05-11 22:57:16 -0400 | [diff] [blame] | 188 |  | 
| Christian Heimes | 7131fd9 | 2008-02-19 14:21:46 +0000 | [diff] [blame] | 189 | def isgenerator(object): | 
 | 190 |     """Return true if the object is a generator. | 
 | 191 |  | 
 | 192 |     Generator objects provide these attributes: | 
| Ezio Melotti | 30b9d5d | 2013-08-17 15:50:46 +0300 | [diff] [blame] | 193 |         __iter__        defined to support iteration over container | 
| Christian Heimes | 7131fd9 | 2008-02-19 14:21:46 +0000 | [diff] [blame] | 194 |         close           raises a new GeneratorExit exception inside the | 
 | 195 |                         generator to terminate the iteration | 
 | 196 |         gi_code         code object | 
 | 197 |         gi_frame        frame object or possibly None once the generator has | 
 | 198 |                         been exhausted | 
 | 199 |         gi_running      set to 1 when generator is executing, 0 otherwise | 
 | 200 |         next            return the next item from the container | 
 | 201 |         send            resumes the generator and "sends" a value that becomes | 
 | 202 |                         the result of the current yield-expression | 
 | 203 |         throw           used to raise an exception inside the generator""" | 
| Yury Selivanov | 5376ba9 | 2015-06-22 12:19:30 -0400 | [diff] [blame] | 204 |     return isinstance(object, types.GeneratorType) | 
| Yury Selivanov | 7544508 | 2015-05-11 22:57:16 -0400 | [diff] [blame] | 205 |  | 
 | 206 | def iscoroutine(object): | 
 | 207 |     """Return true if the object is a coroutine.""" | 
| Yury Selivanov | 5376ba9 | 2015-06-22 12:19:30 -0400 | [diff] [blame] | 208 |     return isinstance(object, types.CoroutineType) | 
| Christian Heimes | 7131fd9 | 2008-02-19 14:21:46 +0000 | [diff] [blame] | 209 |  | 
| Yury Selivanov | fdbeb2b | 2015-07-03 13:11:35 -0400 | [diff] [blame] | 210 | def isawaitable(object): | 
 | 211 |     """Return true is object can be passed to an ``await`` expression.""" | 
 | 212 |     return (isinstance(object, types.CoroutineType) or | 
 | 213 |             isinstance(object, types.GeneratorType) and | 
 | 214 |                 object.gi_code.co_flags & CO_ITERABLE_COROUTINE or | 
 | 215 |             isinstance(object, collections.abc.Awaitable)) | 
 | 216 |  | 
| Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 217 | def istraceback(object): | 
 | 218 |     """Return true if the object is a traceback. | 
 | 219 |  | 
 | 220 |     Traceback objects provide these attributes: | 
 | 221 |         tb_frame        frame object at this level | 
 | 222 |         tb_lasti        index of last attempted instruction in bytecode | 
 | 223 |         tb_lineno       current line number in Python source code | 
 | 224 |         tb_next         next inner traceback object (called by this level)""" | 
| Tim Peters | 28bc59f | 2001-09-16 08:40:16 +0000 | [diff] [blame] | 225 |     return isinstance(object, types.TracebackType) | 
| Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 226 |  | 
 | 227 | def isframe(object): | 
 | 228 |     """Return true if the object is a frame object. | 
 | 229 |  | 
 | 230 |     Frame objects provide these attributes: | 
 | 231 |         f_back          next outer frame object (this frame's caller) | 
 | 232 |         f_builtins      built-in namespace seen by this frame | 
 | 233 |         f_code          code object being executed in this frame | 
| Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 234 |         f_globals       global namespace seen by this frame | 
 | 235 |         f_lasti         index of last attempted instruction in bytecode | 
 | 236 |         f_lineno        current line number in Python source code | 
 | 237 |         f_locals        local namespace seen by this frame | 
| Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 238 |         f_trace         tracing function for this frame, or None""" | 
| Tim Peters | 28bc59f | 2001-09-16 08:40:16 +0000 | [diff] [blame] | 239 |     return isinstance(object, types.FrameType) | 
| Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 240 |  | 
 | 241 | def iscode(object): | 
 | 242 |     """Return true if the object is a code object. | 
 | 243 |  | 
 | 244 |     Code objects provide these attributes: | 
 | 245 |         co_argcount     number of arguments (not including * or ** args) | 
 | 246 |         co_code         string of raw compiled bytecode | 
 | 247 |         co_consts       tuple of constants used in the bytecode | 
 | 248 |         co_filename     name of file in which this code object was created | 
 | 249 |         co_firstlineno  number of first line in Python source code | 
 | 250 |         co_flags        bitmap: 1=optimized | 2=newlocals | 4=*arg | 8=**arg | 
 | 251 |         co_lnotab       encoded mapping of line numbers to bytecode indices | 
 | 252 |         co_name         name with which this code object was defined | 
 | 253 |         co_names        tuple of names of local variables | 
 | 254 |         co_nlocals      number of local variables | 
 | 255 |         co_stacksize    virtual machine stack space required | 
 | 256 |         co_varnames     tuple of names of arguments and local variables""" | 
| Tim Peters | 28bc59f | 2001-09-16 08:40:16 +0000 | [diff] [blame] | 257 |     return isinstance(object, types.CodeType) | 
| Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 258 |  | 
 | 259 | def isbuiltin(object): | 
 | 260 |     """Return true if the object is a built-in function or method. | 
 | 261 |  | 
 | 262 |     Built-in functions and methods provide these attributes: | 
 | 263 |         __doc__         documentation string | 
 | 264 |         __name__        original name of this function or method | 
 | 265 |         __self__        instance to which a method is bound, or None""" | 
| Tim Peters | 28bc59f | 2001-09-16 08:40:16 +0000 | [diff] [blame] | 266 |     return isinstance(object, types.BuiltinFunctionType) | 
| Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 267 |  | 
 | 268 | def isroutine(object): | 
 | 269 |     """Return true if the object is any kind of function or method.""" | 
| Tim Peters | 536d226 | 2001-09-20 05:13:38 +0000 | [diff] [blame] | 270 |     return (isbuiltin(object) | 
 | 271 |             or isfunction(object) | 
 | 272 |             or ismethod(object) | 
 | 273 |             or ismethoddescriptor(object)) | 
| Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 274 |  | 
| Christian Heimes | be5b30b | 2008-03-03 19:18:51 +0000 | [diff] [blame] | 275 | def isabstract(object): | 
 | 276 |     """Return true if the object is an abstract base class (ABC).""" | 
| Benjamin Peterson | a0dfa82 | 2009-11-13 02:25:08 +0000 | [diff] [blame] | 277 |     return bool(isinstance(object, type) and object.__flags__ & TPFLAGS_IS_ABSTRACT) | 
| Christian Heimes | be5b30b | 2008-03-03 19:18:51 +0000 | [diff] [blame] | 278 |  | 
| Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 279 | def getmembers(object, predicate=None): | 
 | 280 |     """Return all members of an object as (name, value) pairs sorted by name. | 
 | 281 |     Optionally, only return members that satisfy a given predicate.""" | 
| Antoine Pitrou | 86a8a9a | 2011-12-21 09:57:40 +0100 | [diff] [blame] | 282 |     if isclass(object): | 
 | 283 |         mro = (object,) + getmro(object) | 
 | 284 |     else: | 
 | 285 |         mro = () | 
| Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 286 |     results = [] | 
| Ethan Furman | e03ea37 | 2013-09-25 07:14:41 -0700 | [diff] [blame] | 287 |     processed = set() | 
 | 288 |     names = dir(object) | 
| Ethan Furman | b0c84cd | 2013-10-20 22:37:39 -0700 | [diff] [blame] | 289 |     # :dd any DynamicClassAttributes to the list of names if object is a class; | 
| Ethan Furman | e03ea37 | 2013-09-25 07:14:41 -0700 | [diff] [blame] | 290 |     # this may result in duplicate entries if, for example, a virtual | 
| Ethan Furman | b0c84cd | 2013-10-20 22:37:39 -0700 | [diff] [blame] | 291 |     # attribute with the same name as a DynamicClassAttribute exists | 
| Ethan Furman | e03ea37 | 2013-09-25 07:14:41 -0700 | [diff] [blame] | 292 |     try: | 
 | 293 |         for base in object.__bases__: | 
 | 294 |             for k, v in base.__dict__.items(): | 
 | 295 |                 if isinstance(v, types.DynamicClassAttribute): | 
 | 296 |                     names.append(k) | 
 | 297 |     except AttributeError: | 
 | 298 |         pass | 
 | 299 |     for key in names: | 
| Ethan Furman | 63c141c | 2013-10-18 00:27:39 -0700 | [diff] [blame] | 300 |         # First try to get the value via getattr.  Some descriptors don't | 
 | 301 |         # like calling their __get__ (see bug #1785), so fall back to | 
 | 302 |         # looking in the __dict__. | 
 | 303 |         try: | 
 | 304 |             value = getattr(object, key) | 
 | 305 |             # handle the duplicate key | 
 | 306 |             if key in processed: | 
 | 307 |                 raise AttributeError | 
 | 308 |         except AttributeError: | 
 | 309 |             for base in mro: | 
 | 310 |                 if key in base.__dict__: | 
 | 311 |                     value = base.__dict__[key] | 
 | 312 |                     break | 
 | 313 |             else: | 
 | 314 |                 # could be a (currently) missing slot member, or a buggy | 
 | 315 |                 # __dir__; discard and move on | 
| Antoine Pitrou | 86a8a9a | 2011-12-21 09:57:40 +0100 | [diff] [blame] | 316 |                 continue | 
| Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 317 |         if not predicate or predicate(value): | 
 | 318 |             results.append((key, value)) | 
| Ethan Furman | e03ea37 | 2013-09-25 07:14:41 -0700 | [diff] [blame] | 319 |         processed.add(key) | 
 | 320 |     results.sort(key=lambda pair: pair[0]) | 
| Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 321 |     return results | 
 | 322 |  | 
| Christian Heimes | 25bb783 | 2008-01-11 16:17:00 +0000 | [diff] [blame] | 323 | Attribute = namedtuple('Attribute', 'name kind defining_class object') | 
 | 324 |  | 
| Tim Peters | 13b49d3 | 2001-09-23 02:00:29 +0000 | [diff] [blame] | 325 | def classify_class_attrs(cls): | 
 | 326 |     """Return list of attribute-descriptor tuples. | 
 | 327 |  | 
 | 328 |     For each name in dir(cls), the return list contains a 4-tuple | 
 | 329 |     with these elements: | 
 | 330 |  | 
 | 331 |         0. The name (a string). | 
 | 332 |  | 
 | 333 |         1. The kind of attribute this is, one of these strings: | 
 | 334 |                'class method'    created via classmethod() | 
 | 335 |                'static method'   created via staticmethod() | 
 | 336 |                'property'        created via property() | 
| Ethan Furman | e03ea37 | 2013-09-25 07:14:41 -0700 | [diff] [blame] | 337 |                'method'          any other flavor of method or descriptor | 
| Tim Peters | 13b49d3 | 2001-09-23 02:00:29 +0000 | [diff] [blame] | 338 |                'data'            not a method | 
 | 339 |  | 
 | 340 |         2. The class which defined this attribute (a class). | 
 | 341 |  | 
| Ethan Furman | e03ea37 | 2013-09-25 07:14:41 -0700 | [diff] [blame] | 342 |         3. The object as obtained by calling getattr; if this fails, or if the | 
 | 343 |            resulting object does not live anywhere in the class' mro (including | 
 | 344 |            metaclasses) then the object is looked up in the defining class's | 
 | 345 |            dict (found by walking the mro). | 
| Ethan Furman | 668dede | 2013-09-14 18:53:26 -0700 | [diff] [blame] | 346 |  | 
 | 347 |     If one of the items in dir(cls) is stored in the metaclass it will now | 
 | 348 |     be discovered and not have None be listed as the class in which it was | 
| Ethan Furman | b0c84cd | 2013-10-20 22:37:39 -0700 | [diff] [blame] | 349 |     defined.  Any items whose home class cannot be discovered are skipped. | 
| Tim Peters | 13b49d3 | 2001-09-23 02:00:29 +0000 | [diff] [blame] | 350 |     """ | 
 | 351 |  | 
 | 352 |     mro = getmro(cls) | 
| Ethan Furman | 668dede | 2013-09-14 18:53:26 -0700 | [diff] [blame] | 353 |     metamro = getmro(type(cls)) # for attributes stored in the metaclass | 
| Ethan Furman | e03ea37 | 2013-09-25 07:14:41 -0700 | [diff] [blame] | 354 |     metamro = tuple([cls for cls in metamro if cls not in (type, object)]) | 
| Ethan Furman | b0c84cd | 2013-10-20 22:37:39 -0700 | [diff] [blame] | 355 |     class_bases = (cls,) + mro | 
 | 356 |     all_bases = class_bases + metamro | 
| Tim Peters | 13b49d3 | 2001-09-23 02:00:29 +0000 | [diff] [blame] | 357 |     names = dir(cls) | 
| Ethan Furman | b0c84cd | 2013-10-20 22:37:39 -0700 | [diff] [blame] | 358 |     # :dd any DynamicClassAttributes to the list of names; | 
| Ethan Furman | e03ea37 | 2013-09-25 07:14:41 -0700 | [diff] [blame] | 359 |     # this may result in duplicate entries if, for example, a virtual | 
| Ethan Furman | b0c84cd | 2013-10-20 22:37:39 -0700 | [diff] [blame] | 360 |     # attribute with the same name as a DynamicClassAttribute exists. | 
| Ethan Furman | 63c141c | 2013-10-18 00:27:39 -0700 | [diff] [blame] | 361 |     for base in mro: | 
| Ethan Furman | e03ea37 | 2013-09-25 07:14:41 -0700 | [diff] [blame] | 362 |         for k, v in base.__dict__.items(): | 
 | 363 |             if isinstance(v, types.DynamicClassAttribute): | 
 | 364 |                 names.append(k) | 
| Tim Peters | 13b49d3 | 2001-09-23 02:00:29 +0000 | [diff] [blame] | 365 |     result = [] | 
| Ethan Furman | e03ea37 | 2013-09-25 07:14:41 -0700 | [diff] [blame] | 366 |     processed = set() | 
| Ethan Furman | b0c84cd | 2013-10-20 22:37:39 -0700 | [diff] [blame] | 367 |  | 
| Tim Peters | 13b49d3 | 2001-09-23 02:00:29 +0000 | [diff] [blame] | 368 |     for name in names: | 
| Antoine Pitrou | 86a8a9a | 2011-12-21 09:57:40 +0100 | [diff] [blame] | 369 |         # Get the object associated with the name, and where it was defined. | 
| Ethan Furman | e03ea37 | 2013-09-25 07:14:41 -0700 | [diff] [blame] | 370 |         # Normal objects will be looked up with both getattr and directly in | 
 | 371 |         # its class' dict (in case getattr fails [bug #1785], and also to look | 
 | 372 |         # for a docstring). | 
| Ethan Furman | b0c84cd | 2013-10-20 22:37:39 -0700 | [diff] [blame] | 373 |         # For DynamicClassAttributes on the second pass we only look in the | 
| Ethan Furman | e03ea37 | 2013-09-25 07:14:41 -0700 | [diff] [blame] | 374 |         # class's dict. | 
 | 375 |         # | 
| Tim Peters | 13b49d3 | 2001-09-23 02:00:29 +0000 | [diff] [blame] | 376 |         # Getting an obj from the __dict__ sometimes reveals more than | 
 | 377 |         # using getattr.  Static and class methods are dramatic examples. | 
| Antoine Pitrou | 86a8a9a | 2011-12-21 09:57:40 +0100 | [diff] [blame] | 378 |         homecls = None | 
| Ethan Furman | b0c84cd | 2013-10-20 22:37:39 -0700 | [diff] [blame] | 379 |         get_obj = None | 
 | 380 |         dict_obj = None | 
| Ethan Furman | e03ea37 | 2013-09-25 07:14:41 -0700 | [diff] [blame] | 381 |         if name not in processed: | 
 | 382 |             try: | 
| Ethan Furman | a8b0707 | 2013-10-18 01:22:08 -0700 | [diff] [blame] | 383 |                 if name == '__dict__': | 
| Ethan Furman | b0c84cd | 2013-10-20 22:37:39 -0700 | [diff] [blame] | 384 |                     raise Exception("__dict__ is special, don't want the proxy") | 
| Ethan Furman | e03ea37 | 2013-09-25 07:14:41 -0700 | [diff] [blame] | 385 |                 get_obj = getattr(cls, name) | 
 | 386 |             except Exception as exc: | 
 | 387 |                 pass | 
 | 388 |             else: | 
| Ethan Furman | e03ea37 | 2013-09-25 07:14:41 -0700 | [diff] [blame] | 389 |                 homecls = getattr(get_obj, "__objclass__", homecls) | 
| Ethan Furman | b0c84cd | 2013-10-20 22:37:39 -0700 | [diff] [blame] | 390 |                 if homecls not in class_bases: | 
| Ethan Furman | e03ea37 | 2013-09-25 07:14:41 -0700 | [diff] [blame] | 391 |                     # if the resulting object does not live somewhere in the | 
| Ethan Furman | 63c141c | 2013-10-18 00:27:39 -0700 | [diff] [blame] | 392 |                     # mro, drop it and search the mro manually | 
| Ethan Furman | e03ea37 | 2013-09-25 07:14:41 -0700 | [diff] [blame] | 393 |                     homecls = None | 
| Ethan Furman | 63c141c | 2013-10-18 00:27:39 -0700 | [diff] [blame] | 394 |                     last_cls = None | 
| Ethan Furman | b0c84cd | 2013-10-20 22:37:39 -0700 | [diff] [blame] | 395 |                     # first look in the classes | 
 | 396 |                     for srch_cls in class_bases: | 
| Ethan Furman | 63c141c | 2013-10-18 00:27:39 -0700 | [diff] [blame] | 397 |                         srch_obj = getattr(srch_cls, name, None) | 
| Yury Selivanov | bf341fb | 2015-05-21 15:41:57 -0400 | [diff] [blame] | 398 |                         if srch_obj is get_obj: | 
| Ethan Furman | 63c141c | 2013-10-18 00:27:39 -0700 | [diff] [blame] | 399 |                             last_cls = srch_cls | 
| Ethan Furman | b0c84cd | 2013-10-20 22:37:39 -0700 | [diff] [blame] | 400 |                     # then check the metaclasses | 
 | 401 |                     for srch_cls in metamro: | 
 | 402 |                         try: | 
 | 403 |                             srch_obj = srch_cls.__getattr__(cls, name) | 
 | 404 |                         except AttributeError: | 
 | 405 |                             continue | 
| Yury Selivanov | bf341fb | 2015-05-21 15:41:57 -0400 | [diff] [blame] | 406 |                         if srch_obj is get_obj: | 
| Ethan Furman | b0c84cd | 2013-10-20 22:37:39 -0700 | [diff] [blame] | 407 |                             last_cls = srch_cls | 
| Ethan Furman | 63c141c | 2013-10-18 00:27:39 -0700 | [diff] [blame] | 408 |                     if last_cls is not None: | 
 | 409 |                         homecls = last_cls | 
| Ethan Furman | b0c84cd | 2013-10-20 22:37:39 -0700 | [diff] [blame] | 410 |         for base in all_bases: | 
| Ethan Furman | e03ea37 | 2013-09-25 07:14:41 -0700 | [diff] [blame] | 411 |             if name in base.__dict__: | 
 | 412 |                 dict_obj = base.__dict__[name] | 
| Ethan Furman | b0c84cd | 2013-10-20 22:37:39 -0700 | [diff] [blame] | 413 |                 if homecls not in metamro: | 
 | 414 |                     homecls = base | 
| Ethan Furman | e03ea37 | 2013-09-25 07:14:41 -0700 | [diff] [blame] | 415 |                 break | 
| Ethan Furman | 63c141c | 2013-10-18 00:27:39 -0700 | [diff] [blame] | 416 |         if homecls is None: | 
 | 417 |             # unable to locate the attribute anywhere, most likely due to | 
 | 418 |             # buggy custom __dir__; discard and move on | 
 | 419 |             continue | 
| Yury Selivanov | bf341fb | 2015-05-21 15:41:57 -0400 | [diff] [blame] | 420 |         obj = get_obj if get_obj is not None else dict_obj | 
| Ethan Furman | e03ea37 | 2013-09-25 07:14:41 -0700 | [diff] [blame] | 421 |         # Classify the object or its descriptor. | 
| Ethan Furman | 63c141c | 2013-10-18 00:27:39 -0700 | [diff] [blame] | 422 |         if isinstance(dict_obj, staticmethod): | 
| Tim Peters | 13b49d3 | 2001-09-23 02:00:29 +0000 | [diff] [blame] | 423 |             kind = "static method" | 
| Ethan Furman | b0c84cd | 2013-10-20 22:37:39 -0700 | [diff] [blame] | 424 |             obj = dict_obj | 
| Ethan Furman | 63c141c | 2013-10-18 00:27:39 -0700 | [diff] [blame] | 425 |         elif isinstance(dict_obj, classmethod): | 
| Tim Peters | 13b49d3 | 2001-09-23 02:00:29 +0000 | [diff] [blame] | 426 |             kind = "class method" | 
| Ethan Furman | b0c84cd | 2013-10-20 22:37:39 -0700 | [diff] [blame] | 427 |             obj = dict_obj | 
 | 428 |         elif isinstance(dict_obj, property): | 
| Tim Peters | 13b49d3 | 2001-09-23 02:00:29 +0000 | [diff] [blame] | 429 |             kind = "property" | 
| Ethan Furman | b0c84cd | 2013-10-20 22:37:39 -0700 | [diff] [blame] | 430 |             obj = dict_obj | 
| Yury Selivanov | 0860a0b | 2014-01-31 14:28:44 -0500 | [diff] [blame] | 431 |         elif isroutine(obj): | 
| Tim Peters | 13b49d3 | 2001-09-23 02:00:29 +0000 | [diff] [blame] | 432 |             kind = "method" | 
| Antoine Pitrou | 86a8a9a | 2011-12-21 09:57:40 +0100 | [diff] [blame] | 433 |         else: | 
| Ethan Furman | e03ea37 | 2013-09-25 07:14:41 -0700 | [diff] [blame] | 434 |             kind = "data" | 
| Christian Heimes | 25bb783 | 2008-01-11 16:17:00 +0000 | [diff] [blame] | 435 |         result.append(Attribute(name, kind, homecls, obj)) | 
| Ethan Furman | e03ea37 | 2013-09-25 07:14:41 -0700 | [diff] [blame] | 436 |         processed.add(name) | 
| Tim Peters | 13b49d3 | 2001-09-23 02:00:29 +0000 | [diff] [blame] | 437 |     return result | 
 | 438 |  | 
| Tim Peters | e0b2d7a | 2001-09-22 06:10:55 +0000 | [diff] [blame] | 439 | # ----------------------------------------------------------- class helpers | 
| Tim Peters | e0b2d7a | 2001-09-22 06:10:55 +0000 | [diff] [blame] | 440 |  | 
 | 441 | def getmro(cls): | 
 | 442 |     "Return tuple of base classes (including cls) in method resolution order." | 
| Benjamin Peterson | b82c8e5 | 2010-11-04 00:38:49 +0000 | [diff] [blame] | 443 |     return cls.__mro__ | 
| Tim Peters | e0b2d7a | 2001-09-22 06:10:55 +0000 | [diff] [blame] | 444 |  | 
| Nick Coghlan | e8c45d6 | 2013-07-28 20:00:01 +1000 | [diff] [blame] | 445 | # -------------------------------------------------------- function helpers | 
 | 446 |  | 
 | 447 | def unwrap(func, *, stop=None): | 
 | 448 |     """Get the object wrapped by *func*. | 
 | 449 |  | 
 | 450 |    Follows the chain of :attr:`__wrapped__` attributes returning the last | 
 | 451 |    object in the chain. | 
 | 452 |  | 
 | 453 |    *stop* is an optional callback accepting an object in the wrapper chain | 
 | 454 |    as its sole argument that allows the unwrapping to be terminated early if | 
 | 455 |    the callback returns a true value. If the callback never returns a true | 
 | 456 |    value, the last object in the chain is returned as usual. For example, | 
 | 457 |    :func:`signature` uses this to stop unwrapping if any object in the | 
 | 458 |    chain has a ``__signature__`` attribute defined. | 
 | 459 |  | 
 | 460 |    :exc:`ValueError` is raised if a cycle is encountered. | 
 | 461 |  | 
 | 462 |     """ | 
 | 463 |     if stop is None: | 
 | 464 |         def _is_wrapper(f): | 
 | 465 |             return hasattr(f, '__wrapped__') | 
 | 466 |     else: | 
 | 467 |         def _is_wrapper(f): | 
 | 468 |             return hasattr(f, '__wrapped__') and not stop(f) | 
 | 469 |     f = func  # remember the original func for error reporting | 
 | 470 |     memo = {id(f)} # Memoise by id to tolerate non-hashable objects | 
 | 471 |     while _is_wrapper(func): | 
 | 472 |         func = func.__wrapped__ | 
 | 473 |         id_func = id(func) | 
 | 474 |         if id_func in memo: | 
 | 475 |             raise ValueError('wrapper loop when unwrapping {!r}'.format(f)) | 
 | 476 |         memo.add(id_func) | 
 | 477 |     return func | 
 | 478 |  | 
| Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 479 | # -------------------------------------------------- source code extraction | 
 | 480 | def indentsize(line): | 
 | 481 |     """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] | 482 |     expline = line.expandtabs() | 
 | 483 |     return len(expline) - len(expline.lstrip()) | 
| Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 484 |  | 
| Serhiy Storchaka | 5cf2b725 | 2015-04-03 22:38:53 +0300 | [diff] [blame] | 485 | def _findclass(func): | 
 | 486 |     cls = sys.modules.get(func.__module__) | 
 | 487 |     if cls is None: | 
 | 488 |         return None | 
 | 489 |     for name in func.__qualname__.split('.')[:-1]: | 
 | 490 |         cls = getattr(cls, name) | 
 | 491 |     if not isclass(cls): | 
 | 492 |         return None | 
 | 493 |     return cls | 
 | 494 |  | 
 | 495 | def _finddoc(obj): | 
 | 496 |     if isclass(obj): | 
 | 497 |         for base in obj.__mro__: | 
 | 498 |             if base is not object: | 
 | 499 |                 try: | 
 | 500 |                     doc = base.__doc__ | 
 | 501 |                 except AttributeError: | 
 | 502 |                     continue | 
 | 503 |                 if doc is not None: | 
 | 504 |                     return doc | 
 | 505 |         return None | 
 | 506 |  | 
 | 507 |     if ismethod(obj): | 
 | 508 |         name = obj.__func__.__name__ | 
 | 509 |         self = obj.__self__ | 
 | 510 |         if (isclass(self) and | 
 | 511 |             getattr(getattr(self, name, None), '__func__') is obj.__func__): | 
 | 512 |             # classmethod | 
 | 513 |             cls = self | 
 | 514 |         else: | 
 | 515 |             cls = self.__class__ | 
 | 516 |     elif isfunction(obj): | 
 | 517 |         name = obj.__name__ | 
 | 518 |         cls = _findclass(obj) | 
 | 519 |         if cls is None or getattr(cls, name) is not obj: | 
 | 520 |             return None | 
 | 521 |     elif isbuiltin(obj): | 
 | 522 |         name = obj.__name__ | 
 | 523 |         self = obj.__self__ | 
 | 524 |         if (isclass(self) and | 
 | 525 |             self.__qualname__ + '.' + name == obj.__qualname__): | 
 | 526 |             # classmethod | 
 | 527 |             cls = self | 
 | 528 |         else: | 
 | 529 |             cls = self.__class__ | 
| Serhiy Storchaka | ac4bdcc | 2015-10-29 08:15:50 +0200 | [diff] [blame] | 530 |     # Should be tested before isdatadescriptor(). | 
 | 531 |     elif isinstance(obj, property): | 
 | 532 |         func = obj.fget | 
 | 533 |         name = func.__name__ | 
 | 534 |         cls = _findclass(func) | 
 | 535 |         if cls is None or getattr(cls, name) is not obj: | 
 | 536 |             return None | 
| Serhiy Storchaka | 5cf2b725 | 2015-04-03 22:38:53 +0300 | [diff] [blame] | 537 |     elif ismethoddescriptor(obj) or isdatadescriptor(obj): | 
 | 538 |         name = obj.__name__ | 
 | 539 |         cls = obj.__objclass__ | 
 | 540 |         if getattr(cls, name) is not obj: | 
 | 541 |             return None | 
| Serhiy Storchaka | 5cf2b725 | 2015-04-03 22:38:53 +0300 | [diff] [blame] | 542 |     else: | 
 | 543 |         return None | 
 | 544 |  | 
 | 545 |     for base in cls.__mro__: | 
 | 546 |         try: | 
 | 547 |             doc = getattr(base, name).__doc__ | 
 | 548 |         except AttributeError: | 
 | 549 |             continue | 
 | 550 |         if doc is not None: | 
 | 551 |             return doc | 
 | 552 |     return None | 
 | 553 |  | 
| Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 554 | def getdoc(object): | 
 | 555 |     """Get the documentation string for an object. | 
 | 556 |  | 
 | 557 |     All tabs are expanded to spaces.  To clean up docstrings that are | 
 | 558 |     indented to line up with blocks of code, any whitespace than can be | 
 | 559 |     uniformly removed from the second line onwards is removed.""" | 
| Tim Peters | 2400831 | 2002-03-17 18:56:20 +0000 | [diff] [blame] | 560 |     try: | 
 | 561 |         doc = object.__doc__ | 
 | 562 |     except AttributeError: | 
 | 563 |         return None | 
| Serhiy Storchaka | 5cf2b725 | 2015-04-03 22:38:53 +0300 | [diff] [blame] | 564 |     if doc is None: | 
 | 565 |         try: | 
 | 566 |             doc = _finddoc(object) | 
 | 567 |         except (AttributeError, TypeError): | 
 | 568 |             return None | 
| Guido van Rossum | 3172c5d | 2007-10-16 18:12:55 +0000 | [diff] [blame] | 569 |     if not isinstance(doc, str): | 
| Tim Peters | 2400831 | 2002-03-17 18:56:20 +0000 | [diff] [blame] | 570 |         return None | 
| Georg Brandl | 0c77a82 | 2008-06-10 16:37:50 +0000 | [diff] [blame] | 571 |     return cleandoc(doc) | 
 | 572 |  | 
 | 573 | def cleandoc(doc): | 
 | 574 |     """Clean up indentation from docstrings. | 
 | 575 |  | 
 | 576 |     Any whitespace that can be uniformly removed from the second line | 
 | 577 |     onwards is removed.""" | 
| Tim Peters | 2400831 | 2002-03-17 18:56:20 +0000 | [diff] [blame] | 578 |     try: | 
| Neal Norwitz | 9d72bb4 | 2007-04-17 08:48:32 +0000 | [diff] [blame] | 579 |         lines = doc.expandtabs().split('\n') | 
| Tim Peters | 2400831 | 2002-03-17 18:56:20 +0000 | [diff] [blame] | 580 |     except UnicodeError: | 
 | 581 |         return None | 
 | 582 |     else: | 
| Ka-Ping Yee | a59ef7b | 2002-11-30 03:53:15 +0000 | [diff] [blame] | 583 |         # Find minimum indentation of any non-blank lines after first line. | 
| Christian Heimes | a37d4c6 | 2007-12-04 23:02:19 +0000 | [diff] [blame] | 584 |         margin = sys.maxsize | 
| Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 585 |         for line in lines[1:]: | 
| Neal Norwitz | 9d72bb4 | 2007-04-17 08:48:32 +0000 | [diff] [blame] | 586 |             content = len(line.lstrip()) | 
| Ka-Ping Yee | a59ef7b | 2002-11-30 03:53:15 +0000 | [diff] [blame] | 587 |             if content: | 
 | 588 |                 indent = len(line) - content | 
 | 589 |                 margin = min(margin, indent) | 
 | 590 |         # Remove indentation. | 
 | 591 |         if lines: | 
 | 592 |             lines[0] = lines[0].lstrip() | 
| Christian Heimes | a37d4c6 | 2007-12-04 23:02:19 +0000 | [diff] [blame] | 593 |         if margin < sys.maxsize: | 
| Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 594 |             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] | 595 |         # Remove any trailing or leading blank lines. | 
 | 596 |         while lines and not lines[-1]: | 
 | 597 |             lines.pop() | 
 | 598 |         while lines and not lines[0]: | 
 | 599 |             lines.pop(0) | 
| Neal Norwitz | 9d72bb4 | 2007-04-17 08:48:32 +0000 | [diff] [blame] | 600 |         return '\n'.join(lines) | 
| Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 601 |  | 
 | 602 | def getfile(object): | 
| Ka-Ping Yee | c113c24 | 2001-03-02 02:08:53 +0000 | [diff] [blame] | 603 |     """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] | 604 |     if ismodule(object): | 
 | 605 |         if hasattr(object, '__file__'): | 
 | 606 |             return object.__file__ | 
| Benjamin Peterson | 4ac9ce4 | 2009-10-04 14:49:41 +0000 | [diff] [blame] | 607 |         raise TypeError('{!r} is a built-in module'.format(object)) | 
| Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 608 |     if isclass(object): | 
| Yury Selivanov | 2eed8b7 | 2014-01-27 13:24:56 -0500 | [diff] [blame] | 609 |         if hasattr(object, '__module__'): | 
 | 610 |             object = sys.modules.get(object.__module__) | 
 | 611 |             if hasattr(object, '__file__'): | 
 | 612 |                 return object.__file__ | 
| Benjamin Peterson | 4ac9ce4 | 2009-10-04 14:49:41 +0000 | [diff] [blame] | 613 |         raise TypeError('{!r} is a built-in class'.format(object)) | 
| Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 614 |     if ismethod(object): | 
| Christian Heimes | ff73795 | 2007-11-27 10:40:20 +0000 | [diff] [blame] | 615 |         object = object.__func__ | 
| Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 616 |     if isfunction(object): | 
| Neal Norwitz | 221085d | 2007-02-25 20:55:47 +0000 | [diff] [blame] | 617 |         object = object.__code__ | 
| Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 618 |     if istraceback(object): | 
 | 619 |         object = object.tb_frame | 
 | 620 |     if isframe(object): | 
 | 621 |         object = object.f_code | 
 | 622 |     if iscode(object): | 
 | 623 |         return object.co_filename | 
| Benjamin Peterson | 4ac9ce4 | 2009-10-04 14:49:41 +0000 | [diff] [blame] | 624 |     raise TypeError('{!r} is not a module, class, method, ' | 
 | 625 |                     'function, traceback, frame, or code object'.format(object)) | 
| Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 626 |  | 
| Christian Heimes | 25bb783 | 2008-01-11 16:17:00 +0000 | [diff] [blame] | 627 | ModuleInfo = namedtuple('ModuleInfo', 'name suffix mode module_type') | 
 | 628 |  | 
| Ka-Ping Yee | 4d6fc7f | 2001-04-10 11:43:00 +0000 | [diff] [blame] | 629 | def getmoduleinfo(path): | 
 | 630 |     """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] | 631 |     warnings.warn('inspect.getmoduleinfo() is deprecated', DeprecationWarning, | 
 | 632 |                   2) | 
| Brett Cannon | e4f41de | 2013-06-16 13:13:40 -0400 | [diff] [blame] | 633 |     with warnings.catch_warnings(): | 
 | 634 |         warnings.simplefilter('ignore', PendingDeprecationWarning) | 
 | 635 |         import imp | 
| Ka-Ping Yee | 4d6fc7f | 2001-04-10 11:43:00 +0000 | [diff] [blame] | 636 |     filename = os.path.basename(path) | 
| Guido van Rossum | 1bc535d | 2007-05-15 18:46:22 +0000 | [diff] [blame] | 637 |     suffixes = [(-len(suffix), suffix, mode, mtype) | 
 | 638 |                     for suffix, mode, mtype in imp.get_suffixes()] | 
| Ka-Ping Yee | 4d6fc7f | 2001-04-10 11:43:00 +0000 | [diff] [blame] | 639 |     suffixes.sort() # try longest suffixes first, in case they overlap | 
 | 640 |     for neglen, suffix, mode, mtype in suffixes: | 
 | 641 |         if filename[neglen:] == suffix: | 
| Christian Heimes | 25bb783 | 2008-01-11 16:17:00 +0000 | [diff] [blame] | 642 |             return ModuleInfo(filename[:neglen], suffix, mode, mtype) | 
| Ka-Ping Yee | 4d6fc7f | 2001-04-10 11:43:00 +0000 | [diff] [blame] | 643 |  | 
 | 644 | def getmodulename(path): | 
 | 645 |     """Return the module name for a given file, or None.""" | 
| Nick Coghlan | 76e0770 | 2012-07-18 23:14:57 +1000 | [diff] [blame] | 646 |     fname = os.path.basename(path) | 
 | 647 |     # Check for paths that look like an actual module file | 
 | 648 |     suffixes = [(-len(suffix), suffix) | 
 | 649 |                     for suffix in importlib.machinery.all_suffixes()] | 
 | 650 |     suffixes.sort() # try longest suffixes first, in case they overlap | 
 | 651 |     for neglen, suffix in suffixes: | 
 | 652 |         if fname.endswith(suffix): | 
 | 653 |             return fname[:neglen] | 
 | 654 |     return None | 
| Ka-Ping Yee | 4d6fc7f | 2001-04-10 11:43:00 +0000 | [diff] [blame] | 655 |  | 
| Ka-Ping Yee | c113c24 | 2001-03-02 02:08:53 +0000 | [diff] [blame] | 656 | def getsourcefile(object): | 
| R. David Murray | a1b3740 | 2010-06-17 02:04:29 +0000 | [diff] [blame] | 657 |     """Return the filename that can be used to locate an object's source. | 
 | 658 |     Return None if no way can be identified to get the source. | 
 | 659 |     """ | 
| Ka-Ping Yee | c113c24 | 2001-03-02 02:08:53 +0000 | [diff] [blame] | 660 |     filename = getfile(object) | 
| Brett Cannon | cb66eb0 | 2012-05-11 12:58:42 -0400 | [diff] [blame] | 661 |     all_bytecode_suffixes = importlib.machinery.DEBUG_BYTECODE_SUFFIXES[:] | 
 | 662 |     all_bytecode_suffixes += importlib.machinery.OPTIMIZED_BYTECODE_SUFFIXES[:] | 
 | 663 |     if any(filename.endswith(s) for s in all_bytecode_suffixes): | 
 | 664 |         filename = (os.path.splitext(filename)[0] + | 
 | 665 |                     importlib.machinery.SOURCE_SUFFIXES[0]) | 
 | 666 |     elif any(filename.endswith(s) for s in | 
 | 667 |                  importlib.machinery.EXTENSION_SUFFIXES): | 
 | 668 |         return None | 
| Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 669 |     if os.path.exists(filename): | 
 | 670 |         return filename | 
| Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 671 |     # only return a non-existent filename if the module has a PEP 302 loader | 
| Brett Cannon | 4c14b5d | 2013-05-04 13:56:58 -0400 | [diff] [blame] | 672 |     if getattr(getmodule(object, filename), '__loader__', None) is not None: | 
| Ka-Ping Yee | c113c24 | 2001-03-02 02:08:53 +0000 | [diff] [blame] | 673 |         return filename | 
| R. David Murray | a1b3740 | 2010-06-17 02:04:29 +0000 | [diff] [blame] | 674 |     # or it is in the linecache | 
 | 675 |     if filename in linecache.cache: | 
 | 676 |         return filename | 
| Ka-Ping Yee | c113c24 | 2001-03-02 02:08:53 +0000 | [diff] [blame] | 677 |  | 
| Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 678 | def getabsfile(object, _filename=None): | 
| Ka-Ping Yee | 4eb0c00 | 2001-03-02 05:50:34 +0000 | [diff] [blame] | 679 |     """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] | 680 |  | 
| Ka-Ping Yee | 4eb0c00 | 2001-03-02 05:50:34 +0000 | [diff] [blame] | 681 |     The idea is for each object to have a unique origin, so this routine | 
 | 682 |     normalizes the result as much as possible.""" | 
| Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 683 |     if _filename is None: | 
 | 684 |         _filename = getsourcefile(object) or getfile(object) | 
 | 685 |     return os.path.normcase(os.path.abspath(_filename)) | 
| Ka-Ping Yee | c113c24 | 2001-03-02 02:08:53 +0000 | [diff] [blame] | 686 |  | 
| Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 687 | modulesbyfile = {} | 
| Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 688 | _filesbymodname = {} | 
| Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 689 |  | 
| Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 690 | def getmodule(object, _filename=None): | 
| Ka-Ping Yee | 4eb0c00 | 2001-03-02 05:50:34 +0000 | [diff] [blame] | 691 |     """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] | 692 |     if ismodule(object): | 
 | 693 |         return object | 
| Johannes Gijsbers | 9324526 | 2004-09-11 15:53:22 +0000 | [diff] [blame] | 694 |     if hasattr(object, '__module__'): | 
| Ka-Ping Yee | 8b58b84 | 2001-03-01 13:56:16 +0000 | [diff] [blame] | 695 |         return sys.modules.get(object.__module__) | 
| Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 696 |     # Try the filename to modulename cache | 
 | 697 |     if _filename is not None and _filename in modulesbyfile: | 
 | 698 |         return sys.modules.get(modulesbyfile[_filename]) | 
 | 699 |     # Try the cache again with the absolute file name | 
| Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 700 |     try: | 
| Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 701 |         file = getabsfile(object, _filename) | 
| Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 702 |     except TypeError: | 
 | 703 |         return None | 
| Raymond Hettinger | 54f0222 | 2002-06-01 14:18:47 +0000 | [diff] [blame] | 704 |     if file in modulesbyfile: | 
| Ka-Ping Yee | b38bbbd | 2003-03-28 16:29:50 +0000 | [diff] [blame] | 705 |         return sys.modules.get(modulesbyfile[file]) | 
| Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 706 |     # Update the filename to module name cache and check yet again | 
 | 707 |     # Copy sys.modules in order to cope with changes while iterating | 
| Éric Araujo | a74f8ef | 2011-11-29 16:58:53 +0100 | [diff] [blame] | 708 |     for modname, module in list(sys.modules.items()): | 
| Thomas Wouters | 49fd7fa | 2006-04-21 10:40:58 +0000 | [diff] [blame] | 709 |         if ismodule(module) and hasattr(module, '__file__'): | 
| Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 710 |             f = module.__file__ | 
 | 711 |             if f == _filesbymodname.get(modname, None): | 
 | 712 |                 # Have already mapped this module, so skip it | 
 | 713 |                 continue | 
 | 714 |             _filesbymodname[modname] = f | 
| Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 715 |             f = getabsfile(module) | 
| Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 716 |             # Always map to the name the module knows itself by | 
| Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 717 |             modulesbyfile[f] = modulesbyfile[ | 
 | 718 |                 os.path.realpath(f)] = module.__name__ | 
| Raymond Hettinger | 54f0222 | 2002-06-01 14:18:47 +0000 | [diff] [blame] | 719 |     if file in modulesbyfile: | 
| Ka-Ping Yee | b38bbbd | 2003-03-28 16:29:50 +0000 | [diff] [blame] | 720 |         return sys.modules.get(modulesbyfile[file]) | 
| Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 721 |     # Check the main module | 
| Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 722 |     main = sys.modules['__main__'] | 
| Brett Cannon | 4a671fe | 2003-06-15 22:33:28 +0000 | [diff] [blame] | 723 |     if not hasattr(object, '__name__'): | 
 | 724 |         return None | 
| Ka-Ping Yee | 4eb0c00 | 2001-03-02 05:50:34 +0000 | [diff] [blame] | 725 |     if hasattr(main, object.__name__): | 
| Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 726 |         mainobject = getattr(main, object.__name__) | 
| Ka-Ping Yee | 4eb0c00 | 2001-03-02 05:50:34 +0000 | [diff] [blame] | 727 |         if mainobject is object: | 
 | 728 |             return main | 
| Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 729 |     # Check builtins | 
| Georg Brandl | 1a3284e | 2007-12-02 09:40:06 +0000 | [diff] [blame] | 730 |     builtin = sys.modules['builtins'] | 
| Ka-Ping Yee | 4eb0c00 | 2001-03-02 05:50:34 +0000 | [diff] [blame] | 731 |     if hasattr(builtin, object.__name__): | 
| Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 732 |         builtinobject = getattr(builtin, object.__name__) | 
| Ka-Ping Yee | 4eb0c00 | 2001-03-02 05:50:34 +0000 | [diff] [blame] | 733 |         if builtinobject is object: | 
 | 734 |             return builtin | 
| Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 735 |  | 
| Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 736 | def findsource(object): | 
 | 737 |     """Return the entire source file and starting line number for an object. | 
 | 738 |  | 
 | 739 |     The argument may be a module, class, method, function, traceback, frame, | 
 | 740 |     or code object.  The source code is returned as a list of all the lines | 
| Andrew Svetlov | f7a17b4 | 2012-12-25 16:47:37 +0200 | [diff] [blame] | 741 |     in the file and the line number indexes a line in that list.  An OSError | 
| Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 742 |     is raised if the source code cannot be retrieved.""" | 
| Benjamin Peterson | 9620cc0 | 2011-06-11 15:53:11 -0500 | [diff] [blame] | 743 |  | 
| Yury Selivanov | ef1e750 | 2014-12-08 16:05:34 -0500 | [diff] [blame] | 744 |     file = getsourcefile(object) | 
 | 745 |     if file: | 
 | 746 |         # Invalidate cache if needed. | 
 | 747 |         linecache.checkcache(file) | 
 | 748 |     else: | 
 | 749 |         file = getfile(object) | 
 | 750 |         # Allow filenames in form of "<something>" to pass through. | 
 | 751 |         # `doctest` monkeypatches `linecache` module to enable | 
 | 752 |         # inspection, so let `linecache.getlines` to be called. | 
 | 753 |         if not (file.startswith('<') and file.endswith('>')): | 
 | 754 |             raise OSError('source code not available') | 
| Benjamin Peterson | 9620cc0 | 2011-06-11 15:53:11 -0500 | [diff] [blame] | 755 |  | 
| Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 756 |     module = getmodule(object, file) | 
| Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 757 |     if module: | 
 | 758 |         lines = linecache.getlines(file, module.__dict__) | 
 | 759 |     else: | 
 | 760 |         lines = linecache.getlines(file) | 
| Neil Schemenauer | f06f853 | 2002-03-23 23:51:04 +0000 | [diff] [blame] | 761 |     if not lines: | 
| Andrew Svetlov | f7a17b4 | 2012-12-25 16:47:37 +0200 | [diff] [blame] | 762 |         raise OSError('could not get source code') | 
| Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 763 |  | 
 | 764 |     if ismodule(object): | 
 | 765 |         return lines, 0 | 
 | 766 |  | 
 | 767 |     if isclass(object): | 
 | 768 |         name = object.__name__ | 
| Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 769 |         pat = re.compile(r'^(\s*)class\s*' + name + r'\b') | 
 | 770 |         # make some effort to find the best matching class definition: | 
 | 771 |         # use the one with the least indentation, which is the one | 
 | 772 |         # that's most probably not inside a function definition. | 
 | 773 |         candidates = [] | 
| Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 774 |         for i in range(len(lines)): | 
| Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 775 |             match = pat.match(lines[i]) | 
 | 776 |             if match: | 
 | 777 |                 # if it's at toplevel, it's already the best one | 
 | 778 |                 if lines[i][0] == 'c': | 
 | 779 |                     return lines, i | 
 | 780 |                 # else add whitespace to candidate list | 
 | 781 |                 candidates.append((match.group(1), i)) | 
 | 782 |         if candidates: | 
 | 783 |             # this will sort by whitespace, and by line number, | 
 | 784 |             # less whitespace first | 
 | 785 |             candidates.sort() | 
 | 786 |             return lines, candidates[0][1] | 
| Jeremy Hylton | ab91902 | 2003-06-27 18:41:20 +0000 | [diff] [blame] | 787 |         else: | 
| Andrew Svetlov | f7a17b4 | 2012-12-25 16:47:37 +0200 | [diff] [blame] | 788 |             raise OSError('could not find class definition') | 
| Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 789 |  | 
 | 790 |     if ismethod(object): | 
| Christian Heimes | ff73795 | 2007-11-27 10:40:20 +0000 | [diff] [blame] | 791 |         object = object.__func__ | 
| Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 792 |     if isfunction(object): | 
| Neal Norwitz | 221085d | 2007-02-25 20:55:47 +0000 | [diff] [blame] | 793 |         object = object.__code__ | 
| Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 794 |     if istraceback(object): | 
 | 795 |         object = object.tb_frame | 
 | 796 |     if isframe(object): | 
 | 797 |         object = object.f_code | 
 | 798 |     if iscode(object): | 
| Ka-Ping Yee | 4eb0c00 | 2001-03-02 05:50:34 +0000 | [diff] [blame] | 799 |         if not hasattr(object, 'co_firstlineno'): | 
| Andrew Svetlov | f7a17b4 | 2012-12-25 16:47:37 +0200 | [diff] [blame] | 800 |             raise OSError('could not find function definition') | 
| Ka-Ping Yee | 4eb0c00 | 2001-03-02 05:50:34 +0000 | [diff] [blame] | 801 |         lnum = object.co_firstlineno - 1 | 
| Yury Selivanov | e4e811d | 2015-07-21 19:01:52 +0300 | [diff] [blame] | 802 |         pat = re.compile(r'^(\s*def\s)|(\s*async\s+def\s)|(.*(?<!\w)lambda(:|\s))|^(\s*@)') | 
| Ka-Ping Yee | 4eb0c00 | 2001-03-02 05:50:34 +0000 | [diff] [blame] | 803 |         while lnum > 0: | 
| Ka-Ping Yee | a6e5971 | 2001-03-10 09:31:55 +0000 | [diff] [blame] | 804 |             if pat.match(lines[lnum]): break | 
| Ka-Ping Yee | 4eb0c00 | 2001-03-02 05:50:34 +0000 | [diff] [blame] | 805 |             lnum = lnum - 1 | 
 | 806 |         return lines, lnum | 
| Andrew Svetlov | f7a17b4 | 2012-12-25 16:47:37 +0200 | [diff] [blame] | 807 |     raise OSError('could not find code object') | 
| Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 808 |  | 
 | 809 | def getcomments(object): | 
| Jeremy Hylton | b4c17c8 | 2002-03-28 23:01:56 +0000 | [diff] [blame] | 810 |     """Get lines of comments immediately preceding an object's source code. | 
 | 811 |  | 
 | 812 |     Returns None when source can't be found. | 
 | 813 |     """ | 
 | 814 |     try: | 
 | 815 |         lines, lnum = findsource(object) | 
| Andrew Svetlov | f7a17b4 | 2012-12-25 16:47:37 +0200 | [diff] [blame] | 816 |     except (OSError, TypeError): | 
| Jeremy Hylton | b4c17c8 | 2002-03-28 23:01:56 +0000 | [diff] [blame] | 817 |         return None | 
| Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 818 |  | 
 | 819 |     if ismodule(object): | 
 | 820 |         # Look for a comment block at the top of the file. | 
 | 821 |         start = 0 | 
| Ka-Ping Yee | b910efe | 2001-04-12 13:17:17 +0000 | [diff] [blame] | 822 |         if lines and lines[0][:2] == '#!': start = 1 | 
| Neal Norwitz | 9d72bb4 | 2007-04-17 08:48:32 +0000 | [diff] [blame] | 823 |         while start < len(lines) and lines[start].strip() in ('', '#'): | 
| Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 824 |             start = start + 1 | 
| Ka-Ping Yee | b910efe | 2001-04-12 13:17:17 +0000 | [diff] [blame] | 825 |         if start < len(lines) and lines[start][:1] == '#': | 
| Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 826 |             comments = [] | 
 | 827 |             end = start | 
 | 828 |             while end < len(lines) and lines[end][:1] == '#': | 
| Neal Norwitz | 9d72bb4 | 2007-04-17 08:48:32 +0000 | [diff] [blame] | 829 |                 comments.append(lines[end].expandtabs()) | 
| Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 830 |                 end = end + 1 | 
| Neal Norwitz | 9d72bb4 | 2007-04-17 08:48:32 +0000 | [diff] [blame] | 831 |             return ''.join(comments) | 
| Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 832 |  | 
 | 833 |     # Look for a preceding block of comments at the same indentation. | 
 | 834 |     elif lnum > 0: | 
 | 835 |         indent = indentsize(lines[lnum]) | 
 | 836 |         end = lnum - 1 | 
| Neal Norwitz | 9d72bb4 | 2007-04-17 08:48:32 +0000 | [diff] [blame] | 837 |         if end >= 0 and lines[end].lstrip()[:1] == '#' and \ | 
| Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 838 |             indentsize(lines[end]) == indent: | 
| Neal Norwitz | 9d72bb4 | 2007-04-17 08:48:32 +0000 | [diff] [blame] | 839 |             comments = [lines[end].expandtabs().lstrip()] | 
| Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 840 |             if end > 0: | 
 | 841 |                 end = end - 1 | 
| Neal Norwitz | 9d72bb4 | 2007-04-17 08:48:32 +0000 | [diff] [blame] | 842 |                 comment = lines[end].expandtabs().lstrip() | 
| Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 843 |                 while comment[:1] == '#' and indentsize(lines[end]) == indent: | 
 | 844 |                     comments[:0] = [comment] | 
 | 845 |                     end = end - 1 | 
 | 846 |                     if end < 0: break | 
| Neal Norwitz | 9d72bb4 | 2007-04-17 08:48:32 +0000 | [diff] [blame] | 847 |                     comment = lines[end].expandtabs().lstrip() | 
 | 848 |             while comments and comments[0].strip() == '#': | 
| Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 849 |                 comments[:1] = [] | 
| Neal Norwitz | 9d72bb4 | 2007-04-17 08:48:32 +0000 | [diff] [blame] | 850 |             while comments and comments[-1].strip() == '#': | 
| Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 851 |                 comments[-1:] = [] | 
| Neal Norwitz | 9d72bb4 | 2007-04-17 08:48:32 +0000 | [diff] [blame] | 852 |             return ''.join(comments) | 
| Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 853 |  | 
| Tim Peters | 4efb6e9 | 2001-06-29 23:51:08 +0000 | [diff] [blame] | 854 | class EndOfBlock(Exception): pass | 
 | 855 |  | 
 | 856 | class BlockFinder: | 
 | 857 |     """Provide a tokeneater() method to detect the end of a code block.""" | 
 | 858 |     def __init__(self): | 
 | 859 |         self.indent = 0 | 
| Johannes Gijsbers | a5855d5 | 2005-03-12 16:37:11 +0000 | [diff] [blame] | 860 |         self.islambda = False | 
| Johannes Gijsbers | 1542f34 | 2004-12-12 16:46:28 +0000 | [diff] [blame] | 861 |         self.started = False | 
 | 862 |         self.passline = False | 
| Meador Inge | 5b718d7 | 2015-07-23 22:49:37 -0500 | [diff] [blame] | 863 |         self.indecorator = False | 
 | 864 |         self.decoratorhasargs = False | 
| Armin Rigo | dd5c023 | 2005-09-25 11:45:45 +0000 | [diff] [blame] | 865 |         self.last = 1 | 
| Tim Peters | 4efb6e9 | 2001-06-29 23:51:08 +0000 | [diff] [blame] | 866 |  | 
| Guido van Rossum | 1bc535d | 2007-05-15 18:46:22 +0000 | [diff] [blame] | 867 |     def tokeneater(self, type, token, srowcol, erowcol, line): | 
| Meador Inge | 5b718d7 | 2015-07-23 22:49:37 -0500 | [diff] [blame] | 868 |         if not self.started and not self.indecorator: | 
 | 869 |             # skip any decorators | 
 | 870 |             if token == "@": | 
 | 871 |                 self.indecorator = True | 
| Armin Rigo | dd5c023 | 2005-09-25 11:45:45 +0000 | [diff] [blame] | 872 |             # look for the first "def", "class" or "lambda" | 
| Meador Inge | 5b718d7 | 2015-07-23 22:49:37 -0500 | [diff] [blame] | 873 |             elif token in ("def", "class", "lambda"): | 
| Johannes Gijsbers | a5855d5 | 2005-03-12 16:37:11 +0000 | [diff] [blame] | 874 |                 if token == "lambda": | 
 | 875 |                     self.islambda = True | 
| Johannes Gijsbers | 1542f34 | 2004-12-12 16:46:28 +0000 | [diff] [blame] | 876 |                 self.started = True | 
| Armin Rigo | dd5c023 | 2005-09-25 11:45:45 +0000 | [diff] [blame] | 877 |             self.passline = True    # skip to the end of the line | 
| Meador Inge | 5b718d7 | 2015-07-23 22:49:37 -0500 | [diff] [blame] | 878 |         elif token == "(": | 
 | 879 |             if self.indecorator: | 
 | 880 |                 self.decoratorhasargs = True | 
 | 881 |         elif token == ")": | 
 | 882 |             if self.indecorator: | 
 | 883 |                 self.indecorator = False | 
 | 884 |                 self.decoratorhasargs = False | 
| Tim Peters | 4efb6e9 | 2001-06-29 23:51:08 +0000 | [diff] [blame] | 885 |         elif type == tokenize.NEWLINE: | 
| Armin Rigo | dd5c023 | 2005-09-25 11:45:45 +0000 | [diff] [blame] | 886 |             self.passline = False   # stop skipping when a NEWLINE is seen | 
| Guido van Rossum | 1bc535d | 2007-05-15 18:46:22 +0000 | [diff] [blame] | 887 |             self.last = srowcol[0] | 
| Armin Rigo | dd5c023 | 2005-09-25 11:45:45 +0000 | [diff] [blame] | 888 |             if self.islambda:       # lambdas always end at the first NEWLINE | 
 | 889 |                 raise EndOfBlock | 
| Meador Inge | 5b718d7 | 2015-07-23 22:49:37 -0500 | [diff] [blame] | 890 |             # hitting a NEWLINE when in a decorator without args | 
 | 891 |             # ends the decorator | 
 | 892 |             if self.indecorator and not self.decoratorhasargs: | 
 | 893 |                 self.indecorator = False | 
| Johannes Gijsbers | 1542f34 | 2004-12-12 16:46:28 +0000 | [diff] [blame] | 894 |         elif self.passline: | 
 | 895 |             pass | 
| Tim Peters | 4efb6e9 | 2001-06-29 23:51:08 +0000 | [diff] [blame] | 896 |         elif type == tokenize.INDENT: | 
 | 897 |             self.indent = self.indent + 1 | 
| Johannes Gijsbers | 1542f34 | 2004-12-12 16:46:28 +0000 | [diff] [blame] | 898 |             self.passline = True | 
| Tim Peters | 4efb6e9 | 2001-06-29 23:51:08 +0000 | [diff] [blame] | 899 |         elif type == tokenize.DEDENT: | 
 | 900 |             self.indent = self.indent - 1 | 
| Armin Rigo | dd5c023 | 2005-09-25 11:45:45 +0000 | [diff] [blame] | 901 |             # the end of matching indent/dedent pairs end a block | 
 | 902 |             # (note that this only works for "def"/"class" blocks, | 
 | 903 |             #  not e.g. for "if: else:" or "try: finally:" blocks) | 
 | 904 |             if self.indent <= 0: | 
 | 905 |                 raise EndOfBlock | 
 | 906 |         elif self.indent == 0 and type not in (tokenize.COMMENT, tokenize.NL): | 
 | 907 |             # any other token on the same indentation level end the previous | 
 | 908 |             # block as well, except the pseudo-tokens COMMENT and NL. | 
 | 909 |             raise EndOfBlock | 
| Tim Peters | 4efb6e9 | 2001-06-29 23:51:08 +0000 | [diff] [blame] | 910 |  | 
| Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 911 | def getblock(lines): | 
 | 912 |     """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] | 913 |     blockfinder = BlockFinder() | 
| Tim Peters | 4efb6e9 | 2001-06-29 23:51:08 +0000 | [diff] [blame] | 914 |     try: | 
| Trent Nelson | 428de65 | 2008-03-18 22:41:35 +0000 | [diff] [blame] | 915 |         tokens = tokenize.generate_tokens(iter(lines).__next__) | 
 | 916 |         for _token in tokens: | 
 | 917 |             blockfinder.tokeneater(*_token) | 
| Armin Rigo | dd5c023 | 2005-09-25 11:45:45 +0000 | [diff] [blame] | 918 |     except (EndOfBlock, IndentationError): | 
 | 919 |         pass | 
 | 920 |     return lines[:blockfinder.last] | 
| Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 921 |  | 
 | 922 | def getsourcelines(object): | 
 | 923 |     """Return a list of source lines and starting line number for an object. | 
 | 924 |  | 
 | 925 |     The argument may be a module, class, method, function, traceback, frame, | 
 | 926 |     or code object.  The source code is returned as a list of the lines | 
 | 927 |     corresponding to the object and the line number indicates where in the | 
| Andrew Svetlov | f7a17b4 | 2012-12-25 16:47:37 +0200 | [diff] [blame] | 928 |     original source file the first line of code was found.  An OSError is | 
| Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 929 |     raised if the source code cannot be retrieved.""" | 
| Yury Selivanov | 081bbf6 | 2014-09-26 17:34:54 -0400 | [diff] [blame] | 930 |     object = unwrap(object) | 
| Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 931 |     lines, lnum = findsource(object) | 
 | 932 |  | 
| Meador Inge | 5b718d7 | 2015-07-23 22:49:37 -0500 | [diff] [blame] | 933 |     if ismodule(object): | 
 | 934 |         return lines, 0 | 
 | 935 |     else: | 
 | 936 |         return getblock(lines[lnum:]), lnum + 1 | 
| Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 937 |  | 
 | 938 | def getsource(object): | 
 | 939 |     """Return the text of the source code for an object. | 
 | 940 |  | 
 | 941 |     The argument may be a module, class, method, function, traceback, frame, | 
 | 942 |     or code object.  The source code is returned as a single string.  An | 
| Andrew Svetlov | f7a17b4 | 2012-12-25 16:47:37 +0200 | [diff] [blame] | 943 |     OSError is raised if the source code cannot be retrieved.""" | 
| Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 944 |     lines, lnum = getsourcelines(object) | 
| Neal Norwitz | 9d72bb4 | 2007-04-17 08:48:32 +0000 | [diff] [blame] | 945 |     return ''.join(lines) | 
| Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 946 |  | 
 | 947 | # --------------------------------------------------- class tree extraction | 
 | 948 | def walktree(classes, children, parent): | 
 | 949 |     """Recursive helper function for getclasstree().""" | 
 | 950 |     results = [] | 
| Raymond Hettinger | a1a992c | 2005-03-11 06:46:45 +0000 | [diff] [blame] | 951 |     classes.sort(key=attrgetter('__module__', '__name__')) | 
| Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 952 |     for c in classes: | 
 | 953 |         results.append((c, c.__bases__)) | 
| Raymond Hettinger | 54f0222 | 2002-06-01 14:18:47 +0000 | [diff] [blame] | 954 |         if c in children: | 
| Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 955 |             results.append(walktree(children[c], children, c)) | 
 | 956 |     return results | 
 | 957 |  | 
| Georg Brandl | 5ce83a0 | 2009-06-01 17:23:51 +0000 | [diff] [blame] | 958 | def getclasstree(classes, unique=False): | 
| Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 959 |     """Arrange the given list of classes into a hierarchy of nested lists. | 
 | 960 |  | 
 | 961 |     Where a nested list appears, it contains classes derived from the class | 
 | 962 |     whose entry immediately precedes the list.  Each entry is a 2-tuple | 
 | 963 |     containing a class and a tuple of its base classes.  If the 'unique' | 
 | 964 |     argument is true, exactly one entry appears in the returned structure | 
 | 965 |     for each class in the given list.  Otherwise, classes using multiple | 
 | 966 |     inheritance and their descendants will appear multiple times.""" | 
 | 967 |     children = {} | 
 | 968 |     roots = [] | 
 | 969 |     for c in classes: | 
 | 970 |         if c.__bases__: | 
 | 971 |             for parent in c.__bases__: | 
| Raymond Hettinger | 54f0222 | 2002-06-01 14:18:47 +0000 | [diff] [blame] | 972 |                 if not parent in children: | 
| Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 973 |                     children[parent] = [] | 
| Serhiy Storchaka | 362c1b5 | 2013-09-05 17:14:32 +0300 | [diff] [blame] | 974 |                 if c not in children[parent]: | 
 | 975 |                     children[parent].append(c) | 
| Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 976 |                 if unique and parent in classes: break | 
 | 977 |         elif c not in roots: | 
 | 978 |             roots.append(c) | 
| Raymond Hettinger | e0d4972 | 2002-06-02 18:55:56 +0000 | [diff] [blame] | 979 |     for parent in children: | 
| Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 980 |         if parent not in classes: | 
 | 981 |             roots.append(parent) | 
 | 982 |     return walktree(roots, children, None) | 
 | 983 |  | 
 | 984 | # ------------------------------------------------ argument list extraction | 
| Christian Heimes | 25bb783 | 2008-01-11 16:17:00 +0000 | [diff] [blame] | 985 | Arguments = namedtuple('Arguments', 'args, varargs, varkw') | 
 | 986 |  | 
| Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 987 | def getargs(co): | 
 | 988 |     """Get information about the arguments accepted by a code object. | 
 | 989 |  | 
| Guido van Rossum | 2e65f89 | 2007-02-28 22:03:49 +0000 | [diff] [blame] | 990 |     Three things are returned: (args, varargs, varkw), where | 
| Georg Brandl | c1c4bf8 | 2010-10-15 16:07:41 +0000 | [diff] [blame] | 991 |     'args' is the list of argument names. Keyword-only arguments are | 
 | 992 |     appended. 'varargs' and 'varkw' are the names of the * and ** | 
 | 993 |     arguments or None.""" | 
| Guido van Rossum | 2e65f89 | 2007-02-28 22:03:49 +0000 | [diff] [blame] | 994 |     args, varargs, kwonlyargs, varkw = _getfullargs(co) | 
| Christian Heimes | 25bb783 | 2008-01-11 16:17:00 +0000 | [diff] [blame] | 995 |     return Arguments(args + kwonlyargs, varargs, varkw) | 
| Guido van Rossum | 2e65f89 | 2007-02-28 22:03:49 +0000 | [diff] [blame] | 996 |  | 
 | 997 | def _getfullargs(co): | 
 | 998 |     """Get information about the arguments accepted by a code object. | 
 | 999 |  | 
 | 1000 |     Four things are returned: (args, varargs, kwonlyargs, varkw), where | 
| Georg Brandl | c1c4bf8 | 2010-10-15 16:07:41 +0000 | [diff] [blame] | 1001 |     'args' and 'kwonlyargs' are lists of argument names, and 'varargs' | 
 | 1002 |     and 'varkw' are the names of the * and ** arguments or None.""" | 
| Jeremy Hylton | 6496788 | 2003-06-27 18:14:39 +0000 | [diff] [blame] | 1003 |  | 
 | 1004 |     if not iscode(co): | 
| Benjamin Peterson | 4ac9ce4 | 2009-10-04 14:49:41 +0000 | [diff] [blame] | 1005 |         raise TypeError('{!r} is not a code object'.format(co)) | 
| Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 1006 |  | 
| Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 1007 |     nargs = co.co_argcount | 
 | 1008 |     names = co.co_varnames | 
| Guido van Rossum | 2e65f89 | 2007-02-28 22:03:49 +0000 | [diff] [blame] | 1009 |     nkwargs = co.co_kwonlyargcount | 
| Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 1010 |     args = list(names[:nargs]) | 
| Guido van Rossum | 2e65f89 | 2007-02-28 22:03:49 +0000 | [diff] [blame] | 1011 |     kwonlyargs = list(names[nargs:nargs+nkwargs]) | 
| Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 1012 |     step = 0 | 
 | 1013 |  | 
| Guido van Rossum | 2e65f89 | 2007-02-28 22:03:49 +0000 | [diff] [blame] | 1014 |     nargs += nkwargs | 
| Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 1015 |     varargs = None | 
 | 1016 |     if co.co_flags & CO_VARARGS: | 
 | 1017 |         varargs = co.co_varnames[nargs] | 
 | 1018 |         nargs = nargs + 1 | 
 | 1019 |     varkw = None | 
 | 1020 |     if co.co_flags & CO_VARKEYWORDS: | 
 | 1021 |         varkw = co.co_varnames[nargs] | 
| Guido van Rossum | 2e65f89 | 2007-02-28 22:03:49 +0000 | [diff] [blame] | 1022 |     return args, varargs, kwonlyargs, varkw | 
| Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 1023 |  | 
| Christian Heimes | 25bb783 | 2008-01-11 16:17:00 +0000 | [diff] [blame] | 1024 |  | 
 | 1025 | ArgSpec = namedtuple('ArgSpec', 'args varargs keywords defaults') | 
 | 1026 |  | 
| Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 1027 | def getargspec(func): | 
 | 1028 |     """Get the names and default values of a function's arguments. | 
 | 1029 |  | 
| Guido van Rossum | e82881c | 2014-07-15 12:29:11 -0700 | [diff] [blame] | 1030 |     A tuple of four things is returned: (args, varargs, keywords, defaults). | 
 | 1031 |     'args' is a list of the argument names, including keyword-only argument names. | 
 | 1032 |     'varargs' and 'keywords' are the names of the * and ** arguments or None. | 
| Jeremy Hylton | 6496788 | 2003-06-27 18:14:39 +0000 | [diff] [blame] | 1033 |     '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] | 1034 |  | 
| Yury Selivanov | 0cf3ed6 | 2014-04-01 10:17:08 -0400 | [diff] [blame] | 1035 |     Use the getfullargspec() API for Python 3 code, as annotations | 
| Guido van Rossum | 2e65f89 | 2007-02-28 22:03:49 +0000 | [diff] [blame] | 1036 |     and keyword arguments are supported. getargspec() will raise ValueError | 
 | 1037 |     if the func has either annotations or keyword arguments. | 
 | 1038 |     """ | 
| Yury Selivanov | 3cfec2e | 2015-05-22 11:38:38 -0400 | [diff] [blame] | 1039 |     warnings.warn("inspect.getargspec() is deprecated, " | 
| Yury Selivanov | c8386f7 | 2015-05-22 16:09:44 -0400 | [diff] [blame] | 1040 |                   "use inspect.signature() instead", DeprecationWarning, | 
 | 1041 |                   stacklevel=2) | 
| Guido van Rossum | 2e65f89 | 2007-02-28 22:03:49 +0000 | [diff] [blame] | 1042 |     args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults, ann = \ | 
 | 1043 |         getfullargspec(func) | 
 | 1044 |     if kwonlyargs or ann: | 
| Collin Winter | ce36ad8 | 2007-08-30 01:19:48 +0000 | [diff] [blame] | 1045 |         raise ValueError("Function has keyword-only arguments or annotations" | 
 | 1046 |                          ", use getfullargspec() API which can support them") | 
| Christian Heimes | 25bb783 | 2008-01-11 16:17:00 +0000 | [diff] [blame] | 1047 |     return ArgSpec(args, varargs, varkw, defaults) | 
 | 1048 |  | 
 | 1049 | FullArgSpec = namedtuple('FullArgSpec', | 
| Benjamin Peterson | 3d4ca74 | 2008-11-12 21:39:01 +0000 | [diff] [blame] | 1050 |     'args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults, annotations') | 
| Guido van Rossum | 2e65f89 | 2007-02-28 22:03:49 +0000 | [diff] [blame] | 1051 |  | 
 | 1052 | def getfullargspec(func): | 
| Yury Selivanov | d82eddc | 2014-01-29 11:24:39 -0500 | [diff] [blame] | 1053 |     """Get the names and default values of a callable object's arguments. | 
| Guido van Rossum | 2e65f89 | 2007-02-28 22:03:49 +0000 | [diff] [blame] | 1054 |  | 
| Brett Cannon | 504d885 | 2007-09-07 02:12:14 +0000 | [diff] [blame] | 1055 |     A tuple of seven things is returned: | 
 | 1056 |     (args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults annotations). | 
| Georg Brandl | c1c4bf8 | 2010-10-15 16:07:41 +0000 | [diff] [blame] | 1057 |     'args' is a list of the argument names. | 
| Guido van Rossum | 2e65f89 | 2007-02-28 22:03:49 +0000 | [diff] [blame] | 1058 |     'varargs' and 'varkw' are the names of the * and ** arguments or None. | 
 | 1059 |     'defaults' is an n-tuple of the default values of the last n arguments. | 
 | 1060 |     'kwonlyargs' is a list of keyword-only argument names. | 
 | 1061 |     'kwonlydefaults' is a dictionary mapping names from kwonlyargs to defaults. | 
 | 1062 |     'annotations' is a dictionary mapping argument names to annotations. | 
| Guido van Rossum | a8add0e | 2007-05-14 22:03:55 +0000 | [diff] [blame] | 1063 |  | 
| Guido van Rossum | 2e65f89 | 2007-02-28 22:03:49 +0000 | [diff] [blame] | 1064 |     The first four items in the tuple correspond to getargspec(). | 
| Yury Selivanov | 3cfec2e | 2015-05-22 11:38:38 -0400 | [diff] [blame] | 1065 |  | 
 | 1066 |     This function is deprecated, use inspect.signature() instead. | 
| Jeremy Hylton | 6496788 | 2003-06-27 18:14:39 +0000 | [diff] [blame] | 1067 |     """ | 
 | 1068 |  | 
| Yury Selivanov | 57d240e | 2014-02-19 16:27:23 -0500 | [diff] [blame] | 1069 |     try: | 
 | 1070 |         # Re: `skip_bound_arg=False` | 
 | 1071 |         # | 
| Yury Selivanov | d82eddc | 2014-01-29 11:24:39 -0500 | [diff] [blame] | 1072 |         # There is a notable difference in behaviour between getfullargspec | 
 | 1073 |         # and Signature: the former always returns 'self' parameter for bound | 
 | 1074 |         # methods, whereas the Signature always shows the actual calling | 
 | 1075 |         # signature of the passed object. | 
 | 1076 |         # | 
 | 1077 |         # To simulate this behaviour, we "unbind" bound methods, to trick | 
 | 1078 |         # inspect.signature to always return their first parameter ("self", | 
 | 1079 |         # usually) | 
| Yury Selivanov | d82eddc | 2014-01-29 11:24:39 -0500 | [diff] [blame] | 1080 |  | 
| Yury Selivanov | 57d240e | 2014-02-19 16:27:23 -0500 | [diff] [blame] | 1081 |         # Re: `follow_wrapper_chains=False` | 
 | 1082 |         # | 
 | 1083 |         # getfullargspec() historically ignored __wrapped__ attributes, | 
 | 1084 |         # so we ensure that remains the case in 3.3+ | 
| Yury Selivanov | d82eddc | 2014-01-29 11:24:39 -0500 | [diff] [blame] | 1085 |  | 
| Yury Selivanov | 5a23bd0 | 2014-03-29 13:47:11 -0400 | [diff] [blame] | 1086 |         sig = _signature_from_callable(func, | 
 | 1087 |                                        follow_wrapper_chains=False, | 
 | 1088 |                                        skip_bound_arg=False, | 
 | 1089 |                                        sigcls=Signature) | 
| Yury Selivanov | d82eddc | 2014-01-29 11:24:39 -0500 | [diff] [blame] | 1090 |     except Exception as ex: | 
 | 1091 |         # Most of the times 'signature' will raise ValueError. | 
 | 1092 |         # But, it can also raise AttributeError, and, maybe something | 
 | 1093 |         # else. So to be fully backwards compatible, we catch all | 
 | 1094 |         # possible exceptions here, and reraise a TypeError. | 
 | 1095 |         raise TypeError('unsupported callable') from ex | 
 | 1096 |  | 
 | 1097 |     args = [] | 
 | 1098 |     varargs = None | 
 | 1099 |     varkw = None | 
 | 1100 |     kwonlyargs = [] | 
 | 1101 |     defaults = () | 
 | 1102 |     annotations = {} | 
 | 1103 |     defaults = () | 
 | 1104 |     kwdefaults = {} | 
 | 1105 |  | 
 | 1106 |     if sig.return_annotation is not sig.empty: | 
 | 1107 |         annotations['return'] = sig.return_annotation | 
 | 1108 |  | 
 | 1109 |     for param in sig.parameters.values(): | 
 | 1110 |         kind = param.kind | 
 | 1111 |         name = param.name | 
 | 1112 |  | 
 | 1113 |         if kind is _POSITIONAL_ONLY: | 
 | 1114 |             args.append(name) | 
 | 1115 |         elif kind is _POSITIONAL_OR_KEYWORD: | 
 | 1116 |             args.append(name) | 
 | 1117 |             if param.default is not param.empty: | 
 | 1118 |                 defaults += (param.default,) | 
 | 1119 |         elif kind is _VAR_POSITIONAL: | 
 | 1120 |             varargs = name | 
 | 1121 |         elif kind is _KEYWORD_ONLY: | 
 | 1122 |             kwonlyargs.append(name) | 
 | 1123 |             if param.default is not param.empty: | 
 | 1124 |                 kwdefaults[name] = param.default | 
 | 1125 |         elif kind is _VAR_KEYWORD: | 
 | 1126 |             varkw = name | 
 | 1127 |  | 
 | 1128 |         if param.annotation is not param.empty: | 
 | 1129 |             annotations[name] = param.annotation | 
 | 1130 |  | 
 | 1131 |     if not kwdefaults: | 
 | 1132 |         # compatibility with 'func.__kwdefaults__' | 
 | 1133 |         kwdefaults = None | 
 | 1134 |  | 
 | 1135 |     if not defaults: | 
 | 1136 |         # compatibility with 'func.__defaults__' | 
 | 1137 |         defaults = None | 
 | 1138 |  | 
| Yury Selivanov | d82eddc | 2014-01-29 11:24:39 -0500 | [diff] [blame] | 1139 |     return FullArgSpec(args, varargs, varkw, defaults, | 
 | 1140 |                        kwonlyargs, kwdefaults, annotations) | 
 | 1141 |  | 
| Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 1142 |  | 
| Christian Heimes | 25bb783 | 2008-01-11 16:17:00 +0000 | [diff] [blame] | 1143 | ArgInfo = namedtuple('ArgInfo', 'args varargs keywords locals') | 
 | 1144 |  | 
| Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 1145 | def getargvalues(frame): | 
 | 1146 |     """Get information about arguments passed into a particular frame. | 
 | 1147 |  | 
 | 1148 |     A tuple of four things is returned: (args, varargs, varkw, locals). | 
| Georg Brandl | c1c4bf8 | 2010-10-15 16:07:41 +0000 | [diff] [blame] | 1149 |     'args' is a list of the argument names. | 
| Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 1150 |     'varargs' and 'varkw' are the names of the * and ** arguments or None. | 
 | 1151 |     'locals' is the locals dictionary of the given frame.""" | 
 | 1152 |     args, varargs, varkw = getargs(frame.f_code) | 
| Benjamin Peterson | 1a6e0d0 | 2008-10-25 15:49:17 +0000 | [diff] [blame] | 1153 |     return ArgInfo(args, varargs, varkw, frame.f_locals) | 
| Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 1154 |  | 
| Guido van Rossum | 2e65f89 | 2007-02-28 22:03:49 +0000 | [diff] [blame] | 1155 | def formatannotation(annotation, base_module=None): | 
 | 1156 |     if isinstance(annotation, type): | 
| Georg Brandl | 1a3284e | 2007-12-02 09:40:06 +0000 | [diff] [blame] | 1157 |         if annotation.__module__ in ('builtins', base_module): | 
| Serhiy Storchaka | 521e586 | 2014-07-22 15:00:37 +0300 | [diff] [blame] | 1158 |             return annotation.__qualname__ | 
 | 1159 |         return annotation.__module__+'.'+annotation.__qualname__ | 
| Guido van Rossum | 2e65f89 | 2007-02-28 22:03:49 +0000 | [diff] [blame] | 1160 |     return repr(annotation) | 
| Guido van Rossum | a8add0e | 2007-05-14 22:03:55 +0000 | [diff] [blame] | 1161 |  | 
| Guido van Rossum | 2e65f89 | 2007-02-28 22:03:49 +0000 | [diff] [blame] | 1162 | def formatannotationrelativeto(object): | 
| Guido van Rossum | a8add0e | 2007-05-14 22:03:55 +0000 | [diff] [blame] | 1163 |     module = getattr(object, '__module__', None) | 
 | 1164 |     def _formatannotation(annotation): | 
 | 1165 |         return formatannotation(annotation, module) | 
 | 1166 |     return _formatannotation | 
| Guido van Rossum | 2e65f89 | 2007-02-28 22:03:49 +0000 | [diff] [blame] | 1167 |  | 
| Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 1168 | def formatargspec(args, varargs=None, varkw=None, defaults=None, | 
| Guido van Rossum | 2e65f89 | 2007-02-28 22:03:49 +0000 | [diff] [blame] | 1169 |                   kwonlyargs=(), kwonlydefaults={}, annotations={}, | 
| Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 1170 |                   formatarg=str, | 
 | 1171 |                   formatvarargs=lambda name: '*' + name, | 
 | 1172 |                   formatvarkw=lambda name: '**' + name, | 
 | 1173 |                   formatvalue=lambda value: '=' + repr(value), | 
| Guido van Rossum | 2e65f89 | 2007-02-28 22:03:49 +0000 | [diff] [blame] | 1174 |                   formatreturns=lambda text: ' -> ' + text, | 
| Georg Brandl | c1c4bf8 | 2010-10-15 16:07:41 +0000 | [diff] [blame] | 1175 |                   formatannotation=formatannotation): | 
| Guido van Rossum | a8add0e | 2007-05-14 22:03:55 +0000 | [diff] [blame] | 1176 |     """Format an argument spec from the values returned by getargspec | 
| Guido van Rossum | 2e65f89 | 2007-02-28 22:03:49 +0000 | [diff] [blame] | 1177 |     or getfullargspec. | 
| Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 1178 |  | 
| Guido van Rossum | 2e65f89 | 2007-02-28 22:03:49 +0000 | [diff] [blame] | 1179 |     The first seven arguments are (args, varargs, varkw, defaults, | 
 | 1180 |     kwonlyargs, kwonlydefaults, annotations).  The other five arguments | 
 | 1181 |     are the corresponding optional formatting functions that are called to | 
 | 1182 |     turn names and values into strings.  The last argument is an optional | 
 | 1183 |     function to format the sequence of arguments.""" | 
 | 1184 |     def formatargandannotation(arg): | 
 | 1185 |         result = formatarg(arg) | 
 | 1186 |         if arg in annotations: | 
 | 1187 |             result += ': ' + formatannotation(annotations[arg]) | 
 | 1188 |         return result | 
| Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 1189 |     specs = [] | 
 | 1190 |     if defaults: | 
 | 1191 |         firstdefault = len(args) - len(defaults) | 
| Benjamin Peterson | b58dda7 | 2009-01-18 22:27:04 +0000 | [diff] [blame] | 1192 |     for i, arg in enumerate(args): | 
| Georg Brandl | c1c4bf8 | 2010-10-15 16:07:41 +0000 | [diff] [blame] | 1193 |         spec = formatargandannotation(arg) | 
| Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 1194 |         if defaults and i >= firstdefault: | 
 | 1195 |             spec = spec + formatvalue(defaults[i - firstdefault]) | 
 | 1196 |         specs.append(spec) | 
| Raymond Hettinger | 936654b | 2002-06-01 03:06:31 +0000 | [diff] [blame] | 1197 |     if varargs is not None: | 
| Guido van Rossum | 2e65f89 | 2007-02-28 22:03:49 +0000 | [diff] [blame] | 1198 |         specs.append(formatvarargs(formatargandannotation(varargs))) | 
 | 1199 |     else: | 
 | 1200 |         if kwonlyargs: | 
 | 1201 |             specs.append('*') | 
 | 1202 |     if kwonlyargs: | 
 | 1203 |         for kwonlyarg in kwonlyargs: | 
 | 1204 |             spec = formatargandannotation(kwonlyarg) | 
| Benjamin Peterson | 9953a8d | 2009-01-17 04:15:01 +0000 | [diff] [blame] | 1205 |             if kwonlydefaults and kwonlyarg in kwonlydefaults: | 
| Guido van Rossum | 2e65f89 | 2007-02-28 22:03:49 +0000 | [diff] [blame] | 1206 |                 spec += formatvalue(kwonlydefaults[kwonlyarg]) | 
 | 1207 |             specs.append(spec) | 
| Raymond Hettinger | 936654b | 2002-06-01 03:06:31 +0000 | [diff] [blame] | 1208 |     if varkw is not None: | 
| Guido van Rossum | 2e65f89 | 2007-02-28 22:03:49 +0000 | [diff] [blame] | 1209 |         specs.append(formatvarkw(formatargandannotation(varkw))) | 
| Neal Norwitz | 9d72bb4 | 2007-04-17 08:48:32 +0000 | [diff] [blame] | 1210 |     result = '(' + ', '.join(specs) + ')' | 
| Guido van Rossum | 2e65f89 | 2007-02-28 22:03:49 +0000 | [diff] [blame] | 1211 |     if 'return' in annotations: | 
 | 1212 |         result += formatreturns(formatannotation(annotations['return'])) | 
 | 1213 |     return result | 
| Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 1214 |  | 
 | 1215 | def formatargvalues(args, varargs, varkw, locals, | 
 | 1216 |                     formatarg=str, | 
 | 1217 |                     formatvarargs=lambda name: '*' + name, | 
 | 1218 |                     formatvarkw=lambda name: '**' + name, | 
| Georg Brandl | c1c4bf8 | 2010-10-15 16:07:41 +0000 | [diff] [blame] | 1219 |                     formatvalue=lambda value: '=' + repr(value)): | 
| Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 1220 |     """Format an argument spec from the 4 values returned by getargvalues. | 
 | 1221 |  | 
 | 1222 |     The first four arguments are (args, varargs, varkw, locals).  The | 
 | 1223 |     next four arguments are the corresponding optional formatting functions | 
 | 1224 |     that are called to turn names and values into strings.  The ninth | 
 | 1225 |     argument is an optional function to format the sequence of arguments.""" | 
 | 1226 |     def convert(name, locals=locals, | 
 | 1227 |                 formatarg=formatarg, formatvalue=formatvalue): | 
 | 1228 |         return formatarg(name) + formatvalue(locals[name]) | 
 | 1229 |     specs = [] | 
 | 1230 |     for i in range(len(args)): | 
| Georg Brandl | c1c4bf8 | 2010-10-15 16:07:41 +0000 | [diff] [blame] | 1231 |         specs.append(convert(args[i])) | 
| Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 1232 |     if varargs: | 
 | 1233 |         specs.append(formatvarargs(varargs) + formatvalue(locals[varargs])) | 
 | 1234 |     if varkw: | 
 | 1235 |         specs.append(formatvarkw(varkw) + formatvalue(locals[varkw])) | 
| Neal Norwitz | 9d72bb4 | 2007-04-17 08:48:32 +0000 | [diff] [blame] | 1236 |     return '(' + ', '.join(specs) + ')' | 
| Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 1237 |  | 
| Benjamin Peterson | e109c70 | 2011-06-24 09:37:26 -0500 | [diff] [blame] | 1238 | def _missing_arguments(f_name, argnames, pos, values): | 
 | 1239 |     names = [repr(name) for name in argnames if name not in values] | 
 | 1240 |     missing = len(names) | 
 | 1241 |     if missing == 1: | 
 | 1242 |         s = names[0] | 
 | 1243 |     elif missing == 2: | 
 | 1244 |         s = "{} and {}".format(*names) | 
 | 1245 |     else: | 
| Yury Selivanov | dccfa13 | 2014-03-27 18:42:52 -0400 | [diff] [blame] | 1246 |         tail = ", {} and {}".format(*names[-2:]) | 
| Benjamin Peterson | e109c70 | 2011-06-24 09:37:26 -0500 | [diff] [blame] | 1247 |         del names[-2:] | 
 | 1248 |         s = ", ".join(names) + tail | 
 | 1249 |     raise TypeError("%s() missing %i required %s argument%s: %s" % | 
 | 1250 |                     (f_name, missing, | 
 | 1251 |                       "positional" if pos else "keyword-only", | 
 | 1252 |                       "" if missing == 1 else "s", s)) | 
 | 1253 |  | 
 | 1254 | def _too_many(f_name, args, kwonly, varargs, defcount, given, values): | 
| Benjamin Peterson | b204a42 | 2011-06-05 22:04:07 -0500 | [diff] [blame] | 1255 |     atleast = len(args) - defcount | 
| Benjamin Peterson | b204a42 | 2011-06-05 22:04:07 -0500 | [diff] [blame] | 1256 |     kwonly_given = len([arg for arg in kwonly if arg in values]) | 
 | 1257 |     if varargs: | 
 | 1258 |         plural = atleast != 1 | 
 | 1259 |         sig = "at least %d" % (atleast,) | 
 | 1260 |     elif defcount: | 
 | 1261 |         plural = True | 
 | 1262 |         sig = "from %d to %d" % (atleast, len(args)) | 
 | 1263 |     else: | 
 | 1264 |         plural = len(args) != 1 | 
 | 1265 |         sig = str(len(args)) | 
 | 1266 |     kwonly_sig = "" | 
 | 1267 |     if kwonly_given: | 
 | 1268 |         msg = " positional argument%s (and %d keyword-only argument%s)" | 
 | 1269 |         kwonly_sig = (msg % ("s" if given != 1 else "", kwonly_given, | 
 | 1270 |                              "s" if kwonly_given != 1 else "")) | 
 | 1271 |     raise TypeError("%s() takes %s positional argument%s but %d%s %s given" % | 
 | 1272 |             (f_name, sig, "s" if plural else "", given, kwonly_sig, | 
 | 1273 |              "was" if given == 1 and not kwonly_given else "were")) | 
 | 1274 |  | 
| Benjamin Peterson | 3e6ab17 | 2014-01-02 12:24:08 -0600 | [diff] [blame] | 1275 | def getcallargs(*func_and_positional, **named): | 
| Benjamin Peterson | 25cd7eb | 2010-03-30 18:42:32 +0000 | [diff] [blame] | 1276 |     """Get the mapping of arguments to values. | 
 | 1277 |  | 
 | 1278 |     A dict is returned, with keys the function argument names (including the | 
 | 1279 |     names of the * and ** arguments, if any), and values the respective bound | 
 | 1280 |     values from 'positional' and 'named'.""" | 
| Benjamin Peterson | 3e6ab17 | 2014-01-02 12:24:08 -0600 | [diff] [blame] | 1281 |     func = func_and_positional[0] | 
 | 1282 |     positional = func_and_positional[1:] | 
| Benjamin Peterson | 25cd7eb | 2010-03-30 18:42:32 +0000 | [diff] [blame] | 1283 |     spec = getfullargspec(func) | 
 | 1284 |     args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults, ann = spec | 
 | 1285 |     f_name = func.__name__ | 
 | 1286 |     arg2value = {} | 
 | 1287 |  | 
| Benjamin Peterson | b204a42 | 2011-06-05 22:04:07 -0500 | [diff] [blame] | 1288 |  | 
| Benjamin Peterson | 25cd7eb | 2010-03-30 18:42:32 +0000 | [diff] [blame] | 1289 |     if ismethod(func) and func.__self__ is not None: | 
 | 1290 |         # implicit 'self' (or 'cls' for classmethods) argument | 
 | 1291 |         positional = (func.__self__,) + positional | 
 | 1292 |     num_pos = len(positional) | 
| Benjamin Peterson | 25cd7eb | 2010-03-30 18:42:32 +0000 | [diff] [blame] | 1293 |     num_args = len(args) | 
 | 1294 |     num_defaults = len(defaults) if defaults else 0 | 
| Benjamin Peterson | 25cd7eb | 2010-03-30 18:42:32 +0000 | [diff] [blame] | 1295 |  | 
| Benjamin Peterson | b204a42 | 2011-06-05 22:04:07 -0500 | [diff] [blame] | 1296 |     n = min(num_pos, num_args) | 
 | 1297 |     for i in range(n): | 
 | 1298 |         arg2value[args[i]] = positional[i] | 
 | 1299 |     if varargs: | 
 | 1300 |         arg2value[varargs] = tuple(positional[n:]) | 
 | 1301 |     possible_kwargs = set(args + kwonlyargs) | 
| Benjamin Peterson | 25cd7eb | 2010-03-30 18:42:32 +0000 | [diff] [blame] | 1302 |     if varkw: | 
| Benjamin Peterson | b204a42 | 2011-06-05 22:04:07 -0500 | [diff] [blame] | 1303 |         arg2value[varkw] = {} | 
 | 1304 |     for kw, value in named.items(): | 
 | 1305 |         if kw not in possible_kwargs: | 
 | 1306 |             if not varkw: | 
 | 1307 |                 raise TypeError("%s() got an unexpected keyword argument %r" % | 
 | 1308 |                                 (f_name, kw)) | 
 | 1309 |             arg2value[varkw][kw] = value | 
 | 1310 |             continue | 
 | 1311 |         if kw in arg2value: | 
 | 1312 |             raise TypeError("%s() got multiple values for argument %r" % | 
 | 1313 |                             (f_name, kw)) | 
 | 1314 |         arg2value[kw] = value | 
 | 1315 |     if num_pos > num_args and not varargs: | 
| Benjamin Peterson | e109c70 | 2011-06-24 09:37:26 -0500 | [diff] [blame] | 1316 |         _too_many(f_name, args, kwonlyargs, varargs, num_defaults, | 
 | 1317 |                    num_pos, arg2value) | 
| Benjamin Peterson | b204a42 | 2011-06-05 22:04:07 -0500 | [diff] [blame] | 1318 |     if num_pos < num_args: | 
| Benjamin Peterson | e109c70 | 2011-06-24 09:37:26 -0500 | [diff] [blame] | 1319 |         req = args[:num_args - num_defaults] | 
 | 1320 |         for arg in req: | 
| Benjamin Peterson | b204a42 | 2011-06-05 22:04:07 -0500 | [diff] [blame] | 1321 |             if arg not in arg2value: | 
| Benjamin Peterson | e109c70 | 2011-06-24 09:37:26 -0500 | [diff] [blame] | 1322 |                 _missing_arguments(f_name, req, True, arg2value) | 
| Benjamin Peterson | b204a42 | 2011-06-05 22:04:07 -0500 | [diff] [blame] | 1323 |         for i, arg in enumerate(args[num_args - num_defaults:]): | 
 | 1324 |             if arg not in arg2value: | 
 | 1325 |                 arg2value[arg] = defaults[i] | 
| Benjamin Peterson | e109c70 | 2011-06-24 09:37:26 -0500 | [diff] [blame] | 1326 |     missing = 0 | 
| Benjamin Peterson | b204a42 | 2011-06-05 22:04:07 -0500 | [diff] [blame] | 1327 |     for kwarg in kwonlyargs: | 
 | 1328 |         if kwarg not in arg2value: | 
| Yury Selivanov | 875df20 | 2014-03-27 18:23:03 -0400 | [diff] [blame] | 1329 |             if kwonlydefaults and kwarg in kwonlydefaults: | 
| Benjamin Peterson | e109c70 | 2011-06-24 09:37:26 -0500 | [diff] [blame] | 1330 |                 arg2value[kwarg] = kwonlydefaults[kwarg] | 
 | 1331 |             else: | 
 | 1332 |                 missing += 1 | 
 | 1333 |     if missing: | 
 | 1334 |         _missing_arguments(f_name, kwonlyargs, False, arg2value) | 
| Benjamin Peterson | 25cd7eb | 2010-03-30 18:42:32 +0000 | [diff] [blame] | 1335 |     return arg2value | 
 | 1336 |  | 
| Nick Coghlan | 2f92e54 | 2012-06-23 19:39:55 +1000 | [diff] [blame] | 1337 | ClosureVars = namedtuple('ClosureVars', 'nonlocals globals builtins unbound') | 
 | 1338 |  | 
 | 1339 | def getclosurevars(func): | 
 | 1340 |     """ | 
 | 1341 |     Get the mapping of free variables to their current values. | 
 | 1342 |  | 
| Meador Inge | 8fda359 | 2012-07-19 21:33:21 -0500 | [diff] [blame] | 1343 |     Returns a named tuple of dicts mapping the current nonlocal, global | 
| Nick Coghlan | 2f92e54 | 2012-06-23 19:39:55 +1000 | [diff] [blame] | 1344 |     and builtin references as seen by the body of the function. A final | 
 | 1345 |     set of unbound names that could not be resolved is also provided. | 
 | 1346 |     """ | 
 | 1347 |  | 
 | 1348 |     if ismethod(func): | 
 | 1349 |         func = func.__func__ | 
 | 1350 |  | 
 | 1351 |     if not isfunction(func): | 
 | 1352 |         raise TypeError("'{!r}' is not a Python function".format(func)) | 
 | 1353 |  | 
 | 1354 |     code = func.__code__ | 
 | 1355 |     # Nonlocal references are named in co_freevars and resolved | 
 | 1356 |     # by looking them up in __closure__ by positional index | 
 | 1357 |     if func.__closure__ is None: | 
 | 1358 |         nonlocal_vars = {} | 
 | 1359 |     else: | 
 | 1360 |         nonlocal_vars = { | 
 | 1361 |             var : cell.cell_contents | 
 | 1362 |             for var, cell in zip(code.co_freevars, func.__closure__) | 
 | 1363 |        } | 
 | 1364 |  | 
 | 1365 |     # Global and builtin references are named in co_names and resolved | 
 | 1366 |     # by looking them up in __globals__ or __builtins__ | 
 | 1367 |     global_ns = func.__globals__ | 
 | 1368 |     builtin_ns = global_ns.get("__builtins__", builtins.__dict__) | 
 | 1369 |     if ismodule(builtin_ns): | 
 | 1370 |         builtin_ns = builtin_ns.__dict__ | 
 | 1371 |     global_vars = {} | 
 | 1372 |     builtin_vars = {} | 
 | 1373 |     unbound_names = set() | 
 | 1374 |     for name in code.co_names: | 
 | 1375 |         if name in ("None", "True", "False"): | 
 | 1376 |             # Because these used to be builtins instead of keywords, they | 
 | 1377 |             # may still show up as name references. We ignore them. | 
 | 1378 |             continue | 
 | 1379 |         try: | 
 | 1380 |             global_vars[name] = global_ns[name] | 
 | 1381 |         except KeyError: | 
 | 1382 |             try: | 
 | 1383 |                 builtin_vars[name] = builtin_ns[name] | 
 | 1384 |             except KeyError: | 
 | 1385 |                 unbound_names.add(name) | 
 | 1386 |  | 
 | 1387 |     return ClosureVars(nonlocal_vars, global_vars, | 
 | 1388 |                        builtin_vars, unbound_names) | 
 | 1389 |  | 
| Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 1390 | # -------------------------------------------------- stack frame extraction | 
| Christian Heimes | 25bb783 | 2008-01-11 16:17:00 +0000 | [diff] [blame] | 1391 |  | 
 | 1392 | Traceback = namedtuple('Traceback', 'filename lineno function code_context index') | 
 | 1393 |  | 
| Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 1394 | def getframeinfo(frame, context=1): | 
 | 1395 |     """Get information about a frame or traceback object. | 
 | 1396 |  | 
 | 1397 |     A tuple of five things is returned: the filename, the line number of | 
 | 1398 |     the current line, the function name, a list of lines of context from | 
 | 1399 |     the source code, and the index of the current line within that list. | 
 | 1400 |     The optional second argument specifies the number of lines of context | 
 | 1401 |     to return, which are centered around the current line.""" | 
 | 1402 |     if istraceback(frame): | 
| Andrew M. Kuchling | ba8b6bc | 2004-06-05 14:11:59 +0000 | [diff] [blame] | 1403 |         lineno = frame.tb_lineno | 
| Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 1404 |         frame = frame.tb_frame | 
| Andrew M. Kuchling | ba8b6bc | 2004-06-05 14:11:59 +0000 | [diff] [blame] | 1405 |     else: | 
 | 1406 |         lineno = frame.f_lineno | 
| Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 1407 |     if not isframe(frame): | 
| Benjamin Peterson | 4ac9ce4 | 2009-10-04 14:49:41 +0000 | [diff] [blame] | 1408 |         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] | 1409 |  | 
| Neil Schemenauer | f06f853 | 2002-03-23 23:51:04 +0000 | [diff] [blame] | 1410 |     filename = getsourcefile(frame) or getfile(frame) | 
| Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 1411 |     if context > 0: | 
| Guido van Rossum | 54e54c6 | 2001-09-04 19:14:14 +0000 | [diff] [blame] | 1412 |         start = lineno - 1 - context//2 | 
| Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 1413 |         try: | 
 | 1414 |             lines, lnum = findsource(frame) | 
| Andrew Svetlov | f7a17b4 | 2012-12-25 16:47:37 +0200 | [diff] [blame] | 1415 |         except OSError: | 
| Ka-Ping Yee | 4eb0c00 | 2001-03-02 05:50:34 +0000 | [diff] [blame] | 1416 |             lines = index = None | 
 | 1417 |         else: | 
| Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 1418 |             start = max(start, 1) | 
| Raymond Hettinger | a050171 | 2004-06-15 11:22:53 +0000 | [diff] [blame] | 1419 |             start = max(0, min(start, len(lines) - context)) | 
| Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 1420 |             lines = lines[start:start+context] | 
| Ka-Ping Yee | 59ade08 | 2001-03-01 03:55:35 +0000 | [diff] [blame] | 1421 |             index = lineno - 1 - start | 
| Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 1422 |     else: | 
 | 1423 |         lines = index = None | 
 | 1424 |  | 
| Christian Heimes | 25bb783 | 2008-01-11 16:17:00 +0000 | [diff] [blame] | 1425 |     return Traceback(filename, lineno, frame.f_code.co_name, lines, index) | 
| Ka-Ping Yee | 59ade08 | 2001-03-01 03:55:35 +0000 | [diff] [blame] | 1426 |  | 
 | 1427 | def getlineno(frame): | 
 | 1428 |     """Get the line number from a frame object, allowing for optimization.""" | 
| Michael W. Hudson | dd32a91 | 2002-08-15 14:59:02 +0000 | [diff] [blame] | 1429 |     # FrameType.f_lineno is now a descriptor that grovels co_lnotab | 
 | 1430 |     return frame.f_lineno | 
| Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 1431 |  | 
| Antoine Pitrou | cdcafb7 | 2014-08-24 10:50:28 -0400 | [diff] [blame] | 1432 | FrameInfo = namedtuple('FrameInfo', ('frame',) + Traceback._fields) | 
 | 1433 |  | 
| Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 1434 | def getouterframes(frame, context=1): | 
 | 1435 |     """Get a list of records for a frame and all higher (calling) frames. | 
 | 1436 |  | 
 | 1437 |     Each record contains a frame object, filename, line number, function | 
 | 1438 |     name, a list of lines of context, and index within the context.""" | 
 | 1439 |     framelist = [] | 
 | 1440 |     while frame: | 
| Antoine Pitrou | cdcafb7 | 2014-08-24 10:50:28 -0400 | [diff] [blame] | 1441 |         frameinfo = (frame,) + getframeinfo(frame, context) | 
 | 1442 |         framelist.append(FrameInfo(*frameinfo)) | 
| Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 1443 |         frame = frame.f_back | 
 | 1444 |     return framelist | 
 | 1445 |  | 
 | 1446 | def getinnerframes(tb, context=1): | 
 | 1447 |     """Get a list of records for a traceback's frame and all lower frames. | 
 | 1448 |  | 
 | 1449 |     Each record contains a frame object, filename, line number, function | 
 | 1450 |     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] | 1451 |     framelist = [] | 
 | 1452 |     while tb: | 
| Antoine Pitrou | cdcafb7 | 2014-08-24 10:50:28 -0400 | [diff] [blame] | 1453 |         frameinfo = (tb.tb_frame,) + getframeinfo(tb, context) | 
 | 1454 |         framelist.append(FrameInfo(*frameinfo)) | 
| Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 1455 |         tb = tb.tb_next | 
 | 1456 |     return framelist | 
 | 1457 |  | 
| Benjamin Peterson | 42ac475 | 2010-08-09 13:05:35 +0000 | [diff] [blame] | 1458 | def currentframe(): | 
| Benjamin Peterson | a3a3fc6 | 2010-08-09 15:49:56 +0000 | [diff] [blame] | 1459 |     """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] | 1460 |     return sys._getframe(1) if hasattr(sys, "_getframe") else None | 
| Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 1461 |  | 
 | 1462 | def stack(context=1): | 
 | 1463 |     """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] | 1464 |     return getouterframes(sys._getframe(1), context) | 
| Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 1465 |  | 
 | 1466 | def trace(context=1): | 
| Tim Peters | 85ba673 | 2001-02-28 08:26:44 +0000 | [diff] [blame] | 1467 |     """Return a list of records for the stack below the current exception.""" | 
| Fred Drake | d451ec1 | 2002-04-26 02:29:55 +0000 | [diff] [blame] | 1468 |     return getinnerframes(sys.exc_info()[2], context) | 
| Michael Foord | 95fc51d | 2010-11-20 15:07:30 +0000 | [diff] [blame] | 1469 |  | 
 | 1470 |  | 
 | 1471 | # ------------------------------------------------ static version of getattr | 
 | 1472 |  | 
 | 1473 | _sentinel = object() | 
 | 1474 |  | 
| Michael Foord | e516265 | 2010-11-20 16:40:44 +0000 | [diff] [blame] | 1475 | def _static_getmro(klass): | 
 | 1476 |     return type.__dict__['__mro__'].__get__(klass) | 
 | 1477 |  | 
| Michael Foord | 95fc51d | 2010-11-20 15:07:30 +0000 | [diff] [blame] | 1478 | def _check_instance(obj, attr): | 
 | 1479 |     instance_dict = {} | 
 | 1480 |     try: | 
 | 1481 |         instance_dict = object.__getattribute__(obj, "__dict__") | 
 | 1482 |     except AttributeError: | 
 | 1483 |         pass | 
| Michael Foord | dcebe0f | 2011-03-15 19:20:44 -0400 | [diff] [blame] | 1484 |     return dict.get(instance_dict, attr, _sentinel) | 
| Michael Foord | 95fc51d | 2010-11-20 15:07:30 +0000 | [diff] [blame] | 1485 |  | 
 | 1486 |  | 
 | 1487 | def _check_class(klass, attr): | 
| Michael Foord | e516265 | 2010-11-20 16:40:44 +0000 | [diff] [blame] | 1488 |     for entry in _static_getmro(klass): | 
| Michael Foord | a51623b | 2011-12-18 22:01:40 +0000 | [diff] [blame] | 1489 |         if _shadowed_dict(type(entry)) is _sentinel: | 
| Michael Foord | dcebe0f | 2011-03-15 19:20:44 -0400 | [diff] [blame] | 1490 |             try: | 
 | 1491 |                 return entry.__dict__[attr] | 
 | 1492 |             except KeyError: | 
 | 1493 |                 pass | 
| Michael Foord | 95fc51d | 2010-11-20 15:07:30 +0000 | [diff] [blame] | 1494 |     return _sentinel | 
 | 1495 |  | 
| Michael Foord | 35184ed | 2010-11-20 16:58:30 +0000 | [diff] [blame] | 1496 | def _is_type(obj): | 
 | 1497 |     try: | 
 | 1498 |         _static_getmro(obj) | 
 | 1499 |     except TypeError: | 
 | 1500 |         return False | 
 | 1501 |     return True | 
 | 1502 |  | 
| Michael Foord | dcebe0f | 2011-03-15 19:20:44 -0400 | [diff] [blame] | 1503 | def _shadowed_dict(klass): | 
 | 1504 |     dict_attr = type.__dict__["__dict__"] | 
 | 1505 |     for entry in _static_getmro(klass): | 
 | 1506 |         try: | 
 | 1507 |             class_dict = dict_attr.__get__(entry)["__dict__"] | 
 | 1508 |         except KeyError: | 
 | 1509 |             pass | 
 | 1510 |         else: | 
 | 1511 |             if not (type(class_dict) is types.GetSetDescriptorType and | 
 | 1512 |                     class_dict.__name__ == "__dict__" and | 
 | 1513 |                     class_dict.__objclass__ is entry): | 
| Michael Foord | a51623b | 2011-12-18 22:01:40 +0000 | [diff] [blame] | 1514 |                 return class_dict | 
 | 1515 |     return _sentinel | 
| Michael Foord | 95fc51d | 2010-11-20 15:07:30 +0000 | [diff] [blame] | 1516 |  | 
 | 1517 | def getattr_static(obj, attr, default=_sentinel): | 
 | 1518 |     """Retrieve attributes without triggering dynamic lookup via the | 
 | 1519 |        descriptor protocol,  __getattr__ or __getattribute__. | 
 | 1520 |  | 
 | 1521 |        Note: this function may not be able to retrieve all attributes | 
 | 1522 |        that getattr can fetch (like dynamically created attributes) | 
 | 1523 |        and may find attributes that getattr can't (like descriptors | 
 | 1524 |        that raise AttributeError). It can also return descriptor objects | 
 | 1525 |        instead of instance members in some cases. See the | 
 | 1526 |        documentation for details. | 
 | 1527 |     """ | 
 | 1528 |     instance_result = _sentinel | 
| Michael Foord | 35184ed | 2010-11-20 16:58:30 +0000 | [diff] [blame] | 1529 |     if not _is_type(obj): | 
| Michael Foord | cc7ebb8 | 2010-11-20 16:20:16 +0000 | [diff] [blame] | 1530 |         klass = type(obj) | 
| Michael Foord | a51623b | 2011-12-18 22:01:40 +0000 | [diff] [blame] | 1531 |         dict_attr = _shadowed_dict(klass) | 
 | 1532 |         if (dict_attr is _sentinel or | 
 | 1533 |             type(dict_attr) is types.MemberDescriptorType): | 
| Michael Foord | dcebe0f | 2011-03-15 19:20:44 -0400 | [diff] [blame] | 1534 |             instance_result = _check_instance(obj, attr) | 
| Michael Foord | 95fc51d | 2010-11-20 15:07:30 +0000 | [diff] [blame] | 1535 |     else: | 
 | 1536 |         klass = obj | 
 | 1537 |  | 
 | 1538 |     klass_result = _check_class(klass, attr) | 
 | 1539 |  | 
 | 1540 |     if instance_result is not _sentinel and klass_result is not _sentinel: | 
 | 1541 |         if (_check_class(type(klass_result), '__get__') is not _sentinel and | 
 | 1542 |             _check_class(type(klass_result), '__set__') is not _sentinel): | 
 | 1543 |             return klass_result | 
 | 1544 |  | 
 | 1545 |     if instance_result is not _sentinel: | 
 | 1546 |         return instance_result | 
 | 1547 |     if klass_result is not _sentinel: | 
 | 1548 |         return klass_result | 
 | 1549 |  | 
 | 1550 |     if obj is klass: | 
 | 1551 |         # for types we check the metaclass too | 
| Michael Foord | e516265 | 2010-11-20 16:40:44 +0000 | [diff] [blame] | 1552 |         for entry in _static_getmro(type(klass)): | 
| Michael Foord | 3ba95f8 | 2011-12-22 01:13:37 +0000 | [diff] [blame] | 1553 |             if _shadowed_dict(type(entry)) is _sentinel: | 
 | 1554 |                 try: | 
 | 1555 |                     return entry.__dict__[attr] | 
 | 1556 |                 except KeyError: | 
 | 1557 |                     pass | 
| Michael Foord | 95fc51d | 2010-11-20 15:07:30 +0000 | [diff] [blame] | 1558 |     if default is not _sentinel: | 
 | 1559 |         return default | 
 | 1560 |     raise AttributeError(attr) | 
| Nick Coghlan | e0f0465 | 2010-11-21 03:44:04 +0000 | [diff] [blame] | 1561 |  | 
 | 1562 |  | 
| Nick Coghlan | 04e2e3f | 2012-06-23 19:52:05 +1000 | [diff] [blame] | 1563 | # ------------------------------------------------ generator introspection | 
 | 1564 |  | 
| Nick Coghlan | 7921b9f | 2010-11-30 06:36:04 +0000 | [diff] [blame] | 1565 | GEN_CREATED = 'GEN_CREATED' | 
 | 1566 | GEN_RUNNING = 'GEN_RUNNING' | 
 | 1567 | GEN_SUSPENDED = 'GEN_SUSPENDED' | 
 | 1568 | GEN_CLOSED = 'GEN_CLOSED' | 
| Nick Coghlan | e0f0465 | 2010-11-21 03:44:04 +0000 | [diff] [blame] | 1569 |  | 
 | 1570 | def getgeneratorstate(generator): | 
 | 1571 |     """Get current state of a generator-iterator. | 
 | 1572 |  | 
 | 1573 |     Possible states are: | 
 | 1574 |       GEN_CREATED: Waiting to start execution. | 
 | 1575 |       GEN_RUNNING: Currently being executed by the interpreter. | 
 | 1576 |       GEN_SUSPENDED: Currently suspended at a yield expression. | 
 | 1577 |       GEN_CLOSED: Execution has completed. | 
 | 1578 |     """ | 
 | 1579 |     if generator.gi_running: | 
 | 1580 |         return GEN_RUNNING | 
 | 1581 |     if generator.gi_frame is None: | 
 | 1582 |         return GEN_CLOSED | 
 | 1583 |     if generator.gi_frame.f_lasti == -1: | 
 | 1584 |         return GEN_CREATED | 
 | 1585 |     return GEN_SUSPENDED | 
| Larry Hastings | 7c7cbfc | 2012-06-22 15:19:35 -0700 | [diff] [blame] | 1586 |  | 
 | 1587 |  | 
| Nick Coghlan | 04e2e3f | 2012-06-23 19:52:05 +1000 | [diff] [blame] | 1588 | def getgeneratorlocals(generator): | 
 | 1589 |     """ | 
 | 1590 |     Get the mapping of generator local variables to their current values. | 
 | 1591 |  | 
 | 1592 |     A dict is returned, with the keys the local variable names and values the | 
 | 1593 |     bound values.""" | 
 | 1594 |  | 
 | 1595 |     if not isgenerator(generator): | 
 | 1596 |         raise TypeError("'{!r}' is not a Python generator".format(generator)) | 
 | 1597 |  | 
 | 1598 |     frame = getattr(generator, "gi_frame", None) | 
 | 1599 |     if frame is not None: | 
 | 1600 |         return generator.gi_frame.f_locals | 
 | 1601 |     else: | 
 | 1602 |         return {} | 
 | 1603 |  | 
| Yury Selivanov | 5376ba9 | 2015-06-22 12:19:30 -0400 | [diff] [blame] | 1604 |  | 
 | 1605 | # ------------------------------------------------ coroutine introspection | 
 | 1606 |  | 
 | 1607 | CORO_CREATED = 'CORO_CREATED' | 
 | 1608 | CORO_RUNNING = 'CORO_RUNNING' | 
 | 1609 | CORO_SUSPENDED = 'CORO_SUSPENDED' | 
 | 1610 | CORO_CLOSED = 'CORO_CLOSED' | 
 | 1611 |  | 
 | 1612 | def getcoroutinestate(coroutine): | 
 | 1613 |     """Get current state of a coroutine object. | 
 | 1614 |  | 
 | 1615 |     Possible states are: | 
 | 1616 |       CORO_CREATED: Waiting to start execution. | 
 | 1617 |       CORO_RUNNING: Currently being executed by the interpreter. | 
 | 1618 |       CORO_SUSPENDED: Currently suspended at an await expression. | 
 | 1619 |       CORO_CLOSED: Execution has completed. | 
 | 1620 |     """ | 
 | 1621 |     if coroutine.cr_running: | 
 | 1622 |         return CORO_RUNNING | 
 | 1623 |     if coroutine.cr_frame is None: | 
 | 1624 |         return CORO_CLOSED | 
 | 1625 |     if coroutine.cr_frame.f_lasti == -1: | 
 | 1626 |         return CORO_CREATED | 
 | 1627 |     return CORO_SUSPENDED | 
 | 1628 |  | 
 | 1629 |  | 
 | 1630 | def getcoroutinelocals(coroutine): | 
 | 1631 |     """ | 
 | 1632 |     Get the mapping of coroutine local variables to their current values. | 
 | 1633 |  | 
 | 1634 |     A dict is returned, with the keys the local variable names and values the | 
 | 1635 |     bound values.""" | 
 | 1636 |     frame = getattr(coroutine, "cr_frame", None) | 
 | 1637 |     if frame is not None: | 
 | 1638 |         return frame.f_locals | 
 | 1639 |     else: | 
 | 1640 |         return {} | 
 | 1641 |  | 
 | 1642 |  | 
| Larry Hastings | 7c7cbfc | 2012-06-22 15:19:35 -0700 | [diff] [blame] | 1643 | ############################################################################### | 
 | 1644 | ### Function Signature Object (PEP 362) | 
 | 1645 | ############################################################################### | 
 | 1646 |  | 
 | 1647 |  | 
 | 1648 | _WrapperDescriptor = type(type.__call__) | 
 | 1649 | _MethodWrapper = type(all.__call__) | 
| Larry Hastings | 5c66189 | 2014-01-24 06:17:25 -0800 | [diff] [blame] | 1650 | _ClassMethodWrapper = type(int.__dict__['from_bytes']) | 
| Larry Hastings | 7c7cbfc | 2012-06-22 15:19:35 -0700 | [diff] [blame] | 1651 |  | 
 | 1652 | _NonUserDefinedCallables = (_WrapperDescriptor, | 
 | 1653 |                             _MethodWrapper, | 
| Larry Hastings | 5c66189 | 2014-01-24 06:17:25 -0800 | [diff] [blame] | 1654 |                             _ClassMethodWrapper, | 
| Larry Hastings | 7c7cbfc | 2012-06-22 15:19:35 -0700 | [diff] [blame] | 1655 |                             types.BuiltinFunctionType) | 
 | 1656 |  | 
 | 1657 |  | 
| Yury Selivanov | 421f0c7 | 2014-01-29 12:05:40 -0500 | [diff] [blame] | 1658 | def _signature_get_user_defined_method(cls, method_name): | 
| Yury Selivanov | 5a23bd0 | 2014-03-29 13:47:11 -0400 | [diff] [blame] | 1659 |     """Private helper. Checks if ``cls`` has an attribute | 
 | 1660 |     named ``method_name`` and returns it only if it is a | 
 | 1661 |     pure python function. | 
 | 1662 |     """ | 
| Larry Hastings | 7c7cbfc | 2012-06-22 15:19:35 -0700 | [diff] [blame] | 1663 |     try: | 
 | 1664 |         meth = getattr(cls, method_name) | 
 | 1665 |     except AttributeError: | 
 | 1666 |         return | 
 | 1667 |     else: | 
 | 1668 |         if not isinstance(meth, _NonUserDefinedCallables): | 
 | 1669 |             # Once '__signature__' will be added to 'C'-level | 
 | 1670 |             # callables, this check won't be necessary | 
 | 1671 |             return meth | 
 | 1672 |  | 
 | 1673 |  | 
| Yury Selivanov | 62560fb | 2014-01-28 12:26:24 -0500 | [diff] [blame] | 1674 | def _signature_get_partial(wrapped_sig, partial, extra_args=()): | 
| Yury Selivanov | 5a23bd0 | 2014-03-29 13:47:11 -0400 | [diff] [blame] | 1675 |     """Private helper to calculate how 'wrapped_sig' signature will | 
 | 1676 |     look like after applying a 'functools.partial' object (or alike) | 
 | 1677 |     on it. | 
 | 1678 |     """ | 
| Yury Selivanov | 62560fb | 2014-01-28 12:26:24 -0500 | [diff] [blame] | 1679 |  | 
| Yury Selivanov | 3f73ca2 | 2014-04-08 11:30:45 -0400 | [diff] [blame] | 1680 |     old_params = wrapped_sig.parameters | 
 | 1681 |     new_params = OrderedDict(old_params.items()) | 
| Yury Selivanov | da5fe4f | 2014-01-27 17:28:37 -0500 | [diff] [blame] | 1682 |  | 
 | 1683 |     partial_args = partial.args or () | 
 | 1684 |     partial_keywords = partial.keywords or {} | 
 | 1685 |  | 
 | 1686 |     if extra_args: | 
 | 1687 |         partial_args = extra_args + partial_args | 
 | 1688 |  | 
 | 1689 |     try: | 
 | 1690 |         ba = wrapped_sig.bind_partial(*partial_args, **partial_keywords) | 
 | 1691 |     except TypeError as ex: | 
 | 1692 |         msg = 'partial object {!r} has incorrect arguments'.format(partial) | 
 | 1693 |         raise ValueError(msg) from ex | 
 | 1694 |  | 
| Yury Selivanov | da5fe4f | 2014-01-27 17:28:37 -0500 | [diff] [blame] | 1695 |  | 
| Yury Selivanov | 3f73ca2 | 2014-04-08 11:30:45 -0400 | [diff] [blame] | 1696 |     transform_to_kwonly = False | 
 | 1697 |     for param_name, param in old_params.items(): | 
 | 1698 |         try: | 
 | 1699 |             arg_value = ba.arguments[param_name] | 
 | 1700 |         except KeyError: | 
 | 1701 |             pass | 
 | 1702 |         else: | 
 | 1703 |             if param.kind is _POSITIONAL_ONLY: | 
 | 1704 |                 # If positional-only parameter is bound by partial, | 
 | 1705 |                 # it effectively disappears from the signature | 
 | 1706 |                 new_params.pop(param_name) | 
 | 1707 |                 continue | 
 | 1708 |  | 
 | 1709 |             if param.kind is _POSITIONAL_OR_KEYWORD: | 
 | 1710 |                 if param_name in partial_keywords: | 
 | 1711 |                     # This means that this parameter, and all parameters | 
 | 1712 |                     # after it should be keyword-only (and var-positional | 
 | 1713 |                     # should be removed). Here's why. Consider the following | 
 | 1714 |                     # function: | 
 | 1715 |                     #     foo(a, b, *args, c): | 
 | 1716 |                     #         pass | 
 | 1717 |                     # | 
 | 1718 |                     # "partial(foo, a='spam')" will have the following | 
 | 1719 |                     # signature: "(*, a='spam', b, c)". Because attempting | 
 | 1720 |                     # to call that partial with "(10, 20)" arguments will | 
 | 1721 |                     # raise a TypeError, saying that "a" argument received | 
 | 1722 |                     # multiple values. | 
 | 1723 |                     transform_to_kwonly = True | 
 | 1724 |                     # Set the new default value | 
 | 1725 |                     new_params[param_name] = param.replace(default=arg_value) | 
 | 1726 |                 else: | 
 | 1727 |                     # was passed as a positional argument | 
 | 1728 |                     new_params.pop(param.name) | 
 | 1729 |                     continue | 
 | 1730 |  | 
 | 1731 |             if param.kind is _KEYWORD_ONLY: | 
 | 1732 |                 # Set the new default value | 
 | 1733 |                 new_params[param_name] = param.replace(default=arg_value) | 
 | 1734 |  | 
 | 1735 |         if transform_to_kwonly: | 
 | 1736 |             assert param.kind is not _POSITIONAL_ONLY | 
 | 1737 |  | 
 | 1738 |             if param.kind is _POSITIONAL_OR_KEYWORD: | 
 | 1739 |                 new_param = new_params[param_name].replace(kind=_KEYWORD_ONLY) | 
 | 1740 |                 new_params[param_name] = new_param | 
 | 1741 |                 new_params.move_to_end(param_name) | 
 | 1742 |             elif param.kind in (_KEYWORD_ONLY, _VAR_KEYWORD): | 
 | 1743 |                 new_params.move_to_end(param_name) | 
 | 1744 |             elif param.kind is _VAR_POSITIONAL: | 
 | 1745 |                 new_params.pop(param.name) | 
| Yury Selivanov | da5fe4f | 2014-01-27 17:28:37 -0500 | [diff] [blame] | 1746 |  | 
 | 1747 |     return wrapped_sig.replace(parameters=new_params.values()) | 
 | 1748 |  | 
 | 1749 |  | 
| Yury Selivanov | 62560fb | 2014-01-28 12:26:24 -0500 | [diff] [blame] | 1750 | def _signature_bound_method(sig): | 
| Yury Selivanov | 5a23bd0 | 2014-03-29 13:47:11 -0400 | [diff] [blame] | 1751 |     """Private helper to transform signatures for unbound | 
 | 1752 |     functions to bound methods. | 
 | 1753 |     """ | 
| Yury Selivanov | 62560fb | 2014-01-28 12:26:24 -0500 | [diff] [blame] | 1754 |  | 
 | 1755 |     params = tuple(sig.parameters.values()) | 
 | 1756 |  | 
 | 1757 |     if not params or params[0].kind in (_VAR_KEYWORD, _KEYWORD_ONLY): | 
 | 1758 |         raise ValueError('invalid method signature') | 
 | 1759 |  | 
 | 1760 |     kind = params[0].kind | 
 | 1761 |     if kind in (_POSITIONAL_OR_KEYWORD, _POSITIONAL_ONLY): | 
 | 1762 |         # Drop first parameter: | 
 | 1763 |         # '(p1, p2[, ...])' -> '(p2[, ...])' | 
 | 1764 |         params = params[1:] | 
 | 1765 |     else: | 
 | 1766 |         if kind is not _VAR_POSITIONAL: | 
 | 1767 |             # Unless we add a new parameter type we never | 
 | 1768 |             # get here | 
 | 1769 |             raise ValueError('invalid argument type') | 
 | 1770 |         # It's a var-positional parameter. | 
 | 1771 |         # Do nothing. '(*args[, ...])' -> '(*args[, ...])' | 
 | 1772 |  | 
 | 1773 |     return sig.replace(parameters=params) | 
 | 1774 |  | 
 | 1775 |  | 
| Yury Selivanov | b77511d | 2014-01-29 10:46:14 -0500 | [diff] [blame] | 1776 | def _signature_is_builtin(obj): | 
| Yury Selivanov | 5a23bd0 | 2014-03-29 13:47:11 -0400 | [diff] [blame] | 1777 |     """Private helper to test if `obj` is a callable that might | 
 | 1778 |     support Argument Clinic's __text_signature__ protocol. | 
 | 1779 |     """ | 
| Yury Selivanov | 1d24183 | 2014-02-02 12:51:20 -0500 | [diff] [blame] | 1780 |     return (isbuiltin(obj) or | 
| Yury Selivanov | b77511d | 2014-01-29 10:46:14 -0500 | [diff] [blame] | 1781 |             ismethoddescriptor(obj) or | 
| Yury Selivanov | 1d24183 | 2014-02-02 12:51:20 -0500 | [diff] [blame] | 1782 |             isinstance(obj, _NonUserDefinedCallables) or | 
| Yury Selivanov | b77511d | 2014-01-29 10:46:14 -0500 | [diff] [blame] | 1783 |             # Can't test 'isinstance(type)' here, as it would | 
 | 1784 |             # also be True for regular python classes | 
 | 1785 |             obj in (type, object)) | 
 | 1786 |  | 
 | 1787 |  | 
| Yury Selivanov | 63da7c7 | 2014-01-31 14:48:37 -0500 | [diff] [blame] | 1788 | def _signature_is_functionlike(obj): | 
| Yury Selivanov | 5a23bd0 | 2014-03-29 13:47:11 -0400 | [diff] [blame] | 1789 |     """Private helper to test if `obj` is a duck type of FunctionType. | 
 | 1790 |     A good example of such objects are functions compiled with | 
 | 1791 |     Cython, which have all attributes that a pure Python function | 
 | 1792 |     would have, but have their code statically compiled. | 
 | 1793 |     """ | 
| Yury Selivanov | 63da7c7 | 2014-01-31 14:48:37 -0500 | [diff] [blame] | 1794 |  | 
 | 1795 |     if not callable(obj) or isclass(obj): | 
 | 1796 |         # All function-like objects are obviously callables, | 
 | 1797 |         # and not classes. | 
 | 1798 |         return False | 
 | 1799 |  | 
 | 1800 |     name = getattr(obj, '__name__', None) | 
 | 1801 |     code = getattr(obj, '__code__', None) | 
 | 1802 |     defaults = getattr(obj, '__defaults__', _void) # Important to use _void ... | 
 | 1803 |     kwdefaults = getattr(obj, '__kwdefaults__', _void) # ... and not None here | 
 | 1804 |     annotations = getattr(obj, '__annotations__', None) | 
 | 1805 |  | 
 | 1806 |     return (isinstance(code, types.CodeType) and | 
 | 1807 |             isinstance(name, str) and | 
 | 1808 |             (defaults is None or isinstance(defaults, tuple)) and | 
 | 1809 |             (kwdefaults is None or isinstance(kwdefaults, dict)) and | 
 | 1810 |             isinstance(annotations, dict)) | 
 | 1811 |  | 
 | 1812 |  | 
| Yury Selivanov | d82eddc | 2014-01-29 11:24:39 -0500 | [diff] [blame] | 1813 | def _signature_get_bound_param(spec): | 
| Yury Selivanov | 5a23bd0 | 2014-03-29 13:47:11 -0400 | [diff] [blame] | 1814 |     """ Private helper to get first parameter name from a | 
 | 1815 |     __text_signature__ of a builtin method, which should | 
 | 1816 |     be in the following format: '($param1, ...)'. | 
 | 1817 |     Assumptions are that the first argument won't have | 
 | 1818 |     a default value or an annotation. | 
 | 1819 |     """ | 
| Yury Selivanov | d82eddc | 2014-01-29 11:24:39 -0500 | [diff] [blame] | 1820 |  | 
 | 1821 |     assert spec.startswith('($') | 
 | 1822 |  | 
 | 1823 |     pos = spec.find(',') | 
 | 1824 |     if pos == -1: | 
 | 1825 |         pos = spec.find(')') | 
 | 1826 |  | 
 | 1827 |     cpos = spec.find(':') | 
 | 1828 |     assert cpos == -1 or cpos > pos | 
 | 1829 |  | 
 | 1830 |     cpos = spec.find('=') | 
 | 1831 |     assert cpos == -1 or cpos > pos | 
 | 1832 |  | 
 | 1833 |     return spec[2:pos] | 
 | 1834 |  | 
 | 1835 |  | 
| Larry Hastings | 2623c8c | 2014-02-08 22:15:29 -0800 | [diff] [blame] | 1836 | def _signature_strip_non_python_syntax(signature): | 
 | 1837 |     """ | 
| Yury Selivanov | 5a23bd0 | 2014-03-29 13:47:11 -0400 | [diff] [blame] | 1838 |     Private helper function. Takes a signature in Argument Clinic's | 
 | 1839 |     extended signature format. | 
 | 1840 |  | 
| Larry Hastings | 2623c8c | 2014-02-08 22:15:29 -0800 | [diff] [blame] | 1841 |     Returns a tuple of three things: | 
 | 1842 |       * that signature re-rendered in standard Python syntax, | 
 | 1843 |       * the index of the "self" parameter (generally 0), or None if | 
 | 1844 |         the function does not have a "self" parameter, and | 
 | 1845 |       * the index of the last "positional only" parameter, | 
 | 1846 |         or None if the signature has no positional-only parameters. | 
 | 1847 |     """ | 
 | 1848 |  | 
 | 1849 |     if not signature: | 
 | 1850 |         return signature, None, None | 
 | 1851 |  | 
 | 1852 |     self_parameter = None | 
 | 1853 |     last_positional_only = None | 
 | 1854 |  | 
 | 1855 |     lines = [l.encode('ascii') for l in signature.split('\n')] | 
 | 1856 |     generator = iter(lines).__next__ | 
 | 1857 |     token_stream = tokenize.tokenize(generator) | 
 | 1858 |  | 
 | 1859 |     delayed_comma = False | 
 | 1860 |     skip_next_comma = False | 
 | 1861 |     text = [] | 
 | 1862 |     add = text.append | 
 | 1863 |  | 
 | 1864 |     current_parameter = 0 | 
 | 1865 |     OP = token.OP | 
 | 1866 |     ERRORTOKEN = token.ERRORTOKEN | 
 | 1867 |  | 
 | 1868 |     # token stream always starts with ENCODING token, skip it | 
 | 1869 |     t = next(token_stream) | 
 | 1870 |     assert t.type == tokenize.ENCODING | 
 | 1871 |  | 
 | 1872 |     for t in token_stream: | 
 | 1873 |         type, string = t.type, t.string | 
 | 1874 |  | 
 | 1875 |         if type == OP: | 
 | 1876 |             if string == ',': | 
 | 1877 |                 if skip_next_comma: | 
 | 1878 |                     skip_next_comma = False | 
 | 1879 |                 else: | 
 | 1880 |                     assert not delayed_comma | 
 | 1881 |                     delayed_comma = True | 
 | 1882 |                     current_parameter += 1 | 
 | 1883 |                 continue | 
 | 1884 |  | 
 | 1885 |             if string == '/': | 
 | 1886 |                 assert not skip_next_comma | 
 | 1887 |                 assert last_positional_only is None | 
 | 1888 |                 skip_next_comma = True | 
 | 1889 |                 last_positional_only = current_parameter - 1 | 
 | 1890 |                 continue | 
 | 1891 |  | 
 | 1892 |         if (type == ERRORTOKEN) and (string == '$'): | 
 | 1893 |             assert self_parameter is None | 
 | 1894 |             self_parameter = current_parameter | 
 | 1895 |             continue | 
 | 1896 |  | 
 | 1897 |         if delayed_comma: | 
 | 1898 |             delayed_comma = False | 
 | 1899 |             if not ((type == OP) and (string == ')')): | 
 | 1900 |                 add(', ') | 
 | 1901 |         add(string) | 
 | 1902 |         if (string == ','): | 
 | 1903 |             add(' ') | 
 | 1904 |     clean_signature = ''.join(text) | 
 | 1905 |     return clean_signature, self_parameter, last_positional_only | 
 | 1906 |  | 
 | 1907 |  | 
| Yury Selivanov | 57d240e | 2014-02-19 16:27:23 -0500 | [diff] [blame] | 1908 | def _signature_fromstr(cls, obj, s, skip_bound_arg=True): | 
| Yury Selivanov | 5a23bd0 | 2014-03-29 13:47:11 -0400 | [diff] [blame] | 1909 |     """Private helper to parse content of '__text_signature__' | 
 | 1910 |     and return a Signature based on it. | 
 | 1911 |     """ | 
 | 1912 |  | 
| Yury Selivanov | 7d2bfed | 2014-02-03 02:46:07 -0500 | [diff] [blame] | 1913 |     Parameter = cls._parameter_cls | 
 | 1914 |  | 
| Larry Hastings | 2623c8c | 2014-02-08 22:15:29 -0800 | [diff] [blame] | 1915 |     clean_signature, self_parameter, last_positional_only = \ | 
 | 1916 |         _signature_strip_non_python_syntax(s) | 
| Yury Selivanov | 7d2bfed | 2014-02-03 02:46:07 -0500 | [diff] [blame] | 1917 |  | 
| Larry Hastings | 2623c8c | 2014-02-08 22:15:29 -0800 | [diff] [blame] | 1918 |     program = "def foo" + clean_signature + ": pass" | 
| Yury Selivanov | 7d2bfed | 2014-02-03 02:46:07 -0500 | [diff] [blame] | 1919 |  | 
 | 1920 |     try: | 
| Larry Hastings | 2623c8c | 2014-02-08 22:15:29 -0800 | [diff] [blame] | 1921 |         module = ast.parse(program) | 
| Yury Selivanov | 7d2bfed | 2014-02-03 02:46:07 -0500 | [diff] [blame] | 1922 |     except SyntaxError: | 
 | 1923 |         module = None | 
 | 1924 |  | 
 | 1925 |     if not isinstance(module, ast.Module): | 
 | 1926 |         raise ValueError("{!r} builtin has invalid signature".format(obj)) | 
 | 1927 |  | 
 | 1928 |     f = module.body[0] | 
 | 1929 |  | 
 | 1930 |     parameters = [] | 
 | 1931 |     empty = Parameter.empty | 
 | 1932 |     invalid = object() | 
 | 1933 |  | 
 | 1934 |     module = None | 
 | 1935 |     module_dict = {} | 
 | 1936 |     module_name = getattr(obj, '__module__', None) | 
 | 1937 |     if module_name: | 
 | 1938 |         module = sys.modules.get(module_name, None) | 
 | 1939 |         if module: | 
 | 1940 |             module_dict = module.__dict__ | 
 | 1941 |     sys_module_dict = sys.modules | 
 | 1942 |  | 
 | 1943 |     def parse_name(node): | 
 | 1944 |         assert isinstance(node, ast.arg) | 
 | 1945 |         if node.annotation != None: | 
 | 1946 |             raise ValueError("Annotations are not currently supported") | 
 | 1947 |         return node.arg | 
 | 1948 |  | 
 | 1949 |     def wrap_value(s): | 
 | 1950 |         try: | 
 | 1951 |             value = eval(s, module_dict) | 
 | 1952 |         except NameError: | 
 | 1953 |             try: | 
 | 1954 |                 value = eval(s, sys_module_dict) | 
 | 1955 |             except NameError: | 
 | 1956 |                 raise RuntimeError() | 
 | 1957 |  | 
 | 1958 |         if isinstance(value, str): | 
 | 1959 |             return ast.Str(value) | 
 | 1960 |         if isinstance(value, (int, float)): | 
 | 1961 |             return ast.Num(value) | 
 | 1962 |         if isinstance(value, bytes): | 
 | 1963 |             return ast.Bytes(value) | 
 | 1964 |         if value in (True, False, None): | 
 | 1965 |             return ast.NameConstant(value) | 
 | 1966 |         raise RuntimeError() | 
 | 1967 |  | 
 | 1968 |     class RewriteSymbolics(ast.NodeTransformer): | 
 | 1969 |         def visit_Attribute(self, node): | 
 | 1970 |             a = [] | 
 | 1971 |             n = node | 
 | 1972 |             while isinstance(n, ast.Attribute): | 
 | 1973 |                 a.append(n.attr) | 
 | 1974 |                 n = n.value | 
 | 1975 |             if not isinstance(n, ast.Name): | 
 | 1976 |                 raise RuntimeError() | 
 | 1977 |             a.append(n.id) | 
 | 1978 |             value = ".".join(reversed(a)) | 
 | 1979 |             return wrap_value(value) | 
 | 1980 |  | 
 | 1981 |         def visit_Name(self, node): | 
 | 1982 |             if not isinstance(node.ctx, ast.Load): | 
 | 1983 |                 raise ValueError() | 
 | 1984 |             return wrap_value(node.id) | 
 | 1985 |  | 
 | 1986 |     def p(name_node, default_node, default=empty): | 
 | 1987 |         name = parse_name(name_node) | 
 | 1988 |         if name is invalid: | 
 | 1989 |             return None | 
 | 1990 |         if default_node and default_node is not _empty: | 
 | 1991 |             try: | 
 | 1992 |                 default_node = RewriteSymbolics().visit(default_node) | 
 | 1993 |                 o = ast.literal_eval(default_node) | 
 | 1994 |             except ValueError: | 
 | 1995 |                 o = invalid | 
 | 1996 |             if o is invalid: | 
 | 1997 |                 return None | 
 | 1998 |             default = o if o is not invalid else default | 
 | 1999 |         parameters.append(Parameter(name, kind, default=default, annotation=empty)) | 
 | 2000 |  | 
 | 2001 |     # non-keyword-only parameters | 
 | 2002 |     args = reversed(f.args.args) | 
 | 2003 |     defaults = reversed(f.args.defaults) | 
 | 2004 |     iter = itertools.zip_longest(args, defaults, fillvalue=None) | 
| Larry Hastings | 2623c8c | 2014-02-08 22:15:29 -0800 | [diff] [blame] | 2005 |     if last_positional_only is not None: | 
 | 2006 |         kind = Parameter.POSITIONAL_ONLY | 
 | 2007 |     else: | 
 | 2008 |         kind = Parameter.POSITIONAL_OR_KEYWORD | 
 | 2009 |     for i, (name, default) in enumerate(reversed(list(iter))): | 
| Yury Selivanov | 7d2bfed | 2014-02-03 02:46:07 -0500 | [diff] [blame] | 2010 |         p(name, default) | 
| Larry Hastings | 2623c8c | 2014-02-08 22:15:29 -0800 | [diff] [blame] | 2011 |         if i == last_positional_only: | 
 | 2012 |             kind = Parameter.POSITIONAL_OR_KEYWORD | 
| Yury Selivanov | 7d2bfed | 2014-02-03 02:46:07 -0500 | [diff] [blame] | 2013 |  | 
 | 2014 |     # *args | 
 | 2015 |     if f.args.vararg: | 
 | 2016 |         kind = Parameter.VAR_POSITIONAL | 
 | 2017 |         p(f.args.vararg, empty) | 
 | 2018 |  | 
 | 2019 |     # keyword-only arguments | 
 | 2020 |     kind = Parameter.KEYWORD_ONLY | 
 | 2021 |     for name, default in zip(f.args.kwonlyargs, f.args.kw_defaults): | 
 | 2022 |         p(name, default) | 
 | 2023 |  | 
 | 2024 |     # **kwargs | 
 | 2025 |     if f.args.kwarg: | 
 | 2026 |         kind = Parameter.VAR_KEYWORD | 
 | 2027 |         p(f.args.kwarg, empty) | 
 | 2028 |  | 
| Larry Hastings | 2623c8c | 2014-02-08 22:15:29 -0800 | [diff] [blame] | 2029 |     if self_parameter is not None: | 
| Yury Selivanov | 8c185ee | 2014-02-21 01:32:42 -0500 | [diff] [blame] | 2030 |         # Possibly strip the bound argument: | 
 | 2031 |         #    - We *always* strip first bound argument if | 
 | 2032 |         #      it is a module. | 
 | 2033 |         #    - We don't strip first bound argument if | 
 | 2034 |         #      skip_bound_arg is False. | 
| Yury Selivanov | 7d2bfed | 2014-02-03 02:46:07 -0500 | [diff] [blame] | 2035 |         assert parameters | 
| Yury Selivanov | 8c185ee | 2014-02-21 01:32:42 -0500 | [diff] [blame] | 2036 |         _self = getattr(obj, '__self__', None) | 
 | 2037 |         self_isbound = _self is not None | 
 | 2038 |         self_ismodule = ismodule(_self) | 
 | 2039 |         if self_isbound and (self_ismodule or skip_bound_arg): | 
| Yury Selivanov | 7d2bfed | 2014-02-03 02:46:07 -0500 | [diff] [blame] | 2040 |             parameters.pop(0) | 
 | 2041 |         else: | 
 | 2042 |             # for builtins, self parameter is always positional-only! | 
 | 2043 |             p = parameters[0].replace(kind=Parameter.POSITIONAL_ONLY) | 
 | 2044 |             parameters[0] = p | 
 | 2045 |  | 
 | 2046 |     return cls(parameters, return_annotation=cls.empty) | 
 | 2047 |  | 
 | 2048 |  | 
| Yury Selivanov | 57d240e | 2014-02-19 16:27:23 -0500 | [diff] [blame] | 2049 | def _signature_from_builtin(cls, func, skip_bound_arg=True): | 
| Yury Selivanov | 5a23bd0 | 2014-03-29 13:47:11 -0400 | [diff] [blame] | 2050 |     """Private helper function to get signature for | 
 | 2051 |     builtin callables. | 
 | 2052 |     """ | 
 | 2053 |  | 
| Yury Selivanov | 57d240e | 2014-02-19 16:27:23 -0500 | [diff] [blame] | 2054 |     if not _signature_is_builtin(func): | 
 | 2055 |         raise TypeError("{!r} is not a Python builtin " | 
 | 2056 |                         "function".format(func)) | 
 | 2057 |  | 
 | 2058 |     s = getattr(func, "__text_signature__", None) | 
 | 2059 |     if not s: | 
 | 2060 |         raise ValueError("no signature found for builtin {!r}".format(func)) | 
 | 2061 |  | 
 | 2062 |     return _signature_fromstr(cls, func, s, skip_bound_arg) | 
 | 2063 |  | 
 | 2064 |  | 
| Yury Selivanov | cf45f02 | 2015-05-20 14:38:50 -0400 | [diff] [blame] | 2065 | def _signature_from_function(cls, func): | 
 | 2066 |     """Private helper: constructs Signature for the given python function.""" | 
 | 2067 |  | 
 | 2068 |     is_duck_function = False | 
 | 2069 |     if not isfunction(func): | 
 | 2070 |         if _signature_is_functionlike(func): | 
 | 2071 |             is_duck_function = True | 
 | 2072 |         else: | 
 | 2073 |             # If it's not a pure Python function, and not a duck type | 
 | 2074 |             # of pure function: | 
 | 2075 |             raise TypeError('{!r} is not a Python function'.format(func)) | 
 | 2076 |  | 
 | 2077 |     Parameter = cls._parameter_cls | 
 | 2078 |  | 
 | 2079 |     # Parameter information. | 
 | 2080 |     func_code = func.__code__ | 
 | 2081 |     pos_count = func_code.co_argcount | 
 | 2082 |     arg_names = func_code.co_varnames | 
 | 2083 |     positional = tuple(arg_names[:pos_count]) | 
 | 2084 |     keyword_only_count = func_code.co_kwonlyargcount | 
 | 2085 |     keyword_only = arg_names[pos_count:(pos_count + keyword_only_count)] | 
 | 2086 |     annotations = func.__annotations__ | 
 | 2087 |     defaults = func.__defaults__ | 
 | 2088 |     kwdefaults = func.__kwdefaults__ | 
 | 2089 |  | 
 | 2090 |     if defaults: | 
 | 2091 |         pos_default_count = len(defaults) | 
 | 2092 |     else: | 
 | 2093 |         pos_default_count = 0 | 
 | 2094 |  | 
 | 2095 |     parameters = [] | 
 | 2096 |  | 
 | 2097 |     # Non-keyword-only parameters w/o defaults. | 
 | 2098 |     non_default_count = pos_count - pos_default_count | 
 | 2099 |     for name in positional[:non_default_count]: | 
 | 2100 |         annotation = annotations.get(name, _empty) | 
 | 2101 |         parameters.append(Parameter(name, annotation=annotation, | 
 | 2102 |                                     kind=_POSITIONAL_OR_KEYWORD)) | 
 | 2103 |  | 
 | 2104 |     # ... w/ defaults. | 
 | 2105 |     for offset, name in enumerate(positional[non_default_count:]): | 
 | 2106 |         annotation = annotations.get(name, _empty) | 
 | 2107 |         parameters.append(Parameter(name, annotation=annotation, | 
 | 2108 |                                     kind=_POSITIONAL_OR_KEYWORD, | 
 | 2109 |                                     default=defaults[offset])) | 
 | 2110 |  | 
 | 2111 |     # *args | 
 | 2112 |     if func_code.co_flags & CO_VARARGS: | 
 | 2113 |         name = arg_names[pos_count + keyword_only_count] | 
 | 2114 |         annotation = annotations.get(name, _empty) | 
 | 2115 |         parameters.append(Parameter(name, annotation=annotation, | 
 | 2116 |                                     kind=_VAR_POSITIONAL)) | 
 | 2117 |  | 
 | 2118 |     # Keyword-only parameters. | 
 | 2119 |     for name in keyword_only: | 
 | 2120 |         default = _empty | 
 | 2121 |         if kwdefaults is not None: | 
 | 2122 |             default = kwdefaults.get(name, _empty) | 
 | 2123 |  | 
 | 2124 |         annotation = annotations.get(name, _empty) | 
 | 2125 |         parameters.append(Parameter(name, annotation=annotation, | 
 | 2126 |                                     kind=_KEYWORD_ONLY, | 
 | 2127 |                                     default=default)) | 
 | 2128 |     # **kwargs | 
 | 2129 |     if func_code.co_flags & CO_VARKEYWORDS: | 
 | 2130 |         index = pos_count + keyword_only_count | 
 | 2131 |         if func_code.co_flags & CO_VARARGS: | 
 | 2132 |             index += 1 | 
 | 2133 |  | 
 | 2134 |         name = arg_names[index] | 
 | 2135 |         annotation = annotations.get(name, _empty) | 
 | 2136 |         parameters.append(Parameter(name, annotation=annotation, | 
 | 2137 |                                     kind=_VAR_KEYWORD)) | 
 | 2138 |  | 
 | 2139 |     # Is 'func' is a pure Python function - don't validate the | 
 | 2140 |     # parameters list (for correct order and defaults), it should be OK. | 
 | 2141 |     return cls(parameters, | 
 | 2142 |                return_annotation=annotations.get('return', _empty), | 
 | 2143 |                __validate_parameters__=is_duck_function) | 
 | 2144 |  | 
 | 2145 |  | 
| Yury Selivanov | 5a23bd0 | 2014-03-29 13:47:11 -0400 | [diff] [blame] | 2146 | def _signature_from_callable(obj, *, | 
 | 2147 |                              follow_wrapper_chains=True, | 
 | 2148 |                              skip_bound_arg=True, | 
 | 2149 |                              sigcls): | 
 | 2150 |  | 
 | 2151 |     """Private helper function to get signature for arbitrary | 
 | 2152 |     callable objects. | 
 | 2153 |     """ | 
| Larry Hastings | 7c7cbfc | 2012-06-22 15:19:35 -0700 | [diff] [blame] | 2154 |  | 
 | 2155 |     if not callable(obj): | 
 | 2156 |         raise TypeError('{!r} is not a callable object'.format(obj)) | 
 | 2157 |  | 
 | 2158 |     if isinstance(obj, types.MethodType): | 
 | 2159 |         # In this case we skip the first parameter of the underlying | 
 | 2160 |         # function (usually `self` or `cls`). | 
| Yury Selivanov | 5a23bd0 | 2014-03-29 13:47:11 -0400 | [diff] [blame] | 2161 |         sig = _signature_from_callable( | 
| Yury Selivanov | da39645 | 2014-03-27 12:09:24 -0400 | [diff] [blame] | 2162 |             obj.__func__, | 
 | 2163 |             follow_wrapper_chains=follow_wrapper_chains, | 
 | 2164 |             skip_bound_arg=skip_bound_arg, | 
 | 2165 |             sigcls=sigcls) | 
 | 2166 |  | 
| Yury Selivanov | 57d240e | 2014-02-19 16:27:23 -0500 | [diff] [blame] | 2167 |         if skip_bound_arg: | 
 | 2168 |             return _signature_bound_method(sig) | 
 | 2169 |         else: | 
 | 2170 |             return sig | 
| Larry Hastings | 7c7cbfc | 2012-06-22 15:19:35 -0700 | [diff] [blame] | 2171 |  | 
| Nick Coghlan | e8c45d6 | 2013-07-28 20:00:01 +1000 | [diff] [blame] | 2172 |     # Was this function wrapped by a decorator? | 
| Yury Selivanov | 57d240e | 2014-02-19 16:27:23 -0500 | [diff] [blame] | 2173 |     if follow_wrapper_chains: | 
 | 2174 |         obj = unwrap(obj, stop=(lambda f: hasattr(f, "__signature__"))) | 
| Yury Selivanov | 46c759d | 2015-05-27 21:56:53 -0400 | [diff] [blame] | 2175 |         if isinstance(obj, types.MethodType): | 
 | 2176 |             # If the unwrapped object is a *method*, we might want to | 
 | 2177 |             # skip its first parameter (self). | 
 | 2178 |             # See test_signature_wrapped_bound_method for details. | 
| Yury Selivanov | 507cd3c | 2015-05-27 21:59:03 -0400 | [diff] [blame] | 2179 |             return _signature_from_callable( | 
| Yury Selivanov | 46c759d | 2015-05-27 21:56:53 -0400 | [diff] [blame] | 2180 |                 obj, | 
 | 2181 |                 follow_wrapper_chains=follow_wrapper_chains, | 
| Yury Selivanov | 507cd3c | 2015-05-27 21:59:03 -0400 | [diff] [blame] | 2182 |                 skip_bound_arg=skip_bound_arg, | 
 | 2183 |                 sigcls=sigcls) | 
| Nick Coghlan | e8c45d6 | 2013-07-28 20:00:01 +1000 | [diff] [blame] | 2184 |  | 
| Larry Hastings | 7c7cbfc | 2012-06-22 15:19:35 -0700 | [diff] [blame] | 2185 |     try: | 
 | 2186 |         sig = obj.__signature__ | 
 | 2187 |     except AttributeError: | 
 | 2188 |         pass | 
 | 2189 |     else: | 
 | 2190 |         if sig is not None: | 
| Yury Selivanov | 42407ab | 2014-06-23 10:23:50 -0700 | [diff] [blame] | 2191 |             if not isinstance(sig, Signature): | 
 | 2192 |                 raise TypeError( | 
 | 2193 |                     'unexpected object {!r} in __signature__ ' | 
 | 2194 |                     'attribute'.format(sig)) | 
| Larry Hastings | 7c7cbfc | 2012-06-22 15:19:35 -0700 | [diff] [blame] | 2195 |             return sig | 
 | 2196 |  | 
| Yury Selivanov | da5fe4f | 2014-01-27 17:28:37 -0500 | [diff] [blame] | 2197 |     try: | 
 | 2198 |         partialmethod = obj._partialmethod | 
 | 2199 |     except AttributeError: | 
 | 2200 |         pass | 
 | 2201 |     else: | 
| Yury Selivanov | 0486f81 | 2014-01-29 12:18:59 -0500 | [diff] [blame] | 2202 |         if isinstance(partialmethod, functools.partialmethod): | 
 | 2203 |             # Unbound partialmethod (see functools.partialmethod) | 
 | 2204 |             # This means, that we need to calculate the signature | 
 | 2205 |             # as if it's a regular partial object, but taking into | 
 | 2206 |             # account that the first positional argument | 
 | 2207 |             # (usually `self`, or `cls`) will not be passed | 
 | 2208 |             # automatically (as for boundmethods) | 
| Yury Selivanov | da5fe4f | 2014-01-27 17:28:37 -0500 | [diff] [blame] | 2209 |  | 
| Yury Selivanov | 5a23bd0 | 2014-03-29 13:47:11 -0400 | [diff] [blame] | 2210 |             wrapped_sig = _signature_from_callable( | 
| Yury Selivanov | da39645 | 2014-03-27 12:09:24 -0400 | [diff] [blame] | 2211 |                 partialmethod.func, | 
 | 2212 |                 follow_wrapper_chains=follow_wrapper_chains, | 
 | 2213 |                 skip_bound_arg=skip_bound_arg, | 
 | 2214 |                 sigcls=sigcls) | 
 | 2215 |  | 
| Yury Selivanov | 0486f81 | 2014-01-29 12:18:59 -0500 | [diff] [blame] | 2216 |             sig = _signature_get_partial(wrapped_sig, partialmethod, (None,)) | 
| Yury Selivanov | da5fe4f | 2014-01-27 17:28:37 -0500 | [diff] [blame] | 2217 |  | 
| Yury Selivanov | 0486f81 | 2014-01-29 12:18:59 -0500 | [diff] [blame] | 2218 |             first_wrapped_param = tuple(wrapped_sig.parameters.values())[0] | 
 | 2219 |             new_params = (first_wrapped_param,) + tuple(sig.parameters.values()) | 
| Yury Selivanov | da5fe4f | 2014-01-27 17:28:37 -0500 | [diff] [blame] | 2220 |  | 
| Yury Selivanov | 0486f81 | 2014-01-29 12:18:59 -0500 | [diff] [blame] | 2221 |             return sig.replace(parameters=new_params) | 
| Yury Selivanov | da5fe4f | 2014-01-27 17:28:37 -0500 | [diff] [blame] | 2222 |  | 
| Yury Selivanov | 63da7c7 | 2014-01-31 14:48:37 -0500 | [diff] [blame] | 2223 |     if isfunction(obj) or _signature_is_functionlike(obj): | 
 | 2224 |         # If it's a pure Python function, or an object that is duck type | 
 | 2225 |         # of a Python function (Cython functions, for instance), then: | 
| Yury Selivanov | cf45f02 | 2015-05-20 14:38:50 -0400 | [diff] [blame] | 2226 |         return _signature_from_function(sigcls, obj) | 
| Larry Hastings | 7c7cbfc | 2012-06-22 15:19:35 -0700 | [diff] [blame] | 2227 |  | 
| Yury Selivanov | a773de0 | 2014-02-21 18:30:53 -0500 | [diff] [blame] | 2228 |     if _signature_is_builtin(obj): | 
| Yury Selivanov | da39645 | 2014-03-27 12:09:24 -0400 | [diff] [blame] | 2229 |         return _signature_from_builtin(sigcls, obj, | 
| Yury Selivanov | a773de0 | 2014-02-21 18:30:53 -0500 | [diff] [blame] | 2230 |                                        skip_bound_arg=skip_bound_arg) | 
 | 2231 |  | 
| Larry Hastings | 7c7cbfc | 2012-06-22 15:19:35 -0700 | [diff] [blame] | 2232 |     if isinstance(obj, functools.partial): | 
| Yury Selivanov | 5a23bd0 | 2014-03-29 13:47:11 -0400 | [diff] [blame] | 2233 |         wrapped_sig = _signature_from_callable( | 
| Yury Selivanov | da39645 | 2014-03-27 12:09:24 -0400 | [diff] [blame] | 2234 |             obj.func, | 
 | 2235 |             follow_wrapper_chains=follow_wrapper_chains, | 
 | 2236 |             skip_bound_arg=skip_bound_arg, | 
 | 2237 |             sigcls=sigcls) | 
| Yury Selivanov | 62560fb | 2014-01-28 12:26:24 -0500 | [diff] [blame] | 2238 |         return _signature_get_partial(wrapped_sig, obj) | 
| Larry Hastings | 7c7cbfc | 2012-06-22 15:19:35 -0700 | [diff] [blame] | 2239 |  | 
 | 2240 |     sig = None | 
 | 2241 |     if isinstance(obj, type): | 
 | 2242 |         # obj is a class or a metaclass | 
 | 2243 |  | 
 | 2244 |         # First, let's see if it has an overloaded __call__ defined | 
 | 2245 |         # in its metaclass | 
| Yury Selivanov | 421f0c7 | 2014-01-29 12:05:40 -0500 | [diff] [blame] | 2246 |         call = _signature_get_user_defined_method(type(obj), '__call__') | 
| Larry Hastings | 7c7cbfc | 2012-06-22 15:19:35 -0700 | [diff] [blame] | 2247 |         if call is not None: | 
| Yury Selivanov | 5a23bd0 | 2014-03-29 13:47:11 -0400 | [diff] [blame] | 2248 |             sig = _signature_from_callable( | 
| Yury Selivanov | da39645 | 2014-03-27 12:09:24 -0400 | [diff] [blame] | 2249 |                 call, | 
 | 2250 |                 follow_wrapper_chains=follow_wrapper_chains, | 
 | 2251 |                 skip_bound_arg=skip_bound_arg, | 
 | 2252 |                 sigcls=sigcls) | 
| Larry Hastings | 7c7cbfc | 2012-06-22 15:19:35 -0700 | [diff] [blame] | 2253 |         else: | 
 | 2254 |             # Now we check if the 'obj' class has a '__new__' method | 
| Yury Selivanov | 421f0c7 | 2014-01-29 12:05:40 -0500 | [diff] [blame] | 2255 |             new = _signature_get_user_defined_method(obj, '__new__') | 
| Larry Hastings | 7c7cbfc | 2012-06-22 15:19:35 -0700 | [diff] [blame] | 2256 |             if new is not None: | 
| Yury Selivanov | 5a23bd0 | 2014-03-29 13:47:11 -0400 | [diff] [blame] | 2257 |                 sig = _signature_from_callable( | 
| Yury Selivanov | da39645 | 2014-03-27 12:09:24 -0400 | [diff] [blame] | 2258 |                     new, | 
 | 2259 |                     follow_wrapper_chains=follow_wrapper_chains, | 
 | 2260 |                     skip_bound_arg=skip_bound_arg, | 
 | 2261 |                     sigcls=sigcls) | 
| Larry Hastings | 7c7cbfc | 2012-06-22 15:19:35 -0700 | [diff] [blame] | 2262 |             else: | 
 | 2263 |                 # Finally, we should have at least __init__ implemented | 
| Yury Selivanov | 421f0c7 | 2014-01-29 12:05:40 -0500 | [diff] [blame] | 2264 |                 init = _signature_get_user_defined_method(obj, '__init__') | 
| Larry Hastings | 7c7cbfc | 2012-06-22 15:19:35 -0700 | [diff] [blame] | 2265 |                 if init is not None: | 
| Yury Selivanov | 5a23bd0 | 2014-03-29 13:47:11 -0400 | [diff] [blame] | 2266 |                     sig = _signature_from_callable( | 
| Yury Selivanov | da39645 | 2014-03-27 12:09:24 -0400 | [diff] [blame] | 2267 |                         init, | 
 | 2268 |                         follow_wrapper_chains=follow_wrapper_chains, | 
 | 2269 |                         skip_bound_arg=skip_bound_arg, | 
 | 2270 |                         sigcls=sigcls) | 
| Yury Selivanov | e7dcc5e | 2014-01-27 19:29:45 -0500 | [diff] [blame] | 2271 |  | 
 | 2272 |         if sig is None: | 
| Yury Selivanov | 7d2bfed | 2014-02-03 02:46:07 -0500 | [diff] [blame] | 2273 |             # At this point we know, that `obj` is a class, with no user- | 
 | 2274 |             # defined '__init__', '__new__', or class-level '__call__' | 
 | 2275 |  | 
| Larry Hastings | 2623c8c | 2014-02-08 22:15:29 -0800 | [diff] [blame] | 2276 |             for base in obj.__mro__[:-1]: | 
| Yury Selivanov | 7d2bfed | 2014-02-03 02:46:07 -0500 | [diff] [blame] | 2277 |                 # Since '__text_signature__' is implemented as a | 
 | 2278 |                 # descriptor that extracts text signature from the | 
 | 2279 |                 # class docstring, if 'obj' is derived from a builtin | 
 | 2280 |                 # class, its own '__text_signature__' may be 'None'. | 
| Larry Hastings | 2623c8c | 2014-02-08 22:15:29 -0800 | [diff] [blame] | 2281 |                 # Therefore, we go through the MRO (except the last | 
 | 2282 |                 # class in there, which is 'object') to find the first | 
| Yury Selivanov | 7d2bfed | 2014-02-03 02:46:07 -0500 | [diff] [blame] | 2283 |                 # class with non-empty text signature. | 
 | 2284 |                 try: | 
 | 2285 |                     text_sig = base.__text_signature__ | 
 | 2286 |                 except AttributeError: | 
 | 2287 |                     pass | 
 | 2288 |                 else: | 
 | 2289 |                     if text_sig: | 
 | 2290 |                         # If 'obj' class has a __text_signature__ attribute: | 
 | 2291 |                         # return a signature based on it | 
| Yury Selivanov | da39645 | 2014-03-27 12:09:24 -0400 | [diff] [blame] | 2292 |                         return _signature_fromstr(sigcls, obj, text_sig) | 
| Yury Selivanov | 7d2bfed | 2014-02-03 02:46:07 -0500 | [diff] [blame] | 2293 |  | 
 | 2294 |             # No '__text_signature__' was found for the 'obj' class. | 
 | 2295 |             # Last option is to check if its '__init__' is | 
 | 2296 |             # object.__init__ or type.__init__. | 
| Larry Hastings | 2623c8c | 2014-02-08 22:15:29 -0800 | [diff] [blame] | 2297 |             if type not in obj.__mro__: | 
| Yury Selivanov | e7dcc5e | 2014-01-27 19:29:45 -0500 | [diff] [blame] | 2298 |                 # We have a class (not metaclass), but no user-defined | 
 | 2299 |                 # __init__ or __new__ for it | 
| Yury Selivanov | bf304fc | 2015-05-30 17:08:36 -0400 | [diff] [blame] | 2300 |                 if (obj.__init__ is object.__init__ and | 
 | 2301 |                     obj.__new__ is object.__new__): | 
| Yury Selivanov | 7d2bfed | 2014-02-03 02:46:07 -0500 | [diff] [blame] | 2302 |                     # Return a signature of 'object' builtin. | 
 | 2303 |                     return signature(object) | 
| Yury Selivanov | bf304fc | 2015-05-30 17:08:36 -0400 | [diff] [blame] | 2304 |                 else: | 
 | 2305 |                     raise ValueError( | 
 | 2306 |                         'no signature found for builtin type {!r}'.format(obj)) | 
| Yury Selivanov | e7dcc5e | 2014-01-27 19:29:45 -0500 | [diff] [blame] | 2307 |  | 
| Larry Hastings | 7c7cbfc | 2012-06-22 15:19:35 -0700 | [diff] [blame] | 2308 |     elif not isinstance(obj, _NonUserDefinedCallables): | 
 | 2309 |         # An object with __call__ | 
 | 2310 |         # We also check that the 'obj' is not an instance of | 
 | 2311 |         # _WrapperDescriptor or _MethodWrapper to avoid | 
 | 2312 |         # infinite recursion (and even potential segfault) | 
| Yury Selivanov | 421f0c7 | 2014-01-29 12:05:40 -0500 | [diff] [blame] | 2313 |         call = _signature_get_user_defined_method(type(obj), '__call__') | 
| Larry Hastings | 7c7cbfc | 2012-06-22 15:19:35 -0700 | [diff] [blame] | 2314 |         if call is not None: | 
| Larry Hastings | 2623c8c | 2014-02-08 22:15:29 -0800 | [diff] [blame] | 2315 |             try: | 
| Yury Selivanov | 5a23bd0 | 2014-03-29 13:47:11 -0400 | [diff] [blame] | 2316 |                 sig = _signature_from_callable( | 
| Yury Selivanov | da39645 | 2014-03-27 12:09:24 -0400 | [diff] [blame] | 2317 |                     call, | 
 | 2318 |                     follow_wrapper_chains=follow_wrapper_chains, | 
 | 2319 |                     skip_bound_arg=skip_bound_arg, | 
 | 2320 |                     sigcls=sigcls) | 
| Larry Hastings | 2623c8c | 2014-02-08 22:15:29 -0800 | [diff] [blame] | 2321 |             except ValueError as ex: | 
 | 2322 |                 msg = 'no signature found for {!r}'.format(obj) | 
 | 2323 |                 raise ValueError(msg) from ex | 
| Larry Hastings | 7c7cbfc | 2012-06-22 15:19:35 -0700 | [diff] [blame] | 2324 |  | 
 | 2325 |     if sig is not None: | 
 | 2326 |         # For classes and objects we skip the first parameter of their | 
 | 2327 |         # __call__, __new__, or __init__ methods | 
| Yury Selivanov | 57d240e | 2014-02-19 16:27:23 -0500 | [diff] [blame] | 2328 |         if skip_bound_arg: | 
 | 2329 |             return _signature_bound_method(sig) | 
 | 2330 |         else: | 
 | 2331 |             return sig | 
| Larry Hastings | 7c7cbfc | 2012-06-22 15:19:35 -0700 | [diff] [blame] | 2332 |  | 
 | 2333 |     if isinstance(obj, types.BuiltinFunctionType): | 
 | 2334 |         # Raise a nicer error message for builtins | 
 | 2335 |         msg = 'no signature found for builtin function {!r}'.format(obj) | 
 | 2336 |         raise ValueError(msg) | 
 | 2337 |  | 
 | 2338 |     raise ValueError('callable {!r} is not supported by signature'.format(obj)) | 
 | 2339 |  | 
 | 2340 |  | 
 | 2341 | class _void: | 
| Yury Selivanov | 5a23bd0 | 2014-03-29 13:47:11 -0400 | [diff] [blame] | 2342 |     """A private marker - used in Parameter & Signature.""" | 
| Larry Hastings | 7c7cbfc | 2012-06-22 15:19:35 -0700 | [diff] [blame] | 2343 |  | 
 | 2344 |  | 
 | 2345 | class _empty: | 
| Yury Selivanov | 5a23bd0 | 2014-03-29 13:47:11 -0400 | [diff] [blame] | 2346 |     """Marker object for Signature.empty and Parameter.empty.""" | 
| Larry Hastings | 7c7cbfc | 2012-06-22 15:19:35 -0700 | [diff] [blame] | 2347 |  | 
 | 2348 |  | 
| Yury Selivanov | 21e83a5 | 2014-03-27 11:23:13 -0400 | [diff] [blame] | 2349 | class _ParameterKind(enum.IntEnum): | 
 | 2350 |     POSITIONAL_ONLY = 0 | 
 | 2351 |     POSITIONAL_OR_KEYWORD = 1 | 
 | 2352 |     VAR_POSITIONAL = 2 | 
 | 2353 |     KEYWORD_ONLY = 3 | 
 | 2354 |     VAR_KEYWORD = 4 | 
| Larry Hastings | 7c7cbfc | 2012-06-22 15:19:35 -0700 | [diff] [blame] | 2355 |  | 
 | 2356 |     def __str__(self): | 
| Yury Selivanov | 21e83a5 | 2014-03-27 11:23:13 -0400 | [diff] [blame] | 2357 |         return self._name_ | 
| Larry Hastings | 7c7cbfc | 2012-06-22 15:19:35 -0700 | [diff] [blame] | 2358 |  | 
 | 2359 |  | 
| Yury Selivanov | 21e83a5 | 2014-03-27 11:23:13 -0400 | [diff] [blame] | 2360 | _POSITIONAL_ONLY         = _ParameterKind.POSITIONAL_ONLY | 
 | 2361 | _POSITIONAL_OR_KEYWORD   = _ParameterKind.POSITIONAL_OR_KEYWORD | 
 | 2362 | _VAR_POSITIONAL          = _ParameterKind.VAR_POSITIONAL | 
 | 2363 | _KEYWORD_ONLY            = _ParameterKind.KEYWORD_ONLY | 
 | 2364 | _VAR_KEYWORD             = _ParameterKind.VAR_KEYWORD | 
| Larry Hastings | 7c7cbfc | 2012-06-22 15:19:35 -0700 | [diff] [blame] | 2365 |  | 
 | 2366 |  | 
 | 2367 | class Parameter: | 
| Yury Selivanov | 5a23bd0 | 2014-03-29 13:47:11 -0400 | [diff] [blame] | 2368 |     """Represents a parameter in a function signature. | 
| Larry Hastings | 7c7cbfc | 2012-06-22 15:19:35 -0700 | [diff] [blame] | 2369 |  | 
 | 2370 |     Has the following public attributes: | 
 | 2371 |  | 
 | 2372 |     * name : str | 
 | 2373 |         The name of the parameter as a string. | 
 | 2374 |     * default : object | 
 | 2375 |         The default value for the parameter if specified.  If the | 
| Yury Selivanov | 8757ead | 2014-01-28 16:39:25 -0500 | [diff] [blame] | 2376 |         parameter has no default value, this attribute is set to | 
 | 2377 |         `Parameter.empty`. | 
| Larry Hastings | 7c7cbfc | 2012-06-22 15:19:35 -0700 | [diff] [blame] | 2378 |     * annotation | 
 | 2379 |         The annotation for the parameter if specified.  If the | 
| Yury Selivanov | 8757ead | 2014-01-28 16:39:25 -0500 | [diff] [blame] | 2380 |         parameter has no annotation, this attribute is set to | 
 | 2381 |         `Parameter.empty`. | 
| Larry Hastings | 7c7cbfc | 2012-06-22 15:19:35 -0700 | [diff] [blame] | 2382 |     * kind : str | 
 | 2383 |         Describes how argument values are bound to the parameter. | 
 | 2384 |         Possible values: `Parameter.POSITIONAL_ONLY`, | 
 | 2385 |         `Parameter.POSITIONAL_OR_KEYWORD`, `Parameter.VAR_POSITIONAL`, | 
 | 2386 |         `Parameter.KEYWORD_ONLY`, `Parameter.VAR_KEYWORD`. | 
| Yury Selivanov | 5a23bd0 | 2014-03-29 13:47:11 -0400 | [diff] [blame] | 2387 |     """ | 
| Larry Hastings | 7c7cbfc | 2012-06-22 15:19:35 -0700 | [diff] [blame] | 2388 |  | 
| Yury Selivanov | 3f73ca2 | 2014-04-08 11:30:45 -0400 | [diff] [blame] | 2389 |     __slots__ = ('_name', '_kind', '_default', '_annotation') | 
| Larry Hastings | 7c7cbfc | 2012-06-22 15:19:35 -0700 | [diff] [blame] | 2390 |  | 
 | 2391 |     POSITIONAL_ONLY         = _POSITIONAL_ONLY | 
 | 2392 |     POSITIONAL_OR_KEYWORD   = _POSITIONAL_OR_KEYWORD | 
 | 2393 |     VAR_POSITIONAL          = _VAR_POSITIONAL | 
 | 2394 |     KEYWORD_ONLY            = _KEYWORD_ONLY | 
 | 2395 |     VAR_KEYWORD             = _VAR_KEYWORD | 
 | 2396 |  | 
 | 2397 |     empty = _empty | 
 | 2398 |  | 
| Yury Selivanov | 3f73ca2 | 2014-04-08 11:30:45 -0400 | [diff] [blame] | 2399 |     def __init__(self, name, kind, *, default=_empty, annotation=_empty): | 
| Larry Hastings | 7c7cbfc | 2012-06-22 15:19:35 -0700 | [diff] [blame] | 2400 |  | 
 | 2401 |         if kind not in (_POSITIONAL_ONLY, _POSITIONAL_OR_KEYWORD, | 
 | 2402 |                         _VAR_POSITIONAL, _KEYWORD_ONLY, _VAR_KEYWORD): | 
 | 2403 |             raise ValueError("invalid value for 'Parameter.kind' attribute") | 
 | 2404 |         self._kind = kind | 
 | 2405 |  | 
 | 2406 |         if default is not _empty: | 
 | 2407 |             if kind in (_VAR_POSITIONAL, _VAR_KEYWORD): | 
 | 2408 |                 msg = '{} parameters cannot have default values'.format(kind) | 
 | 2409 |                 raise ValueError(msg) | 
 | 2410 |         self._default = default | 
 | 2411 |         self._annotation = annotation | 
 | 2412 |  | 
| Yury Selivanov | 2393dca | 2014-01-27 15:07:58 -0500 | [diff] [blame] | 2413 |         if name is _empty: | 
 | 2414 |             raise ValueError('name is a required attribute for Parameter') | 
 | 2415 |  | 
 | 2416 |         if not isinstance(name, str): | 
 | 2417 |             raise TypeError("name must be a str, not a {!r}".format(name)) | 
 | 2418 |  | 
 | 2419 |         if not name.isidentifier(): | 
 | 2420 |             raise ValueError('{!r} is not a valid parameter name'.format(name)) | 
 | 2421 |  | 
 | 2422 |         self._name = name | 
| Larry Hastings | 7c7cbfc | 2012-06-22 15:19:35 -0700 | [diff] [blame] | 2423 |  | 
| Yury Selivanov | a5d63dd | 2014-03-27 11:31:43 -0400 | [diff] [blame] | 2424 |     def __reduce__(self): | 
 | 2425 |         return (type(self), | 
 | 2426 |                 (self._name, self._kind), | 
| Yury Selivanov | 3f73ca2 | 2014-04-08 11:30:45 -0400 | [diff] [blame] | 2427 |                 {'_default': self._default, | 
| Yury Selivanov | a5d63dd | 2014-03-27 11:31:43 -0400 | [diff] [blame] | 2428 |                  '_annotation': self._annotation}) | 
 | 2429 |  | 
 | 2430 |     def __setstate__(self, state): | 
| Yury Selivanov | a5d63dd | 2014-03-27 11:31:43 -0400 | [diff] [blame] | 2431 |         self._default = state['_default'] | 
 | 2432 |         self._annotation = state['_annotation'] | 
 | 2433 |  | 
| Larry Hastings | 7c7cbfc | 2012-06-22 15:19:35 -0700 | [diff] [blame] | 2434 |     @property | 
 | 2435 |     def name(self): | 
 | 2436 |         return self._name | 
 | 2437 |  | 
 | 2438 |     @property | 
 | 2439 |     def default(self): | 
 | 2440 |         return self._default | 
 | 2441 |  | 
 | 2442 |     @property | 
 | 2443 |     def annotation(self): | 
 | 2444 |         return self._annotation | 
 | 2445 |  | 
 | 2446 |     @property | 
 | 2447 |     def kind(self): | 
 | 2448 |         return self._kind | 
 | 2449 |  | 
| Yury Selivanov | 3f73ca2 | 2014-04-08 11:30:45 -0400 | [diff] [blame] | 2450 |     def replace(self, *, name=_void, kind=_void, | 
 | 2451 |                 annotation=_void, default=_void): | 
| Yury Selivanov | 5a23bd0 | 2014-03-29 13:47:11 -0400 | [diff] [blame] | 2452 |         """Creates a customized copy of the Parameter.""" | 
| Larry Hastings | 7c7cbfc | 2012-06-22 15:19:35 -0700 | [diff] [blame] | 2453 |  | 
 | 2454 |         if name is _void: | 
 | 2455 |             name = self._name | 
 | 2456 |  | 
 | 2457 |         if kind is _void: | 
 | 2458 |             kind = self._kind | 
 | 2459 |  | 
 | 2460 |         if annotation is _void: | 
 | 2461 |             annotation = self._annotation | 
 | 2462 |  | 
 | 2463 |         if default is _void: | 
 | 2464 |             default = self._default | 
 | 2465 |  | 
| Yury Selivanov | 3f73ca2 | 2014-04-08 11:30:45 -0400 | [diff] [blame] | 2466 |         return type(self)(name, kind, default=default, annotation=annotation) | 
| Larry Hastings | 7c7cbfc | 2012-06-22 15:19:35 -0700 | [diff] [blame] | 2467 |  | 
 | 2468 |     def __str__(self): | 
 | 2469 |         kind = self.kind | 
| Larry Hastings | 7c7cbfc | 2012-06-22 15:19:35 -0700 | [diff] [blame] | 2470 |         formatted = self._name | 
| Larry Hastings | 7c7cbfc | 2012-06-22 15:19:35 -0700 | [diff] [blame] | 2471 |  | 
 | 2472 |         # Add annotation and default value | 
 | 2473 |         if self._annotation is not _empty: | 
 | 2474 |             formatted = '{}:{}'.format(formatted, | 
 | 2475 |                                        formatannotation(self._annotation)) | 
 | 2476 |  | 
 | 2477 |         if self._default is not _empty: | 
 | 2478 |             formatted = '{}={}'.format(formatted, repr(self._default)) | 
 | 2479 |  | 
 | 2480 |         if kind == _VAR_POSITIONAL: | 
 | 2481 |             formatted = '*' + formatted | 
 | 2482 |         elif kind == _VAR_KEYWORD: | 
 | 2483 |             formatted = '**' + formatted | 
 | 2484 |  | 
 | 2485 |         return formatted | 
 | 2486 |  | 
 | 2487 |     def __repr__(self): | 
| Yury Selivanov | f229bc5 | 2015-05-15 12:53:56 -0400 | [diff] [blame] | 2488 |         return '<{} "{}">'.format(self.__class__.__name__, self) | 
| Larry Hastings | 7c7cbfc | 2012-06-22 15:19:35 -0700 | [diff] [blame] | 2489 |  | 
| Yury Selivanov | 67ae50e | 2014-04-08 11:46:50 -0400 | [diff] [blame] | 2490 |     def __hash__(self): | 
| Yury Selivanov | 08d4a4f | 2014-09-12 15:48:02 -0400 | [diff] [blame] | 2491 |         return hash((self.name, self.kind, self.annotation, self.default)) | 
| Yury Selivanov | 67ae50e | 2014-04-08 11:46:50 -0400 | [diff] [blame] | 2492 |  | 
| Larry Hastings | 7c7cbfc | 2012-06-22 15:19:35 -0700 | [diff] [blame] | 2493 |     def __eq__(self, other): | 
| Serhiy Storchaka | 2489bd5 | 2015-07-18 23:20:50 +0300 | [diff] [blame] | 2494 |         if self is other: | 
 | 2495 |             return True | 
| Serhiy Storchaka | 3018cc4 | 2015-07-18 23:19:05 +0300 | [diff] [blame] | 2496 |         if not isinstance(other, Parameter): | 
 | 2497 |             return NotImplemented | 
 | 2498 |         return (self._name == other._name and | 
| Larry Hastings | 7c7cbfc | 2012-06-22 15:19:35 -0700 | [diff] [blame] | 2499 |                 self._kind == other._kind and | 
 | 2500 |                 self._default == other._default and | 
 | 2501 |                 self._annotation == other._annotation) | 
 | 2502 |  | 
| Larry Hastings | 7c7cbfc | 2012-06-22 15:19:35 -0700 | [diff] [blame] | 2503 |  | 
 | 2504 | class BoundArguments: | 
| Yury Selivanov | 5a23bd0 | 2014-03-29 13:47:11 -0400 | [diff] [blame] | 2505 |     """Result of `Signature.bind` call.  Holds the mapping of arguments | 
| Larry Hastings | 7c7cbfc | 2012-06-22 15:19:35 -0700 | [diff] [blame] | 2506 |     to the function's parameters. | 
 | 2507 |  | 
 | 2508 |     Has the following public attributes: | 
 | 2509 |  | 
 | 2510 |     * arguments : OrderedDict | 
 | 2511 |         An ordered mutable mapping of parameters' names to arguments' values. | 
 | 2512 |         Does not contain arguments' default values. | 
 | 2513 |     * signature : Signature | 
 | 2514 |         The Signature object that created this instance. | 
 | 2515 |     * args : tuple | 
 | 2516 |         Tuple of positional arguments values. | 
 | 2517 |     * kwargs : dict | 
 | 2518 |         Dict of keyword arguments values. | 
| Yury Selivanov | 5a23bd0 | 2014-03-29 13:47:11 -0400 | [diff] [blame] | 2519 |     """ | 
| Larry Hastings | 7c7cbfc | 2012-06-22 15:19:35 -0700 | [diff] [blame] | 2520 |  | 
| Yury Selivanov | 6abe032 | 2015-05-13 17:18:41 -0400 | [diff] [blame] | 2521 |     __slots__ = ('arguments', '_signature', '__weakref__') | 
 | 2522 |  | 
| Larry Hastings | 7c7cbfc | 2012-06-22 15:19:35 -0700 | [diff] [blame] | 2523 |     def __init__(self, signature, arguments): | 
 | 2524 |         self.arguments = arguments | 
 | 2525 |         self._signature = signature | 
 | 2526 |  | 
 | 2527 |     @property | 
 | 2528 |     def signature(self): | 
 | 2529 |         return self._signature | 
 | 2530 |  | 
 | 2531 |     @property | 
 | 2532 |     def args(self): | 
 | 2533 |         args = [] | 
 | 2534 |         for param_name, param in self._signature.parameters.items(): | 
| Yury Selivanov | 3f73ca2 | 2014-04-08 11:30:45 -0400 | [diff] [blame] | 2535 |             if param.kind in (_VAR_KEYWORD, _KEYWORD_ONLY): | 
| Larry Hastings | 7c7cbfc | 2012-06-22 15:19:35 -0700 | [diff] [blame] | 2536 |                 break | 
 | 2537 |  | 
 | 2538 |             try: | 
 | 2539 |                 arg = self.arguments[param_name] | 
 | 2540 |             except KeyError: | 
 | 2541 |                 # We're done here. Other arguments | 
 | 2542 |                 # will be mapped in 'BoundArguments.kwargs' | 
 | 2543 |                 break | 
 | 2544 |             else: | 
 | 2545 |                 if param.kind == _VAR_POSITIONAL: | 
 | 2546 |                     # *args | 
 | 2547 |                     args.extend(arg) | 
 | 2548 |                 else: | 
 | 2549 |                     # plain argument | 
 | 2550 |                     args.append(arg) | 
 | 2551 |  | 
 | 2552 |         return tuple(args) | 
 | 2553 |  | 
 | 2554 |     @property | 
 | 2555 |     def kwargs(self): | 
 | 2556 |         kwargs = {} | 
 | 2557 |         kwargs_started = False | 
 | 2558 |         for param_name, param in self._signature.parameters.items(): | 
 | 2559 |             if not kwargs_started: | 
| Yury Selivanov | 3f73ca2 | 2014-04-08 11:30:45 -0400 | [diff] [blame] | 2560 |                 if param.kind in (_VAR_KEYWORD, _KEYWORD_ONLY): | 
| Larry Hastings | 7c7cbfc | 2012-06-22 15:19:35 -0700 | [diff] [blame] | 2561 |                     kwargs_started = True | 
 | 2562 |                 else: | 
 | 2563 |                     if param_name not in self.arguments: | 
 | 2564 |                         kwargs_started = True | 
 | 2565 |                         continue | 
 | 2566 |  | 
 | 2567 |             if not kwargs_started: | 
 | 2568 |                 continue | 
 | 2569 |  | 
 | 2570 |             try: | 
 | 2571 |                 arg = self.arguments[param_name] | 
 | 2572 |             except KeyError: | 
 | 2573 |                 pass | 
 | 2574 |             else: | 
 | 2575 |                 if param.kind == _VAR_KEYWORD: | 
 | 2576 |                     # **kwargs | 
 | 2577 |                     kwargs.update(arg) | 
 | 2578 |                 else: | 
 | 2579 |                     # plain keyword argument | 
 | 2580 |                     kwargs[param_name] = arg | 
 | 2581 |  | 
 | 2582 |         return kwargs | 
 | 2583 |  | 
| Yury Selivanov | b907a51 | 2015-05-16 13:45:09 -0400 | [diff] [blame] | 2584 |     def apply_defaults(self): | 
 | 2585 |         """Set default values for missing arguments. | 
 | 2586 |  | 
 | 2587 |         For variable-positional arguments (*args) the default is an | 
 | 2588 |         empty tuple. | 
 | 2589 |  | 
 | 2590 |         For variable-keyword arguments (**kwargs) the default is an | 
 | 2591 |         empty dict. | 
 | 2592 |         """ | 
 | 2593 |         arguments = self.arguments | 
| Yury Selivanov | b907a51 | 2015-05-16 13:45:09 -0400 | [diff] [blame] | 2594 |         new_arguments = [] | 
 | 2595 |         for name, param in self._signature.parameters.items(): | 
 | 2596 |             try: | 
 | 2597 |                 new_arguments.append((name, arguments[name])) | 
 | 2598 |             except KeyError: | 
 | 2599 |                 if param.default is not _empty: | 
 | 2600 |                     val = param.default | 
 | 2601 |                 elif param.kind is _VAR_POSITIONAL: | 
 | 2602 |                     val = () | 
 | 2603 |                 elif param.kind is _VAR_KEYWORD: | 
 | 2604 |                     val = {} | 
 | 2605 |                 else: | 
 | 2606 |                     # This BoundArguments was likely produced by | 
 | 2607 |                     # Signature.bind_partial(). | 
 | 2608 |                     continue | 
 | 2609 |                 new_arguments.append((name, val)) | 
 | 2610 |         self.arguments = OrderedDict(new_arguments) | 
 | 2611 |  | 
| Larry Hastings | 7c7cbfc | 2012-06-22 15:19:35 -0700 | [diff] [blame] | 2612 |     def __eq__(self, other): | 
| Serhiy Storchaka | 2489bd5 | 2015-07-18 23:20:50 +0300 | [diff] [blame] | 2613 |         if self is other: | 
 | 2614 |             return True | 
| Serhiy Storchaka | 3018cc4 | 2015-07-18 23:19:05 +0300 | [diff] [blame] | 2615 |         if not isinstance(other, BoundArguments): | 
 | 2616 |             return NotImplemented | 
 | 2617 |         return (self.signature == other.signature and | 
| Larry Hastings | 7c7cbfc | 2012-06-22 15:19:35 -0700 | [diff] [blame] | 2618 |                 self.arguments == other.arguments) | 
 | 2619 |  | 
| Yury Selivanov | 6abe032 | 2015-05-13 17:18:41 -0400 | [diff] [blame] | 2620 |     def __setstate__(self, state): | 
 | 2621 |         self._signature = state['_signature'] | 
 | 2622 |         self.arguments = state['arguments'] | 
 | 2623 |  | 
 | 2624 |     def __getstate__(self): | 
 | 2625 |         return {'_signature': self._signature, 'arguments': self.arguments} | 
 | 2626 |  | 
| Yury Selivanov | 3f6538f | 2015-05-14 18:47:17 -0400 | [diff] [blame] | 2627 |     def __repr__(self): | 
 | 2628 |         args = [] | 
 | 2629 |         for arg, value in self.arguments.items(): | 
 | 2630 |             args.append('{}={!r}'.format(arg, value)) | 
| Yury Selivanov | f229bc5 | 2015-05-15 12:53:56 -0400 | [diff] [blame] | 2631 |         return '<{} ({})>'.format(self.__class__.__name__, ', '.join(args)) | 
| Yury Selivanov | 3f6538f | 2015-05-14 18:47:17 -0400 | [diff] [blame] | 2632 |  | 
| Larry Hastings | 7c7cbfc | 2012-06-22 15:19:35 -0700 | [diff] [blame] | 2633 |  | 
 | 2634 | class Signature: | 
| Yury Selivanov | 5a23bd0 | 2014-03-29 13:47:11 -0400 | [diff] [blame] | 2635 |     """A Signature object represents the overall signature of a function. | 
| Larry Hastings | 7c7cbfc | 2012-06-22 15:19:35 -0700 | [diff] [blame] | 2636 |     It stores a Parameter object for each parameter accepted by the | 
 | 2637 |     function, as well as information specific to the function itself. | 
 | 2638 |  | 
 | 2639 |     A Signature object has the following public attributes and methods: | 
 | 2640 |  | 
 | 2641 |     * parameters : OrderedDict | 
 | 2642 |         An ordered mapping of parameters' names to the corresponding | 
 | 2643 |         Parameter objects (keyword-only arguments are in the same order | 
 | 2644 |         as listed in `code.co_varnames`). | 
 | 2645 |     * return_annotation : object | 
 | 2646 |         The annotation for the return type of the function if specified. | 
 | 2647 |         If the function has no annotation for its return type, this | 
| Yury Selivanov | 8757ead | 2014-01-28 16:39:25 -0500 | [diff] [blame] | 2648 |         attribute is set to `Signature.empty`. | 
| Larry Hastings | 7c7cbfc | 2012-06-22 15:19:35 -0700 | [diff] [blame] | 2649 |     * bind(*args, **kwargs) -> BoundArguments | 
 | 2650 |         Creates a mapping from positional and keyword arguments to | 
 | 2651 |         parameters. | 
 | 2652 |     * bind_partial(*args, **kwargs) -> BoundArguments | 
 | 2653 |         Creates a partial mapping from positional and keyword arguments | 
 | 2654 |         to parameters (simulating 'functools.partial' behavior.) | 
| Yury Selivanov | 5a23bd0 | 2014-03-29 13:47:11 -0400 | [diff] [blame] | 2655 |     """ | 
| Larry Hastings | 7c7cbfc | 2012-06-22 15:19:35 -0700 | [diff] [blame] | 2656 |  | 
 | 2657 |     __slots__ = ('_return_annotation', '_parameters') | 
 | 2658 |  | 
 | 2659 |     _parameter_cls = Parameter | 
 | 2660 |     _bound_arguments_cls = BoundArguments | 
 | 2661 |  | 
 | 2662 |     empty = _empty | 
 | 2663 |  | 
 | 2664 |     def __init__(self, parameters=None, *, return_annotation=_empty, | 
 | 2665 |                  __validate_parameters__=True): | 
| Yury Selivanov | 5a23bd0 | 2014-03-29 13:47:11 -0400 | [diff] [blame] | 2666 |         """Constructs Signature from the given list of Parameter | 
| Larry Hastings | 7c7cbfc | 2012-06-22 15:19:35 -0700 | [diff] [blame] | 2667 |         objects and 'return_annotation'.  All arguments are optional. | 
| Yury Selivanov | 5a23bd0 | 2014-03-29 13:47:11 -0400 | [diff] [blame] | 2668 |         """ | 
| Larry Hastings | 7c7cbfc | 2012-06-22 15:19:35 -0700 | [diff] [blame] | 2669 |  | 
 | 2670 |         if parameters is None: | 
 | 2671 |             params = OrderedDict() | 
 | 2672 |         else: | 
 | 2673 |             if __validate_parameters__: | 
 | 2674 |                 params = OrderedDict() | 
 | 2675 |                 top_kind = _POSITIONAL_ONLY | 
| Yury Selivanov | 07a9e45 | 2014-01-29 10:58:16 -0500 | [diff] [blame] | 2676 |                 kind_defaults = False | 
| Larry Hastings | 7c7cbfc | 2012-06-22 15:19:35 -0700 | [diff] [blame] | 2677 |  | 
 | 2678 |                 for idx, param in enumerate(parameters): | 
 | 2679 |                     kind = param.kind | 
| Yury Selivanov | 2393dca | 2014-01-27 15:07:58 -0500 | [diff] [blame] | 2680 |                     name = param.name | 
 | 2681 |  | 
| Larry Hastings | 7c7cbfc | 2012-06-22 15:19:35 -0700 | [diff] [blame] | 2682 |                     if kind < top_kind: | 
| Yury Selivanov | 3f73ca2 | 2014-04-08 11:30:45 -0400 | [diff] [blame] | 2683 |                         msg = 'wrong parameter order: {!r} before {!r}' | 
| Yury Selivanov | 2393dca | 2014-01-27 15:07:58 -0500 | [diff] [blame] | 2684 |                         msg = msg.format(top_kind, kind) | 
| Larry Hastings | 7c7cbfc | 2012-06-22 15:19:35 -0700 | [diff] [blame] | 2685 |                         raise ValueError(msg) | 
| Yury Selivanov | 07a9e45 | 2014-01-29 10:58:16 -0500 | [diff] [blame] | 2686 |                     elif kind > top_kind: | 
 | 2687 |                         kind_defaults = False | 
| Larry Hastings | 7c7cbfc | 2012-06-22 15:19:35 -0700 | [diff] [blame] | 2688 |                         top_kind = kind | 
 | 2689 |  | 
| Yury Selivanov | 3f73ca2 | 2014-04-08 11:30:45 -0400 | [diff] [blame] | 2690 |                     if kind in (_POSITIONAL_ONLY, _POSITIONAL_OR_KEYWORD): | 
| Yury Selivanov | 07a9e45 | 2014-01-29 10:58:16 -0500 | [diff] [blame] | 2691 |                         if param.default is _empty: | 
 | 2692 |                             if kind_defaults: | 
 | 2693 |                                 # No default for this parameter, but the | 
 | 2694 |                                 # previous parameter of the same kind had | 
 | 2695 |                                 # a default | 
 | 2696 |                                 msg = 'non-default argument follows default ' \ | 
 | 2697 |                                       'argument' | 
 | 2698 |                                 raise ValueError(msg) | 
 | 2699 |                         else: | 
 | 2700 |                             # There is a default for this parameter. | 
 | 2701 |                             kind_defaults = True | 
 | 2702 |  | 
| Larry Hastings | 7c7cbfc | 2012-06-22 15:19:35 -0700 | [diff] [blame] | 2703 |                     if name in params: | 
 | 2704 |                         msg = 'duplicate parameter name: {!r}'.format(name) | 
 | 2705 |                         raise ValueError(msg) | 
| Yury Selivanov | 2393dca | 2014-01-27 15:07:58 -0500 | [diff] [blame] | 2706 |  | 
| Larry Hastings | 7c7cbfc | 2012-06-22 15:19:35 -0700 | [diff] [blame] | 2707 |                     params[name] = param | 
 | 2708 |             else: | 
 | 2709 |                 params = OrderedDict(((param.name, param) | 
 | 2710 |                                                 for param in parameters)) | 
 | 2711 |  | 
 | 2712 |         self._parameters = types.MappingProxyType(params) | 
 | 2713 |         self._return_annotation = return_annotation | 
 | 2714 |  | 
 | 2715 |     @classmethod | 
 | 2716 |     def from_function(cls, func): | 
| Yury Selivanov | 5a23bd0 | 2014-03-29 13:47:11 -0400 | [diff] [blame] | 2717 |         """Constructs Signature for the given python function.""" | 
| Yury Selivanov | 57c74fc | 2015-05-20 23:07:02 -0400 | [diff] [blame] | 2718 |  | 
 | 2719 |         warnings.warn("inspect.Signature.from_function() is deprecated, " | 
| Berker Peksag | b560158 | 2015-05-21 23:40:54 +0300 | [diff] [blame] | 2720 |                       "use Signature.from_callable()", | 
 | 2721 |                       DeprecationWarning, stacklevel=2) | 
| Yury Selivanov | cf45f02 | 2015-05-20 14:38:50 -0400 | [diff] [blame] | 2722 |         return _signature_from_function(cls, func) | 
| Larry Hastings | 7c7cbfc | 2012-06-22 15:19:35 -0700 | [diff] [blame] | 2723 |  | 
| Larry Hastings | 44e2eaa | 2013-11-23 15:37:55 -0800 | [diff] [blame] | 2724 |     @classmethod | 
 | 2725 |     def from_builtin(cls, func): | 
| Yury Selivanov | 5a23bd0 | 2014-03-29 13:47:11 -0400 | [diff] [blame] | 2726 |         """Constructs Signature for the given builtin function.""" | 
| Yury Selivanov | 57c74fc | 2015-05-20 23:07:02 -0400 | [diff] [blame] | 2727 |  | 
 | 2728 |         warnings.warn("inspect.Signature.from_builtin() is deprecated, " | 
| Berker Peksag | b560158 | 2015-05-21 23:40:54 +0300 | [diff] [blame] | 2729 |                       "use Signature.from_callable()", | 
 | 2730 |                       DeprecationWarning, stacklevel=2) | 
| Yury Selivanov | 57d240e | 2014-02-19 16:27:23 -0500 | [diff] [blame] | 2731 |         return _signature_from_builtin(cls, func) | 
| Larry Hastings | 44e2eaa | 2013-11-23 15:37:55 -0800 | [diff] [blame] | 2732 |  | 
| Yury Selivanov | da39645 | 2014-03-27 12:09:24 -0400 | [diff] [blame] | 2733 |     @classmethod | 
| Yury Selivanov | bcd4fc1 | 2015-05-20 14:30:08 -0400 | [diff] [blame] | 2734 |     def from_callable(cls, obj, *, follow_wrapped=True): | 
| Yury Selivanov | 5a23bd0 | 2014-03-29 13:47:11 -0400 | [diff] [blame] | 2735 |         """Constructs Signature for the given callable object.""" | 
| Yury Selivanov | bcd4fc1 | 2015-05-20 14:30:08 -0400 | [diff] [blame] | 2736 |         return _signature_from_callable(obj, sigcls=cls, | 
 | 2737 |                                         follow_wrapper_chains=follow_wrapped) | 
| Yury Selivanov | da39645 | 2014-03-27 12:09:24 -0400 | [diff] [blame] | 2738 |  | 
| Larry Hastings | 7c7cbfc | 2012-06-22 15:19:35 -0700 | [diff] [blame] | 2739 |     @property | 
 | 2740 |     def parameters(self): | 
 | 2741 |         return self._parameters | 
 | 2742 |  | 
 | 2743 |     @property | 
 | 2744 |     def return_annotation(self): | 
 | 2745 |         return self._return_annotation | 
 | 2746 |  | 
 | 2747 |     def replace(self, *, parameters=_void, return_annotation=_void): | 
| Yury Selivanov | 5a23bd0 | 2014-03-29 13:47:11 -0400 | [diff] [blame] | 2748 |         """Creates a customized copy of the Signature. | 
| Larry Hastings | 7c7cbfc | 2012-06-22 15:19:35 -0700 | [diff] [blame] | 2749 |         Pass 'parameters' and/or 'return_annotation' arguments | 
 | 2750 |         to override them in the new copy. | 
| Yury Selivanov | 5a23bd0 | 2014-03-29 13:47:11 -0400 | [diff] [blame] | 2751 |         """ | 
| Larry Hastings | 7c7cbfc | 2012-06-22 15:19:35 -0700 | [diff] [blame] | 2752 |  | 
 | 2753 |         if parameters is _void: | 
 | 2754 |             parameters = self.parameters.values() | 
 | 2755 |  | 
 | 2756 |         if return_annotation is _void: | 
 | 2757 |             return_annotation = self._return_annotation | 
 | 2758 |  | 
 | 2759 |         return type(self)(parameters, | 
 | 2760 |                           return_annotation=return_annotation) | 
 | 2761 |  | 
| Yury Selivanov | 08d4a4f | 2014-09-12 15:48:02 -0400 | [diff] [blame] | 2762 |     def _hash_basis(self): | 
 | 2763 |         params = tuple(param for param in self.parameters.values() | 
 | 2764 |                              if param.kind != _KEYWORD_ONLY) | 
 | 2765 |  | 
 | 2766 |         kwo_params = {param.name: param for param in self.parameters.values() | 
 | 2767 |                                         if param.kind == _KEYWORD_ONLY} | 
 | 2768 |  | 
 | 2769 |         return params, kwo_params, self.return_annotation | 
 | 2770 |  | 
| Yury Selivanov | 67ae50e | 2014-04-08 11:46:50 -0400 | [diff] [blame] | 2771 |     def __hash__(self): | 
| Yury Selivanov | 08d4a4f | 2014-09-12 15:48:02 -0400 | [diff] [blame] | 2772 |         params, kwo_params, return_annotation = self._hash_basis() | 
 | 2773 |         kwo_params = frozenset(kwo_params.values()) | 
 | 2774 |         return hash((params, kwo_params, return_annotation)) | 
| Yury Selivanov | 67ae50e | 2014-04-08 11:46:50 -0400 | [diff] [blame] | 2775 |  | 
| Larry Hastings | 7c7cbfc | 2012-06-22 15:19:35 -0700 | [diff] [blame] | 2776 |     def __eq__(self, other): | 
| Serhiy Storchaka | 2489bd5 | 2015-07-18 23:20:50 +0300 | [diff] [blame] | 2777 |         if self is other: | 
 | 2778 |             return True | 
| Serhiy Storchaka | 3018cc4 | 2015-07-18 23:19:05 +0300 | [diff] [blame] | 2779 |         if not isinstance(other, Signature): | 
 | 2780 |             return NotImplemented | 
| Serhiy Storchaka | 2489bd5 | 2015-07-18 23:20:50 +0300 | [diff] [blame] | 2781 |         return self._hash_basis() == other._hash_basis() | 
| Larry Hastings | 7c7cbfc | 2012-06-22 15:19:35 -0700 | [diff] [blame] | 2782 |  | 
| Larry Hastings | 7c7cbfc | 2012-06-22 15:19:35 -0700 | [diff] [blame] | 2783 |     def _bind(self, args, kwargs, *, partial=False): | 
| Yury Selivanov | 5a23bd0 | 2014-03-29 13:47:11 -0400 | [diff] [blame] | 2784 |         """Private method. Don't use directly.""" | 
| Larry Hastings | 7c7cbfc | 2012-06-22 15:19:35 -0700 | [diff] [blame] | 2785 |  | 
 | 2786 |         arguments = OrderedDict() | 
 | 2787 |  | 
 | 2788 |         parameters = iter(self.parameters.values()) | 
 | 2789 |         parameters_ex = () | 
 | 2790 |         arg_vals = iter(args) | 
 | 2791 |  | 
| Larry Hastings | 7c7cbfc | 2012-06-22 15:19:35 -0700 | [diff] [blame] | 2792 |         while True: | 
 | 2793 |             # Let's iterate through the positional arguments and corresponding | 
 | 2794 |             # parameters | 
 | 2795 |             try: | 
 | 2796 |                 arg_val = next(arg_vals) | 
 | 2797 |             except StopIteration: | 
 | 2798 |                 # No more positional arguments | 
 | 2799 |                 try: | 
 | 2800 |                     param = next(parameters) | 
 | 2801 |                 except StopIteration: | 
 | 2802 |                     # No more parameters. That's it. Just need to check that | 
 | 2803 |                     # we have no `kwargs` after this while loop | 
 | 2804 |                     break | 
 | 2805 |                 else: | 
 | 2806 |                     if param.kind == _VAR_POSITIONAL: | 
 | 2807 |                         # That's OK, just empty *args.  Let's start parsing | 
 | 2808 |                         # kwargs | 
 | 2809 |                         break | 
 | 2810 |                     elif param.name in kwargs: | 
 | 2811 |                         if param.kind == _POSITIONAL_ONLY: | 
 | 2812 |                             msg = '{arg!r} parameter is positional only, ' \ | 
 | 2813 |                                   'but was passed as a keyword' | 
 | 2814 |                             msg = msg.format(arg=param.name) | 
 | 2815 |                             raise TypeError(msg) from None | 
 | 2816 |                         parameters_ex = (param,) | 
 | 2817 |                         break | 
 | 2818 |                     elif (param.kind == _VAR_KEYWORD or | 
 | 2819 |                                                 param.default is not _empty): | 
 | 2820 |                         # That's fine too - we have a default value for this | 
 | 2821 |                         # parameter.  So, lets start parsing `kwargs`, starting | 
 | 2822 |                         # with the current parameter | 
 | 2823 |                         parameters_ex = (param,) | 
 | 2824 |                         break | 
 | 2825 |                     else: | 
| Yury Selivanov | 38b0d5a | 2014-01-28 17:27:39 -0500 | [diff] [blame] | 2826 |                         # No default, not VAR_KEYWORD, not VAR_POSITIONAL, | 
 | 2827 |                         # not in `kwargs` | 
| Larry Hastings | 7c7cbfc | 2012-06-22 15:19:35 -0700 | [diff] [blame] | 2828 |                         if partial: | 
 | 2829 |                             parameters_ex = (param,) | 
 | 2830 |                             break | 
 | 2831 |                         else: | 
| Yury Selivanov | 8687275 | 2015-05-19 00:27:49 -0400 | [diff] [blame] | 2832 |                             msg = 'missing a required argument: {arg!r}' | 
| Larry Hastings | 7c7cbfc | 2012-06-22 15:19:35 -0700 | [diff] [blame] | 2833 |                             msg = msg.format(arg=param.name) | 
 | 2834 |                             raise TypeError(msg) from None | 
 | 2835 |             else: | 
 | 2836 |                 # We have a positional argument to process | 
 | 2837 |                 try: | 
 | 2838 |                     param = next(parameters) | 
 | 2839 |                 except StopIteration: | 
 | 2840 |                     raise TypeError('too many positional arguments') from None | 
 | 2841 |                 else: | 
 | 2842 |                     if param.kind in (_VAR_KEYWORD, _KEYWORD_ONLY): | 
 | 2843 |                         # Looks like we have no parameter for this positional | 
 | 2844 |                         # argument | 
| Yury Selivanov | 8687275 | 2015-05-19 00:27:49 -0400 | [diff] [blame] | 2845 |                         raise TypeError( | 
 | 2846 |                             'too many positional arguments') from None | 
| Larry Hastings | 7c7cbfc | 2012-06-22 15:19:35 -0700 | [diff] [blame] | 2847 |  | 
 | 2848 |                     if param.kind == _VAR_POSITIONAL: | 
 | 2849 |                         # We have an '*args'-like argument, let's fill it with | 
 | 2850 |                         # all positional arguments we have left and move on to | 
 | 2851 |                         # the next phase | 
 | 2852 |                         values = [arg_val] | 
 | 2853 |                         values.extend(arg_vals) | 
 | 2854 |                         arguments[param.name] = tuple(values) | 
 | 2855 |                         break | 
 | 2856 |  | 
 | 2857 |                     if param.name in kwargs: | 
| Yury Selivanov | 8687275 | 2015-05-19 00:27:49 -0400 | [diff] [blame] | 2858 |                         raise TypeError( | 
 | 2859 |                             'multiple values for argument {arg!r}'.format( | 
 | 2860 |                                 arg=param.name)) from None | 
| Larry Hastings | 7c7cbfc | 2012-06-22 15:19:35 -0700 | [diff] [blame] | 2861 |  | 
 | 2862 |                     arguments[param.name] = arg_val | 
 | 2863 |  | 
 | 2864 |         # Now, we iterate through the remaining parameters to process | 
 | 2865 |         # keyword arguments | 
 | 2866 |         kwargs_param = None | 
 | 2867 |         for param in itertools.chain(parameters_ex, parameters): | 
| Larry Hastings | 7c7cbfc | 2012-06-22 15:19:35 -0700 | [diff] [blame] | 2868 |             if param.kind == _VAR_KEYWORD: | 
 | 2869 |                 # Memorize that we have a '**kwargs'-like parameter | 
 | 2870 |                 kwargs_param = param | 
 | 2871 |                 continue | 
 | 2872 |  | 
| Yury Selivanov | 38b0d5a | 2014-01-28 17:27:39 -0500 | [diff] [blame] | 2873 |             if param.kind == _VAR_POSITIONAL: | 
 | 2874 |                 # Named arguments don't refer to '*args'-like parameters. | 
 | 2875 |                 # We only arrive here if the positional arguments ended | 
 | 2876 |                 # before reaching the last parameter before *args. | 
 | 2877 |                 continue | 
 | 2878 |  | 
| Larry Hastings | 7c7cbfc | 2012-06-22 15:19:35 -0700 | [diff] [blame] | 2879 |             param_name = param.name | 
 | 2880 |             try: | 
 | 2881 |                 arg_val = kwargs.pop(param_name) | 
 | 2882 |             except KeyError: | 
 | 2883 |                 # We have no value for this parameter.  It's fine though, | 
 | 2884 |                 # if it has a default value, or it is an '*args'-like | 
 | 2885 |                 # parameter, left alone by the processing of positional | 
 | 2886 |                 # arguments. | 
 | 2887 |                 if (not partial and param.kind != _VAR_POSITIONAL and | 
 | 2888 |                                                     param.default is _empty): | 
| Yury Selivanov | 8687275 | 2015-05-19 00:27:49 -0400 | [diff] [blame] | 2889 |                     raise TypeError('missing a required argument: {arg!r}'. \ | 
| Larry Hastings | 7c7cbfc | 2012-06-22 15:19:35 -0700 | [diff] [blame] | 2890 |                                     format(arg=param_name)) from None | 
 | 2891 |  | 
 | 2892 |             else: | 
| Yury Selivanov | 9b9ac95 | 2014-01-28 20:54:28 -0500 | [diff] [blame] | 2893 |                 if param.kind == _POSITIONAL_ONLY: | 
 | 2894 |                     # This should never happen in case of a properly built | 
 | 2895 |                     # Signature object (but let's have this check here | 
 | 2896 |                     # to ensure correct behaviour just in case) | 
 | 2897 |                     raise TypeError('{arg!r} parameter is positional only, ' | 
 | 2898 |                                     'but was passed as a keyword'. \ | 
 | 2899 |                                     format(arg=param.name)) | 
 | 2900 |  | 
| Larry Hastings | 7c7cbfc | 2012-06-22 15:19:35 -0700 | [diff] [blame] | 2901 |                 arguments[param_name] = arg_val | 
 | 2902 |  | 
 | 2903 |         if kwargs: | 
 | 2904 |             if kwargs_param is not None: | 
 | 2905 |                 # Process our '**kwargs'-like parameter | 
 | 2906 |                 arguments[kwargs_param.name] = kwargs | 
 | 2907 |             else: | 
| Yury Selivanov | 8687275 | 2015-05-19 00:27:49 -0400 | [diff] [blame] | 2908 |                 raise TypeError( | 
 | 2909 |                     'got an unexpected keyword argument {arg!r}'.format( | 
 | 2910 |                         arg=next(iter(kwargs)))) | 
| Larry Hastings | 7c7cbfc | 2012-06-22 15:19:35 -0700 | [diff] [blame] | 2911 |  | 
 | 2912 |         return self._bound_arguments_cls(self, arguments) | 
 | 2913 |  | 
| Yury Selivanov | c45873e | 2014-01-29 12:10:27 -0500 | [diff] [blame] | 2914 |     def bind(*args, **kwargs): | 
| Yury Selivanov | 5a23bd0 | 2014-03-29 13:47:11 -0400 | [diff] [blame] | 2915 |         """Get a BoundArguments object, that maps the passed `args` | 
| Larry Hastings | 7c7cbfc | 2012-06-22 15:19:35 -0700 | [diff] [blame] | 2916 |         and `kwargs` to the function's signature.  Raises `TypeError` | 
 | 2917 |         if the passed arguments can not be bound. | 
| Yury Selivanov | 5a23bd0 | 2014-03-29 13:47:11 -0400 | [diff] [blame] | 2918 |         """ | 
| Yury Selivanov | c45873e | 2014-01-29 12:10:27 -0500 | [diff] [blame] | 2919 |         return args[0]._bind(args[1:], kwargs) | 
| Larry Hastings | 7c7cbfc | 2012-06-22 15:19:35 -0700 | [diff] [blame] | 2920 |  | 
| Yury Selivanov | c45873e | 2014-01-29 12:10:27 -0500 | [diff] [blame] | 2921 |     def bind_partial(*args, **kwargs): | 
| Yury Selivanov | 5a23bd0 | 2014-03-29 13:47:11 -0400 | [diff] [blame] | 2922 |         """Get a BoundArguments object, that partially maps the | 
| Larry Hastings | 7c7cbfc | 2012-06-22 15:19:35 -0700 | [diff] [blame] | 2923 |         passed `args` and `kwargs` to the function's signature. | 
 | 2924 |         Raises `TypeError` if the passed arguments can not be bound. | 
| Yury Selivanov | 5a23bd0 | 2014-03-29 13:47:11 -0400 | [diff] [blame] | 2925 |         """ | 
| Yury Selivanov | c45873e | 2014-01-29 12:10:27 -0500 | [diff] [blame] | 2926 |         return args[0]._bind(args[1:], kwargs, partial=True) | 
| Larry Hastings | 7c7cbfc | 2012-06-22 15:19:35 -0700 | [diff] [blame] | 2927 |  | 
| Yury Selivanov | a5d63dd | 2014-03-27 11:31:43 -0400 | [diff] [blame] | 2928 |     def __reduce__(self): | 
 | 2929 |         return (type(self), | 
 | 2930 |                 (tuple(self._parameters.values()),), | 
 | 2931 |                 {'_return_annotation': self._return_annotation}) | 
 | 2932 |  | 
 | 2933 |     def __setstate__(self, state): | 
 | 2934 |         self._return_annotation = state['_return_annotation'] | 
 | 2935 |  | 
| Yury Selivanov | 374375d | 2014-03-27 12:41:53 -0400 | [diff] [blame] | 2936 |     def __repr__(self): | 
| Yury Selivanov | f229bc5 | 2015-05-15 12:53:56 -0400 | [diff] [blame] | 2937 |         return '<{} {}>'.format(self.__class__.__name__, self) | 
| Yury Selivanov | 374375d | 2014-03-27 12:41:53 -0400 | [diff] [blame] | 2938 |  | 
| Larry Hastings | 7c7cbfc | 2012-06-22 15:19:35 -0700 | [diff] [blame] | 2939 |     def __str__(self): | 
 | 2940 |         result = [] | 
| Yury Selivanov | 2393dca | 2014-01-27 15:07:58 -0500 | [diff] [blame] | 2941 |         render_pos_only_separator = False | 
| Larry Hastings | 7c7cbfc | 2012-06-22 15:19:35 -0700 | [diff] [blame] | 2942 |         render_kw_only_separator = True | 
| Yury Selivanov | 2393dca | 2014-01-27 15:07:58 -0500 | [diff] [blame] | 2943 |         for param in self.parameters.values(): | 
| Larry Hastings | 7c7cbfc | 2012-06-22 15:19:35 -0700 | [diff] [blame] | 2944 |             formatted = str(param) | 
 | 2945 |  | 
 | 2946 |             kind = param.kind | 
| Yury Selivanov | 2393dca | 2014-01-27 15:07:58 -0500 | [diff] [blame] | 2947 |  | 
 | 2948 |             if kind == _POSITIONAL_ONLY: | 
 | 2949 |                 render_pos_only_separator = True | 
 | 2950 |             elif render_pos_only_separator: | 
 | 2951 |                 # It's not a positional-only parameter, and the flag | 
 | 2952 |                 # is set to 'True' (there were pos-only params before.) | 
 | 2953 |                 result.append('/') | 
 | 2954 |                 render_pos_only_separator = False | 
 | 2955 |  | 
| Larry Hastings | 7c7cbfc | 2012-06-22 15:19:35 -0700 | [diff] [blame] | 2956 |             if kind == _VAR_POSITIONAL: | 
 | 2957 |                 # OK, we have an '*args'-like parameter, so we won't need | 
 | 2958 |                 # a '*' to separate keyword-only arguments | 
 | 2959 |                 render_kw_only_separator = False | 
 | 2960 |             elif kind == _KEYWORD_ONLY and render_kw_only_separator: | 
 | 2961 |                 # We have a keyword-only parameter to render and we haven't | 
 | 2962 |                 # rendered an '*args'-like parameter before, so add a '*' | 
 | 2963 |                 # separator to the parameters list ("foo(arg1, *, arg2)" case) | 
 | 2964 |                 result.append('*') | 
 | 2965 |                 # This condition should be only triggered once, so | 
 | 2966 |                 # reset the flag | 
 | 2967 |                 render_kw_only_separator = False | 
 | 2968 |  | 
 | 2969 |             result.append(formatted) | 
 | 2970 |  | 
| Yury Selivanov | 2393dca | 2014-01-27 15:07:58 -0500 | [diff] [blame] | 2971 |         if render_pos_only_separator: | 
 | 2972 |             # There were only positional-only parameters, hence the | 
 | 2973 |             # flag was not reset to 'False' | 
 | 2974 |             result.append('/') | 
 | 2975 |  | 
| Larry Hastings | 7c7cbfc | 2012-06-22 15:19:35 -0700 | [diff] [blame] | 2976 |         rendered = '({})'.format(', '.join(result)) | 
 | 2977 |  | 
 | 2978 |         if self.return_annotation is not _empty: | 
 | 2979 |             anno = formatannotation(self.return_annotation) | 
 | 2980 |             rendered += ' -> {}'.format(anno) | 
 | 2981 |  | 
 | 2982 |         return rendered | 
| Nick Coghlan | f94a16b | 2013-09-22 22:46:49 +1000 | [diff] [blame] | 2983 |  | 
| Yury Selivanov | da39645 | 2014-03-27 12:09:24 -0400 | [diff] [blame] | 2984 |  | 
| Yury Selivanov | bcd4fc1 | 2015-05-20 14:30:08 -0400 | [diff] [blame] | 2985 | def signature(obj, *, follow_wrapped=True): | 
| Yury Selivanov | 5a23bd0 | 2014-03-29 13:47:11 -0400 | [diff] [blame] | 2986 |     """Get a signature object for the passed callable.""" | 
| Yury Selivanov | bcd4fc1 | 2015-05-20 14:30:08 -0400 | [diff] [blame] | 2987 |     return Signature.from_callable(obj, follow_wrapped=follow_wrapped) | 
| Yury Selivanov | da39645 | 2014-03-27 12:09:24 -0400 | [diff] [blame] | 2988 |  | 
 | 2989 |  | 
| Nick Coghlan | f94a16b | 2013-09-22 22:46:49 +1000 | [diff] [blame] | 2990 | def _main(): | 
 | 2991 |     """ Logic for inspecting an object given at command line """ | 
 | 2992 |     import argparse | 
 | 2993 |     import importlib | 
 | 2994 |  | 
 | 2995 |     parser = argparse.ArgumentParser() | 
 | 2996 |     parser.add_argument( | 
 | 2997 |         'object', | 
 | 2998 |          help="The object to be analysed. " | 
 | 2999 |               "It supports the 'module:qualname' syntax") | 
 | 3000 |     parser.add_argument( | 
 | 3001 |         '-d', '--details', action='store_true', | 
 | 3002 |         help='Display info about the module rather than its source code') | 
 | 3003 |  | 
 | 3004 |     args = parser.parse_args() | 
 | 3005 |  | 
 | 3006 |     target = args.object | 
 | 3007 |     mod_name, has_attrs, attrs = target.partition(":") | 
 | 3008 |     try: | 
 | 3009 |         obj = module = importlib.import_module(mod_name) | 
 | 3010 |     except Exception as exc: | 
 | 3011 |         msg = "Failed to import {} ({}: {})".format(mod_name, | 
 | 3012 |                                                     type(exc).__name__, | 
 | 3013 |                                                     exc) | 
 | 3014 |         print(msg, file=sys.stderr) | 
 | 3015 |         exit(2) | 
 | 3016 |  | 
 | 3017 |     if has_attrs: | 
 | 3018 |         parts = attrs.split(".") | 
 | 3019 |         obj = module | 
 | 3020 |         for part in parts: | 
 | 3021 |             obj = getattr(obj, part) | 
 | 3022 |  | 
 | 3023 |     if module.__name__ in sys.builtin_module_names: | 
 | 3024 |         print("Can't get info for builtin modules.", file=sys.stderr) | 
 | 3025 |         exit(1) | 
 | 3026 |  | 
 | 3027 |     if args.details: | 
 | 3028 |         print('Target: {}'.format(target)) | 
 | 3029 |         print('Origin: {}'.format(getsourcefile(module))) | 
 | 3030 |         print('Cached: {}'.format(module.__cached__)) | 
 | 3031 |         if obj is module: | 
 | 3032 |             print('Loader: {}'.format(repr(module.__loader__))) | 
 | 3033 |             if hasattr(module, '__path__'): | 
 | 3034 |                 print('Submodule search path: {}'.format(module.__path__)) | 
 | 3035 |         else: | 
 | 3036 |             try: | 
 | 3037 |                 __, lineno = findsource(obj) | 
 | 3038 |             except Exception: | 
 | 3039 |                 pass | 
 | 3040 |             else: | 
 | 3041 |                 print('Line: {}'.format(lineno)) | 
 | 3042 |  | 
 | 3043 |         print('\n') | 
 | 3044 |     else: | 
 | 3045 |         print(getsource(obj)) | 
 | 3046 |  | 
 | 3047 |  | 
 | 3048 | if __name__ == "__main__": | 
 | 3049 |     _main() |