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