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