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