Debian Codegraph @

lib-python/3/inspect.py

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