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