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