blob: ad7e8cb1203e7f0b7b2cefd9c5616d6a852a2cd9 [file] [log] [blame]
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001"""Get useful information from live Python objects.
2
3This module encapsulates the interface provided by the internal special
Neal Norwitz221085d2007-02-25 20:55:47 +00004attributes (co_*, im_*, tb_*, etc.) in a friendlier fashion.
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00005It also provides some help for examining source code and class layout.
6
7Here are some of the useful functions provided by this module:
8
Christian Heimes7131fd92008-02-19 14:21:46 +00009 ismodule(), isclass(), ismethod(), isfunction(), isgeneratorfunction(),
10 isgenerator(), istraceback(), isframe(), iscode(), isbuiltin(),
11 isroutine() - check object types
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +000012 getmembers() - get members of an object that satisfy a given condition
13
14 getfile(), getsourcefile(), getsource() - find an object's source code
15 getdoc(), getcomments() - get documentation on an object
16 getmodule() - determine the module that an object came from
17 getclasstree() - arrange classes so as to represent their hierarchy
18
Berker Peksagfa3922c2015-07-31 04:11:29 +030019 getargvalues(), getcallargs() - get info about function arguments
Yury Selivanov0cf3ed62014-04-01 10:17:08 -040020 getfullargspec() - same, with support for Python 3 features
Matthias Bussonnier46c5cd02018-06-11 22:08:16 +020021 formatargvalues() - format an argument spec
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +000022 getouterframes(), getinnerframes() - get info about frames
23 currentframe() - get the current stack frame
24 stack(), trace() - get info about frames on the stack or in a traceback
Larry Hastings7c7cbfc2012-06-22 15:19:35 -070025
26 signature() - get a Signature object for the callable
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +000027"""
28
29# This module is in the public domain. No warranties.
30
Larry Hastings7c7cbfc2012-06-22 15:19:35 -070031__author__ = ('Ka-Ping Yee <ping@lfw.org>',
32 'Yury Selivanov <yselivanov@sprymix.com>')
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +000033
Natefcfe80e2017-04-24 10:06:15 -070034import abc
Karthikeyan Singaravelan696136b2020-04-18 21:49:32 +053035import ast
Antoine Pitroua8723a02015-04-15 00:41:29 +020036import dis
Yury Selivanov75445082015-05-11 22:57:16 -040037import collections.abc
Yury Selivanov21e83a52014-03-27 11:23:13 -040038import enum
Brett Cannoncb66eb02012-05-11 12:58:42 -040039import importlib.machinery
40import itertools
Christian Heimes7131fd92008-02-19 14:21:46 +000041import linecache
Brett Cannoncb66eb02012-05-11 12:58:42 -040042import os
43import re
44import sys
45import tokenize
Larry Hastings2623c8c2014-02-08 22:15:29 -080046import token
Brett Cannoncb66eb02012-05-11 12:58:42 -040047import types
Brett Cannon2b88fcf2012-06-02 22:28:42 -040048import warnings
Larry Hastings7c7cbfc2012-06-22 15:19:35 -070049import functools
Nick Coghlan2f92e542012-06-23 19:39:55 +100050import builtins
Raymond Hettingera1a992c2005-03-11 06:46:45 +000051from operator import attrgetter
Inada Naoki21105512020-03-02 18:54:49 +090052from collections import namedtuple, OrderedDict
Nick Coghlan09c81232010-08-17 10:18:16 +000053
54# Create constants for the compiler flags in Include/code.h
Antoine Pitroua8723a02015-04-15 00:41:29 +020055# We try to get them from dis to avoid duplication
56mod_dict = globals()
57for k, v in dis.COMPILER_FLAG_NAMES.items():
58 mod_dict["CO_" + v] = k
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +000059
Christian Heimesbe5b30b2008-03-03 19:18:51 +000060# See Include/object.h
61TPFLAGS_IS_ABSTRACT = 1 << 20
62
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +000063# ----------------------------------------------------------- type-checking
64def ismodule(object):
65 """Return true if the object is a module.
66
67 Module objects provide these attributes:
Barry Warsaw28a691b2010-04-17 00:19:56 +000068 __cached__ pathname to byte compiled file
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +000069 __doc__ documentation string
70 __file__ filename (missing for built-in modules)"""
Tim Peters28bc59f2001-09-16 08:40:16 +000071 return isinstance(object, types.ModuleType)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +000072
73def isclass(object):
74 """Return true if the object is a class.
75
76 Class objects provide these attributes:
77 __doc__ documentation string
78 __module__ name of module in which this class was defined"""
Benjamin Petersonc4656002009-01-17 22:41:18 +000079 return isinstance(object, type)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +000080
81def ismethod(object):
82 """Return true if the object is an instance method.
83
84 Instance method objects provide these attributes:
85 __doc__ documentation string
86 __name__ name with which this method was defined
Christian Heimesff737952007-11-27 10:40:20 +000087 __func__ function object containing implementation of method
88 __self__ instance to which this method is bound"""
Tim Peters28bc59f2001-09-16 08:40:16 +000089 return isinstance(object, types.MethodType)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +000090
Tim Peters536d2262001-09-20 05:13:38 +000091def ismethoddescriptor(object):
Tim Petersf1d90b92001-09-20 05:47:55 +000092 """Return true if the object is a method descriptor.
93
94 But not if ismethod() or isclass() or isfunction() are true.
Tim Peters536d2262001-09-20 05:13:38 +000095
96 This is new in Python 2.2, and, for example, is true of int.__add__.
97 An object passing this test has a __get__ attribute but not a __set__
98 attribute, but beyond that the set of attributes varies. __name__ is
99 usually sensible, and __doc__ often is.
100
Tim Petersf1d90b92001-09-20 05:47:55 +0000101 Methods implemented via descriptors that also pass one of the other
102 tests return false from the ismethoddescriptor() test, simply because
103 the other tests promise more -- you can, e.g., count on having the
Christian Heimesff737952007-11-27 10:40:20 +0000104 __func__ attribute (etc) when an object passes ismethod()."""
Antoine Pitrou86a8a9a2011-12-21 09:57:40 +0100105 if isclass(object) or ismethod(object) or isfunction(object):
106 # mutual exclusion
107 return False
108 tp = type(object)
109 return hasattr(tp, "__get__") and not hasattr(tp, "__set__")
Tim Peters536d2262001-09-20 05:13:38 +0000110
Martin v. Löwise59e2ba2003-05-03 09:09:02 +0000111def isdatadescriptor(object):
112 """Return true if the object is a data descriptor.
113
Aaron Hall, MBA4054b172018-05-20 19:46:42 -0400114 Data descriptors have a __set__ or a __delete__ attribute. Examples are
Martin v. Löwise59e2ba2003-05-03 09:09:02 +0000115 properties (defined in Python) and getsets and members (defined in C).
116 Typically, data descriptors will also have __name__ and __doc__ attributes
117 (properties, getsets, and members have both of these attributes), but this
118 is not guaranteed."""
Antoine Pitrou86a8a9a2011-12-21 09:57:40 +0100119 if isclass(object) or ismethod(object) or isfunction(object):
120 # mutual exclusion
121 return False
122 tp = type(object)
Aaron Hall, MBA4054b172018-05-20 19:46:42 -0400123 return hasattr(tp, "__set__") or hasattr(tp, "__delete__")
Martin v. Löwise59e2ba2003-05-03 09:09:02 +0000124
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000125if hasattr(types, 'MemberDescriptorType'):
126 # CPython and equivalent
127 def ismemberdescriptor(object):
128 """Return true if the object is a member descriptor.
129
130 Member descriptors are specialized descriptors defined in extension
131 modules."""
132 return isinstance(object, types.MemberDescriptorType)
133else:
134 # Other implementations
135 def ismemberdescriptor(object):
136 """Return true if the object is a member descriptor.
137
138 Member descriptors are specialized descriptors defined in extension
139 modules."""
140 return False
141
142if hasattr(types, 'GetSetDescriptorType'):
143 # CPython and equivalent
144 def isgetsetdescriptor(object):
145 """Return true if the object is a getset descriptor.
146
147 getset descriptors are specialized descriptors defined in extension
148 modules."""
149 return isinstance(object, types.GetSetDescriptorType)
150else:
151 # Other implementations
152 def isgetsetdescriptor(object):
153 """Return true if the object is a getset descriptor.
154
155 getset descriptors are specialized descriptors defined in extension
156 modules."""
157 return False
158
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000159def isfunction(object):
160 """Return true if the object is a user-defined function.
161
162 Function objects provide these attributes:
163 __doc__ documentation string
164 __name__ name with which this function was defined
Neal Norwitz221085d2007-02-25 20:55:47 +0000165 __code__ code object containing compiled function bytecode
166 __defaults__ tuple of any default values for arguments
167 __globals__ global namespace in which this function was defined
168 __annotations__ dict of parameter annotations
169 __kwdefaults__ dict of keyword only parameters with defaults"""
Tim Peters28bc59f2001-09-16 08:40:16 +0000170 return isinstance(object, types.FunctionType)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000171
Jeroen Demeyerfcef60f2019-04-02 16:03:42 +0200172def _has_code_flag(f, flag):
173 """Return true if ``f`` is a function (or a method or functools.partial
174 wrapper wrapping a function) whose code object has the given ``flag``
175 set in its flags."""
176 while ismethod(f):
177 f = f.__func__
178 f = functools._unwrap_partial(f)
179 if not isfunction(f):
180 return False
181 return bool(f.__code__.co_flags & flag)
182
Pablo Galindo7cd25432018-10-26 12:19:14 +0100183def isgeneratorfunction(obj):
Christian Heimes7131fd92008-02-19 14:21:46 +0000184 """Return true if the object is a user-defined generator function.
185
Martin Panter0f0eac42016-09-07 11:04:41 +0000186 Generator function objects provide the same attributes as functions.
187 See help(isfunction) for a list of attributes."""
Jeroen Demeyerfcef60f2019-04-02 16:03:42 +0200188 return _has_code_flag(obj, CO_GENERATOR)
Yury Selivanov75445082015-05-11 22:57:16 -0400189
Pablo Galindo7cd25432018-10-26 12:19:14 +0100190def iscoroutinefunction(obj):
Yury Selivanov75445082015-05-11 22:57:16 -0400191 """Return true if the object is a coroutine function.
192
Yury Selivanov4778e132016-11-08 12:23:09 -0500193 Coroutine functions are defined with "async def" syntax.
Yury Selivanov75445082015-05-11 22:57:16 -0400194 """
Jeroen Demeyerfcef60f2019-04-02 16:03:42 +0200195 return _has_code_flag(obj, CO_COROUTINE)
Yury Selivanov75445082015-05-11 22:57:16 -0400196
Pablo Galindo7cd25432018-10-26 12:19:14 +0100197def isasyncgenfunction(obj):
Yury Selivanov4778e132016-11-08 12:23:09 -0500198 """Return true if the object is an asynchronous generator function.
199
200 Asynchronous generator functions are defined with "async def"
201 syntax and have "yield" expressions in their body.
202 """
Jeroen Demeyerfcef60f2019-04-02 16:03:42 +0200203 return _has_code_flag(obj, CO_ASYNC_GENERATOR)
Yury Selivanoveb636452016-09-08 22:01:51 -0700204
205def isasyncgen(object):
Yury Selivanov4778e132016-11-08 12:23:09 -0500206 """Return true if the object is an asynchronous generator."""
Yury Selivanoveb636452016-09-08 22:01:51 -0700207 return isinstance(object, types.AsyncGeneratorType)
208
Christian Heimes7131fd92008-02-19 14:21:46 +0000209def isgenerator(object):
210 """Return true if the object is a generator.
211
212 Generator objects provide these attributes:
Ezio Melotti30b9d5d2013-08-17 15:50:46 +0300213 __iter__ defined to support iteration over container
Christian Heimes7131fd92008-02-19 14:21:46 +0000214 close raises a new GeneratorExit exception inside the
215 generator to terminate the iteration
216 gi_code code object
217 gi_frame frame object or possibly None once the generator has
218 been exhausted
219 gi_running set to 1 when generator is executing, 0 otherwise
220 next return the next item from the container
221 send resumes the generator and "sends" a value that becomes
222 the result of the current yield-expression
223 throw used to raise an exception inside the generator"""
Yury Selivanov5376ba92015-06-22 12:19:30 -0400224 return isinstance(object, types.GeneratorType)
Yury Selivanov75445082015-05-11 22:57:16 -0400225
226def iscoroutine(object):
227 """Return true if the object is a coroutine."""
Yury Selivanov5376ba92015-06-22 12:19:30 -0400228 return isinstance(object, types.CoroutineType)
Christian Heimes7131fd92008-02-19 14:21:46 +0000229
Yury Selivanovfdbeb2b2015-07-03 13:11:35 -0400230def isawaitable(object):
Yury Selivanovc0215df2016-11-08 19:57:44 -0500231 """Return true if object can be passed to an ``await`` expression."""
Yury Selivanovfdbeb2b2015-07-03 13:11:35 -0400232 return (isinstance(object, types.CoroutineType) or
233 isinstance(object, types.GeneratorType) and
Yury Selivanovc0215df2016-11-08 19:57:44 -0500234 bool(object.gi_code.co_flags & CO_ITERABLE_COROUTINE) or
Yury Selivanovfdbeb2b2015-07-03 13:11:35 -0400235 isinstance(object, collections.abc.Awaitable))
236
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000237def istraceback(object):
238 """Return true if the object is a traceback.
239
240 Traceback objects provide these attributes:
241 tb_frame frame object at this level
242 tb_lasti index of last attempted instruction in bytecode
243 tb_lineno current line number in Python source code
244 tb_next next inner traceback object (called by this level)"""
Tim Peters28bc59f2001-09-16 08:40:16 +0000245 return isinstance(object, types.TracebackType)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000246
247def isframe(object):
248 """Return true if the object is a frame object.
249
250 Frame objects provide these attributes:
251 f_back next outer frame object (this frame's caller)
252 f_builtins built-in namespace seen by this frame
253 f_code code object being executed in this frame
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000254 f_globals global namespace seen by this frame
255 f_lasti index of last attempted instruction in bytecode
256 f_lineno current line number in Python source code
257 f_locals local namespace seen by this frame
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000258 f_trace tracing function for this frame, or None"""
Tim Peters28bc59f2001-09-16 08:40:16 +0000259 return isinstance(object, types.FrameType)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000260
261def iscode(object):
262 """Return true if the object is a code object.
263
264 Code objects provide these attributes:
Xiang Zhanga6902e62017-04-13 10:38:28 +0800265 co_argcount number of arguments (not including *, ** args
266 or keyword only arguments)
267 co_code string of raw compiled bytecode
268 co_cellvars tuple of names of cell variables
269 co_consts tuple of constants used in the bytecode
270 co_filename name of file in which this code object was created
271 co_firstlineno number of first line in Python source code
272 co_flags bitmap: 1=optimized | 2=newlocals | 4=*arg | 8=**arg
273 | 16=nested | 32=generator | 64=nofree | 128=coroutine
274 | 256=iterable_coroutine | 512=async_generator
275 co_freevars tuple of names of free variables
Pablo Galindo8c77b8c2019-04-29 13:36:57 +0100276 co_posonlyargcount number of positional only arguments
Xiang Zhanga6902e62017-04-13 10:38:28 +0800277 co_kwonlyargcount number of keyword only arguments (not including ** arg)
278 co_lnotab encoded mapping of line numbers to bytecode indices
279 co_name name with which this code object was defined
280 co_names tuple of names of local variables
281 co_nlocals number of local variables
282 co_stacksize virtual machine stack space required
283 co_varnames tuple of names of arguments and local variables"""
Tim Peters28bc59f2001-09-16 08:40:16 +0000284 return isinstance(object, types.CodeType)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000285
286def isbuiltin(object):
287 """Return true if the object is a built-in function or method.
288
289 Built-in functions and methods provide these attributes:
290 __doc__ documentation string
291 __name__ original name of this function or method
292 __self__ instance to which a method is bound, or None"""
Tim Peters28bc59f2001-09-16 08:40:16 +0000293 return isinstance(object, types.BuiltinFunctionType)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000294
295def isroutine(object):
296 """Return true if the object is any kind of function or method."""
Tim Peters536d2262001-09-20 05:13:38 +0000297 return (isbuiltin(object)
298 or isfunction(object)
299 or ismethod(object)
300 or ismethoddescriptor(object))
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000301
Christian Heimesbe5b30b2008-03-03 19:18:51 +0000302def isabstract(object):
303 """Return true if the object is an abstract base class (ABC)."""
Natefcfe80e2017-04-24 10:06:15 -0700304 if not isinstance(object, type):
305 return False
306 if object.__flags__ & TPFLAGS_IS_ABSTRACT:
307 return True
308 if not issubclass(type(object), abc.ABCMeta):
309 return False
310 if hasattr(object, '__abstractmethods__'):
311 # It looks like ABCMeta.__new__ has finished running;
312 # TPFLAGS_IS_ABSTRACT should have been accurate.
313 return False
314 # It looks like ABCMeta.__new__ has not finished running yet; we're
315 # probably in __init_subclass__. We'll look for abstractmethods manually.
316 for name, value in object.__dict__.items():
317 if getattr(value, "__isabstractmethod__", False):
318 return True
319 for base in object.__bases__:
320 for name in getattr(base, "__abstractmethods__", ()):
321 value = getattr(object, name, None)
322 if getattr(value, "__isabstractmethod__", False):
323 return True
324 return False
Christian Heimesbe5b30b2008-03-03 19:18:51 +0000325
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000326def getmembers(object, predicate=None):
327 """Return all members of an object as (name, value) pairs sorted by name.
328 Optionally, only return members that satisfy a given predicate."""
Antoine Pitrou86a8a9a2011-12-21 09:57:40 +0100329 if isclass(object):
330 mro = (object,) + getmro(object)
331 else:
332 mro = ()
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000333 results = []
Ethan Furmane03ea372013-09-25 07:14:41 -0700334 processed = set()
335 names = dir(object)
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700336 # :dd any DynamicClassAttributes to the list of names if object is a class;
Ethan Furmane03ea372013-09-25 07:14:41 -0700337 # this may result in duplicate entries if, for example, a virtual
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700338 # attribute with the same name as a DynamicClassAttribute exists
Ethan Furmane03ea372013-09-25 07:14:41 -0700339 try:
340 for base in object.__bases__:
341 for k, v in base.__dict__.items():
342 if isinstance(v, types.DynamicClassAttribute):
343 names.append(k)
344 except AttributeError:
345 pass
346 for key in names:
Ethan Furman63c141c2013-10-18 00:27:39 -0700347 # First try to get the value via getattr. Some descriptors don't
348 # like calling their __get__ (see bug #1785), so fall back to
349 # looking in the __dict__.
350 try:
351 value = getattr(object, key)
352 # handle the duplicate key
353 if key in processed:
354 raise AttributeError
355 except AttributeError:
356 for base in mro:
357 if key in base.__dict__:
358 value = base.__dict__[key]
359 break
360 else:
361 # could be a (currently) missing slot member, or a buggy
362 # __dir__; discard and move on
Antoine Pitrou86a8a9a2011-12-21 09:57:40 +0100363 continue
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000364 if not predicate or predicate(value):
365 results.append((key, value))
Ethan Furmane03ea372013-09-25 07:14:41 -0700366 processed.add(key)
367 results.sort(key=lambda pair: pair[0])
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000368 return results
369
Christian Heimes25bb7832008-01-11 16:17:00 +0000370Attribute = namedtuple('Attribute', 'name kind defining_class object')
371
Tim Peters13b49d32001-09-23 02:00:29 +0000372def classify_class_attrs(cls):
373 """Return list of attribute-descriptor tuples.
374
375 For each name in dir(cls), the return list contains a 4-tuple
376 with these elements:
377
378 0. The name (a string).
379
380 1. The kind of attribute this is, one of these strings:
381 'class method' created via classmethod()
382 'static method' created via staticmethod()
383 'property' created via property()
Ethan Furmane03ea372013-09-25 07:14:41 -0700384 'method' any other flavor of method or descriptor
Tim Peters13b49d32001-09-23 02:00:29 +0000385 'data' not a method
386
387 2. The class which defined this attribute (a class).
388
Ethan Furmane03ea372013-09-25 07:14:41 -0700389 3. The object as obtained by calling getattr; if this fails, or if the
390 resulting object does not live anywhere in the class' mro (including
391 metaclasses) then the object is looked up in the defining class's
392 dict (found by walking the mro).
Ethan Furman668dede2013-09-14 18:53:26 -0700393
394 If one of the items in dir(cls) is stored in the metaclass it will now
395 be discovered and not have None be listed as the class in which it was
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700396 defined. Any items whose home class cannot be discovered are skipped.
Tim Peters13b49d32001-09-23 02:00:29 +0000397 """
398
399 mro = getmro(cls)
Ethan Furman668dede2013-09-14 18:53:26 -0700400 metamro = getmro(type(cls)) # for attributes stored in the metaclass
Jon Dufresne39726282017-05-18 07:35:54 -0700401 metamro = tuple(cls for cls in metamro if cls not in (type, object))
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700402 class_bases = (cls,) + mro
403 all_bases = class_bases + metamro
Tim Peters13b49d32001-09-23 02:00:29 +0000404 names = dir(cls)
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700405 # :dd any DynamicClassAttributes to the list of names;
Ethan Furmane03ea372013-09-25 07:14:41 -0700406 # this may result in duplicate entries if, for example, a virtual
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700407 # attribute with the same name as a DynamicClassAttribute exists.
Ethan Furman63c141c2013-10-18 00:27:39 -0700408 for base in mro:
Ethan Furmane03ea372013-09-25 07:14:41 -0700409 for k, v in base.__dict__.items():
410 if isinstance(v, types.DynamicClassAttribute):
411 names.append(k)
Tim Peters13b49d32001-09-23 02:00:29 +0000412 result = []
Ethan Furmane03ea372013-09-25 07:14:41 -0700413 processed = set()
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700414
Tim Peters13b49d32001-09-23 02:00:29 +0000415 for name in names:
Antoine Pitrou86a8a9a2011-12-21 09:57:40 +0100416 # Get the object associated with the name, and where it was defined.
Ethan Furmane03ea372013-09-25 07:14:41 -0700417 # Normal objects will be looked up with both getattr and directly in
418 # its class' dict (in case getattr fails [bug #1785], and also to look
419 # for a docstring).
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700420 # For DynamicClassAttributes on the second pass we only look in the
Ethan Furmane03ea372013-09-25 07:14:41 -0700421 # class's dict.
422 #
Tim Peters13b49d32001-09-23 02:00:29 +0000423 # Getting an obj from the __dict__ sometimes reveals more than
424 # using getattr. Static and class methods are dramatic examples.
Antoine Pitrou86a8a9a2011-12-21 09:57:40 +0100425 homecls = None
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700426 get_obj = None
427 dict_obj = None
Ethan Furmane03ea372013-09-25 07:14:41 -0700428 if name not in processed:
429 try:
Ethan Furmana8b07072013-10-18 01:22:08 -0700430 if name == '__dict__':
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700431 raise Exception("__dict__ is special, don't want the proxy")
Ethan Furmane03ea372013-09-25 07:14:41 -0700432 get_obj = getattr(cls, name)
433 except Exception as exc:
434 pass
435 else:
Ethan Furmane03ea372013-09-25 07:14:41 -0700436 homecls = getattr(get_obj, "__objclass__", homecls)
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700437 if homecls not in class_bases:
Ethan Furmane03ea372013-09-25 07:14:41 -0700438 # if the resulting object does not live somewhere in the
Ethan Furman63c141c2013-10-18 00:27:39 -0700439 # mro, drop it and search the mro manually
Ethan Furmane03ea372013-09-25 07:14:41 -0700440 homecls = None
Ethan Furman63c141c2013-10-18 00:27:39 -0700441 last_cls = None
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700442 # first look in the classes
443 for srch_cls in class_bases:
Ethan Furman63c141c2013-10-18 00:27:39 -0700444 srch_obj = getattr(srch_cls, name, None)
Yury Selivanovbf341fb2015-05-21 15:41:57 -0400445 if srch_obj is get_obj:
Ethan Furman63c141c2013-10-18 00:27:39 -0700446 last_cls = srch_cls
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700447 # then check the metaclasses
448 for srch_cls in metamro:
449 try:
450 srch_obj = srch_cls.__getattr__(cls, name)
451 except AttributeError:
452 continue
Yury Selivanovbf341fb2015-05-21 15:41:57 -0400453 if srch_obj is get_obj:
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700454 last_cls = srch_cls
Ethan Furman63c141c2013-10-18 00:27:39 -0700455 if last_cls is not None:
456 homecls = last_cls
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700457 for base in all_bases:
Ethan Furmane03ea372013-09-25 07:14:41 -0700458 if name in base.__dict__:
459 dict_obj = base.__dict__[name]
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700460 if homecls not in metamro:
461 homecls = base
Ethan Furmane03ea372013-09-25 07:14:41 -0700462 break
Ethan Furman63c141c2013-10-18 00:27:39 -0700463 if homecls is None:
464 # unable to locate the attribute anywhere, most likely due to
465 # buggy custom __dir__; discard and move on
466 continue
Yury Selivanovbf341fb2015-05-21 15:41:57 -0400467 obj = get_obj if get_obj is not None else dict_obj
Ethan Furmane03ea372013-09-25 07:14:41 -0700468 # Classify the object or its descriptor.
Serhiy Storchaka3327a2d2017-12-15 14:13:41 +0200469 if isinstance(dict_obj, (staticmethod, types.BuiltinMethodType)):
Tim Peters13b49d32001-09-23 02:00:29 +0000470 kind = "static method"
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700471 obj = dict_obj
Serhiy Storchaka3327a2d2017-12-15 14:13:41 +0200472 elif isinstance(dict_obj, (classmethod, types.ClassMethodDescriptorType)):
Tim Peters13b49d32001-09-23 02:00:29 +0000473 kind = "class method"
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700474 obj = dict_obj
475 elif isinstance(dict_obj, property):
Tim Peters13b49d32001-09-23 02:00:29 +0000476 kind = "property"
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700477 obj = dict_obj
Yury Selivanov0860a0b2014-01-31 14:28:44 -0500478 elif isroutine(obj):
Tim Peters13b49d32001-09-23 02:00:29 +0000479 kind = "method"
Antoine Pitrou86a8a9a2011-12-21 09:57:40 +0100480 else:
Ethan Furmane03ea372013-09-25 07:14:41 -0700481 kind = "data"
Christian Heimes25bb7832008-01-11 16:17:00 +0000482 result.append(Attribute(name, kind, homecls, obj))
Ethan Furmane03ea372013-09-25 07:14:41 -0700483 processed.add(name)
Tim Peters13b49d32001-09-23 02:00:29 +0000484 return result
485
Tim Peterse0b2d7a2001-09-22 06:10:55 +0000486# ----------------------------------------------------------- class helpers
Tim Peterse0b2d7a2001-09-22 06:10:55 +0000487
488def getmro(cls):
489 "Return tuple of base classes (including cls) in method resolution order."
Benjamin Petersonb82c8e52010-11-04 00:38:49 +0000490 return cls.__mro__
Tim Peterse0b2d7a2001-09-22 06:10:55 +0000491
Nick Coghlane8c45d62013-07-28 20:00:01 +1000492# -------------------------------------------------------- function helpers
493
494def unwrap(func, *, stop=None):
495 """Get the object wrapped by *func*.
496
497 Follows the chain of :attr:`__wrapped__` attributes returning the last
498 object in the chain.
499
500 *stop* is an optional callback accepting an object in the wrapper chain
501 as its sole argument that allows the unwrapping to be terminated early if
502 the callback returns a true value. If the callback never returns a true
503 value, the last object in the chain is returned as usual. For example,
504 :func:`signature` uses this to stop unwrapping if any object in the
505 chain has a ``__signature__`` attribute defined.
506
507 :exc:`ValueError` is raised if a cycle is encountered.
508
509 """
510 if stop is None:
511 def _is_wrapper(f):
512 return hasattr(f, '__wrapped__')
513 else:
514 def _is_wrapper(f):
515 return hasattr(f, '__wrapped__') and not stop(f)
516 f = func # remember the original func for error reporting
Thomas Kluyverf9169ce2017-05-23 04:27:52 +0100517 # Memoise by id to tolerate non-hashable objects, but store objects to
518 # ensure they aren't destroyed, which would allow their IDs to be reused.
519 memo = {id(f): f}
520 recursion_limit = sys.getrecursionlimit()
Nick Coghlane8c45d62013-07-28 20:00:01 +1000521 while _is_wrapper(func):
522 func = func.__wrapped__
523 id_func = id(func)
Thomas Kluyverf9169ce2017-05-23 04:27:52 +0100524 if (id_func in memo) or (len(memo) >= recursion_limit):
Nick Coghlane8c45d62013-07-28 20:00:01 +1000525 raise ValueError('wrapper loop when unwrapping {!r}'.format(f))
Thomas Kluyverf9169ce2017-05-23 04:27:52 +0100526 memo[id_func] = func
Nick Coghlane8c45d62013-07-28 20:00:01 +1000527 return func
528
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000529# -------------------------------------------------- source code extraction
530def indentsize(line):
531 """Return the indent size, in spaces, at the start of a line of text."""
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000532 expline = line.expandtabs()
533 return len(expline) - len(expline.lstrip())
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000534
Serhiy Storchaka5cf2b722015-04-03 22:38:53 +0300535def _findclass(func):
536 cls = sys.modules.get(func.__module__)
537 if cls is None:
538 return None
539 for name in func.__qualname__.split('.')[:-1]:
540 cls = getattr(cls, name)
541 if not isclass(cls):
542 return None
543 return cls
544
545def _finddoc(obj):
Serhiy Storchaka5cf2b722015-04-03 22:38:53 +0300546 if ismethod(obj):
547 name = obj.__func__.__name__
548 self = obj.__self__
549 if (isclass(self) and
550 getattr(getattr(self, name, None), '__func__') is obj.__func__):
551 # classmethod
552 cls = self
553 else:
554 cls = self.__class__
555 elif isfunction(obj):
556 name = obj.__name__
557 cls = _findclass(obj)
558 if cls is None or getattr(cls, name) is not obj:
559 return None
560 elif isbuiltin(obj):
561 name = obj.__name__
562 self = obj.__self__
563 if (isclass(self) and
564 self.__qualname__ + '.' + name == obj.__qualname__):
565 # classmethod
566 cls = self
567 else:
568 cls = self.__class__
Serhiy Storchakaac4bdcc2015-10-29 08:15:50 +0200569 # Should be tested before isdatadescriptor().
570 elif isinstance(obj, property):
571 func = obj.fget
572 name = func.__name__
573 cls = _findclass(func)
574 if cls is None or getattr(cls, name) is not obj:
575 return None
Serhiy Storchaka5cf2b722015-04-03 22:38:53 +0300576 elif ismethoddescriptor(obj) or isdatadescriptor(obj):
577 name = obj.__name__
578 cls = obj.__objclass__
579 if getattr(cls, name) is not obj:
580 return None
Raymond Hettingerd1e768a2019-03-25 13:01:13 -0700581 if ismemberdescriptor(obj):
582 slots = getattr(cls, '__slots__', None)
583 if isinstance(slots, dict) and name in slots:
584 return slots[name]
Serhiy Storchaka5cf2b722015-04-03 22:38:53 +0300585 else:
586 return None
Serhiy Storchaka5cf2b722015-04-03 22:38:53 +0300587 for base in cls.__mro__:
588 try:
Serhiy Storchakafbf27862020-04-15 23:00:20 +0300589 doc = _getowndoc(getattr(base, name))
Serhiy Storchaka5cf2b722015-04-03 22:38:53 +0300590 except AttributeError:
591 continue
592 if doc is not None:
593 return doc
594 return None
595
Serhiy Storchakafbf27862020-04-15 23:00:20 +0300596def _getowndoc(obj):
597 """Get the documentation string for an object if it is not
598 inherited from its class."""
599 try:
600 doc = object.__getattribute__(obj, '__doc__')
601 if doc is None:
602 return None
603 if obj is not type:
604 typedoc = type(obj).__doc__
605 if isinstance(typedoc, str) and typedoc == doc:
606 return None
607 return doc
608 except AttributeError:
609 return None
610
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000611def getdoc(object):
612 """Get the documentation string for an object.
613
614 All tabs are expanded to spaces. To clean up docstrings that are
615 indented to line up with blocks of code, any whitespace than can be
616 uniformly removed from the second line onwards is removed."""
Serhiy Storchakafbf27862020-04-15 23:00:20 +0300617 doc = _getowndoc(object)
Serhiy Storchaka5cf2b722015-04-03 22:38:53 +0300618 if doc is None:
619 try:
620 doc = _finddoc(object)
621 except (AttributeError, TypeError):
622 return None
Guido van Rossum3172c5d2007-10-16 18:12:55 +0000623 if not isinstance(doc, str):
Tim Peters24008312002-03-17 18:56:20 +0000624 return None
Georg Brandl0c77a822008-06-10 16:37:50 +0000625 return cleandoc(doc)
626
627def cleandoc(doc):
628 """Clean up indentation from docstrings.
629
630 Any whitespace that can be uniformly removed from the second line
631 onwards is removed."""
Tim Peters24008312002-03-17 18:56:20 +0000632 try:
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000633 lines = doc.expandtabs().split('\n')
Tim Peters24008312002-03-17 18:56:20 +0000634 except UnicodeError:
635 return None
636 else:
Ka-Ping Yeea59ef7b2002-11-30 03:53:15 +0000637 # Find minimum indentation of any non-blank lines after first line.
Christian Heimesa37d4c62007-12-04 23:02:19 +0000638 margin = sys.maxsize
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000639 for line in lines[1:]:
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000640 content = len(line.lstrip())
Ka-Ping Yeea59ef7b2002-11-30 03:53:15 +0000641 if content:
642 indent = len(line) - content
643 margin = min(margin, indent)
644 # Remove indentation.
645 if lines:
646 lines[0] = lines[0].lstrip()
Christian Heimesa37d4c62007-12-04 23:02:19 +0000647 if margin < sys.maxsize:
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000648 for i in range(1, len(lines)): lines[i] = lines[i][margin:]
Ka-Ping Yeea59ef7b2002-11-30 03:53:15 +0000649 # Remove any trailing or leading blank lines.
650 while lines and not lines[-1]:
651 lines.pop()
652 while lines and not lines[0]:
653 lines.pop(0)
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000654 return '\n'.join(lines)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000655
656def getfile(object):
Ka-Ping Yeec113c242001-03-02 02:08:53 +0000657 """Work out which source or compiled file an object was defined in."""
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000658 if ismodule(object):
Jason R. Coombsb9650a02018-03-05 18:29:08 -0500659 if getattr(object, '__file__', None):
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000660 return object.__file__
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +0000661 raise TypeError('{!r} is a built-in module'.format(object))
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000662 if isclass(object):
Yury Selivanov2eed8b72014-01-27 13:24:56 -0500663 if hasattr(object, '__module__'):
Philipp Ad407d2a2019-06-08 14:05:46 +0200664 module = sys.modules.get(object.__module__)
665 if getattr(module, '__file__', None):
666 return module.__file__
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +0000667 raise TypeError('{!r} is a built-in class'.format(object))
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000668 if ismethod(object):
Christian Heimesff737952007-11-27 10:40:20 +0000669 object = object.__func__
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000670 if isfunction(object):
Neal Norwitz221085d2007-02-25 20:55:47 +0000671 object = object.__code__
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000672 if istraceback(object):
673 object = object.tb_frame
674 if isframe(object):
675 object = object.f_code
676 if iscode(object):
677 return object.co_filename
Thomas Kluyvere968bc732017-10-24 13:42:36 +0100678 raise TypeError('module, class, method, function, traceback, frame, or '
679 'code object was expected, got {}'.format(
680 type(object).__name__))
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000681
Ka-Ping Yee4d6fc7f2001-04-10 11:43:00 +0000682def getmodulename(path):
683 """Return the module name for a given file, or None."""
Nick Coghlan76e07702012-07-18 23:14:57 +1000684 fname = os.path.basename(path)
685 # Check for paths that look like an actual module file
686 suffixes = [(-len(suffix), suffix)
687 for suffix in importlib.machinery.all_suffixes()]
688 suffixes.sort() # try longest suffixes first, in case they overlap
689 for neglen, suffix in suffixes:
690 if fname.endswith(suffix):
691 return fname[:neglen]
692 return None
Ka-Ping Yee4d6fc7f2001-04-10 11:43:00 +0000693
Ka-Ping Yeec113c242001-03-02 02:08:53 +0000694def getsourcefile(object):
R. David Murraya1b37402010-06-17 02:04:29 +0000695 """Return the filename that can be used to locate an object's source.
696 Return None if no way can be identified to get the source.
697 """
Ka-Ping Yeec113c242001-03-02 02:08:53 +0000698 filename = getfile(object)
Brett Cannoncb66eb02012-05-11 12:58:42 -0400699 all_bytecode_suffixes = importlib.machinery.DEBUG_BYTECODE_SUFFIXES[:]
700 all_bytecode_suffixes += importlib.machinery.OPTIMIZED_BYTECODE_SUFFIXES[:]
701 if any(filename.endswith(s) for s in all_bytecode_suffixes):
702 filename = (os.path.splitext(filename)[0] +
703 importlib.machinery.SOURCE_SUFFIXES[0])
704 elif any(filename.endswith(s) for s in
705 importlib.machinery.EXTENSION_SUFFIXES):
706 return None
Thomas Wouters477c8d52006-05-27 19:21:47 +0000707 if os.path.exists(filename):
708 return filename
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000709 # only return a non-existent filename if the module has a PEP 302 loader
Brett Cannon4c14b5d2013-05-04 13:56:58 -0400710 if getattr(getmodule(object, filename), '__loader__', None) is not None:
Ka-Ping Yeec113c242001-03-02 02:08:53 +0000711 return filename
R. David Murraya1b37402010-06-17 02:04:29 +0000712 # or it is in the linecache
713 if filename in linecache.cache:
714 return filename
Ka-Ping Yeec113c242001-03-02 02:08:53 +0000715
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000716def getabsfile(object, _filename=None):
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000717 """Return an absolute path to the source or compiled file for an object.
Ka-Ping Yeec113c242001-03-02 02:08:53 +0000718
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000719 The idea is for each object to have a unique origin, so this routine
720 normalizes the result as much as possible."""
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000721 if _filename is None:
722 _filename = getsourcefile(object) or getfile(object)
723 return os.path.normcase(os.path.abspath(_filename))
Ka-Ping Yeec113c242001-03-02 02:08:53 +0000724
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000725modulesbyfile = {}
Thomas Wouters89f507f2006-12-13 04:49:30 +0000726_filesbymodname = {}
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000727
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000728def getmodule(object, _filename=None):
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000729 """Return the module an object was defined in, or None if not found."""
Ka-Ping Yee202c99b2001-04-13 09:15:08 +0000730 if ismodule(object):
731 return object
Johannes Gijsbers93245262004-09-11 15:53:22 +0000732 if hasattr(object, '__module__'):
Ka-Ping Yee8b58b842001-03-01 13:56:16 +0000733 return sys.modules.get(object.__module__)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000734 # Try the filename to modulename cache
735 if _filename is not None and _filename in modulesbyfile:
736 return sys.modules.get(modulesbyfile[_filename])
737 # Try the cache again with the absolute file name
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000738 try:
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000739 file = getabsfile(object, _filename)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000740 except TypeError:
741 return None
Raymond Hettinger54f02222002-06-01 14:18:47 +0000742 if file in modulesbyfile:
Ka-Ping Yeeb38bbbd2003-03-28 16:29:50 +0000743 return sys.modules.get(modulesbyfile[file])
Thomas Wouters89f507f2006-12-13 04:49:30 +0000744 # Update the filename to module name cache and check yet again
745 # Copy sys.modules in order to cope with changes while iterating
Gregory P. Smith85cf1d52020-03-04 16:45:22 -0800746 for modname, module in sys.modules.copy().items():
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000747 if ismodule(module) and hasattr(module, '__file__'):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000748 f = module.__file__
749 if f == _filesbymodname.get(modname, None):
750 # Have already mapped this module, so skip it
751 continue
752 _filesbymodname[modname] = f
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000753 f = getabsfile(module)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000754 # Always map to the name the module knows itself by
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000755 modulesbyfile[f] = modulesbyfile[
756 os.path.realpath(f)] = module.__name__
Raymond Hettinger54f02222002-06-01 14:18:47 +0000757 if file in modulesbyfile:
Ka-Ping Yeeb38bbbd2003-03-28 16:29:50 +0000758 return sys.modules.get(modulesbyfile[file])
Thomas Wouters89f507f2006-12-13 04:49:30 +0000759 # Check the main module
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000760 main = sys.modules['__main__']
Brett Cannon4a671fe2003-06-15 22:33:28 +0000761 if not hasattr(object, '__name__'):
762 return None
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000763 if hasattr(main, object.__name__):
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000764 mainobject = getattr(main, object.__name__)
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000765 if mainobject is object:
766 return main
Thomas Wouters89f507f2006-12-13 04:49:30 +0000767 # Check builtins
Georg Brandl1a3284e2007-12-02 09:40:06 +0000768 builtin = sys.modules['builtins']
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000769 if hasattr(builtin, object.__name__):
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000770 builtinobject = getattr(builtin, object.__name__)
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000771 if builtinobject is object:
772 return builtin
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000773
Karthikeyan Singaravelan696136b2020-04-18 21:49:32 +0530774
775class ClassFoundException(Exception):
776 pass
777
778
779class _ClassFinder(ast.NodeVisitor):
780
781 def __init__(self, qualname):
782 self.stack = []
783 self.qualname = qualname
784
785 def visit_FunctionDef(self, node):
786 self.stack.append(node.name)
787 self.stack.append('<locals>')
788 self.generic_visit(node)
789 self.stack.pop()
790 self.stack.pop()
791
792 visit_AsyncFunctionDef = visit_FunctionDef
793
794 def visit_ClassDef(self, node):
795 self.stack.append(node.name)
796 if self.qualname == '.'.join(self.stack):
797 # Return the decorator for the class if present
798 if node.decorator_list:
799 line_number = node.decorator_list[0].lineno
800 else:
801 line_number = node.lineno
802
803 # decrement by one since lines starts with indexing by zero
804 line_number -= 1
805 raise ClassFoundException(line_number)
806 self.generic_visit(node)
807 self.stack.pop()
808
809
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000810def findsource(object):
811 """Return the entire source file and starting line number for an object.
812
813 The argument may be a module, class, method, function, traceback, frame,
814 or code object. The source code is returned as a list of all the lines
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200815 in the file and the line number indexes a line in that list. An OSError
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000816 is raised if the source code cannot be retrieved."""
Benjamin Peterson9620cc02011-06-11 15:53:11 -0500817
Yury Selivanovef1e7502014-12-08 16:05:34 -0500818 file = getsourcefile(object)
819 if file:
820 # Invalidate cache if needed.
821 linecache.checkcache(file)
822 else:
823 file = getfile(object)
824 # Allow filenames in form of "<something>" to pass through.
825 # `doctest` monkeypatches `linecache` module to enable
826 # inspection, so let `linecache.getlines` to be called.
827 if not (file.startswith('<') and file.endswith('>')):
828 raise OSError('source code not available')
Benjamin Peterson9620cc02011-06-11 15:53:11 -0500829
Thomas Wouters89f507f2006-12-13 04:49:30 +0000830 module = getmodule(object, file)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000831 if module:
832 lines = linecache.getlines(file, module.__dict__)
833 else:
834 lines = linecache.getlines(file)
Neil Schemenauerf06f8532002-03-23 23:51:04 +0000835 if not lines:
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200836 raise OSError('could not get source code')
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000837
838 if ismodule(object):
839 return lines, 0
840
841 if isclass(object):
Karthikeyan Singaravelan696136b2020-04-18 21:49:32 +0530842 qualname = object.__qualname__
843 source = ''.join(lines)
844 tree = ast.parse(source)
845 class_finder = _ClassFinder(qualname)
846 try:
847 class_finder.visit(tree)
848 except ClassFoundException as e:
849 line_number = e.args[0]
850 return lines, line_number
Jeremy Hyltonab919022003-06-27 18:41:20 +0000851 else:
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200852 raise OSError('could not find class definition')
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000853
854 if ismethod(object):
Christian Heimesff737952007-11-27 10:40:20 +0000855 object = object.__func__
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000856 if isfunction(object):
Neal Norwitz221085d2007-02-25 20:55:47 +0000857 object = object.__code__
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000858 if istraceback(object):
859 object = object.tb_frame
860 if isframe(object):
861 object = object.f_code
862 if iscode(object):
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000863 if not hasattr(object, 'co_firstlineno'):
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200864 raise OSError('could not find function definition')
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000865 lnum = object.co_firstlineno - 1
Yury Selivanove4e811d2015-07-21 19:01:52 +0300866 pat = re.compile(r'^(\s*def\s)|(\s*async\s+def\s)|(.*(?<!\w)lambda(:|\s))|^(\s*@)')
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000867 while lnum > 0:
Ka-Ping Yeea6e59712001-03-10 09:31:55 +0000868 if pat.match(lines[lnum]): break
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000869 lnum = lnum - 1
870 return lines, lnum
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200871 raise OSError('could not find code object')
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000872
873def getcomments(object):
Jeremy Hyltonb4c17c82002-03-28 23:01:56 +0000874 """Get lines of comments immediately preceding an object's source code.
875
876 Returns None when source can't be found.
877 """
878 try:
879 lines, lnum = findsource(object)
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200880 except (OSError, TypeError):
Jeremy Hyltonb4c17c82002-03-28 23:01:56 +0000881 return None
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000882
883 if ismodule(object):
884 # Look for a comment block at the top of the file.
885 start = 0
Ka-Ping Yeeb910efe2001-04-12 13:17:17 +0000886 if lines and lines[0][:2] == '#!': start = 1
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000887 while start < len(lines) and lines[start].strip() in ('', '#'):
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000888 start = start + 1
Ka-Ping Yeeb910efe2001-04-12 13:17:17 +0000889 if start < len(lines) and lines[start][:1] == '#':
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000890 comments = []
891 end = start
892 while end < len(lines) and lines[end][:1] == '#':
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000893 comments.append(lines[end].expandtabs())
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000894 end = end + 1
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000895 return ''.join(comments)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000896
897 # Look for a preceding block of comments at the same indentation.
898 elif lnum > 0:
899 indent = indentsize(lines[lnum])
900 end = lnum - 1
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000901 if end >= 0 and lines[end].lstrip()[:1] == '#' and \
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000902 indentsize(lines[end]) == indent:
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000903 comments = [lines[end].expandtabs().lstrip()]
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000904 if end > 0:
905 end = end - 1
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000906 comment = lines[end].expandtabs().lstrip()
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000907 while comment[:1] == '#' and indentsize(lines[end]) == indent:
908 comments[:0] = [comment]
909 end = end - 1
910 if end < 0: break
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000911 comment = lines[end].expandtabs().lstrip()
912 while comments and comments[0].strip() == '#':
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000913 comments[:1] = []
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000914 while comments and comments[-1].strip() == '#':
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000915 comments[-1:] = []
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000916 return ''.join(comments)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000917
Tim Peters4efb6e92001-06-29 23:51:08 +0000918class EndOfBlock(Exception): pass
919
920class BlockFinder:
921 """Provide a tokeneater() method to detect the end of a code block."""
922 def __init__(self):
923 self.indent = 0
Johannes Gijsbersa5855d52005-03-12 16:37:11 +0000924 self.islambda = False
Johannes Gijsbers1542f342004-12-12 16:46:28 +0000925 self.started = False
926 self.passline = False
Meador Inge5b718d72015-07-23 22:49:37 -0500927 self.indecorator = False
928 self.decoratorhasargs = False
Armin Rigodd5c0232005-09-25 11:45:45 +0000929 self.last = 1
Tim Peters4efb6e92001-06-29 23:51:08 +0000930
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000931 def tokeneater(self, type, token, srowcol, erowcol, line):
Meador Inge5b718d72015-07-23 22:49:37 -0500932 if not self.started and not self.indecorator:
933 # skip any decorators
934 if token == "@":
935 self.indecorator = True
Armin Rigodd5c0232005-09-25 11:45:45 +0000936 # look for the first "def", "class" or "lambda"
Meador Inge5b718d72015-07-23 22:49:37 -0500937 elif token in ("def", "class", "lambda"):
Johannes Gijsbersa5855d52005-03-12 16:37:11 +0000938 if token == "lambda":
939 self.islambda = True
Johannes Gijsbers1542f342004-12-12 16:46:28 +0000940 self.started = True
Armin Rigodd5c0232005-09-25 11:45:45 +0000941 self.passline = True # skip to the end of the line
Meador Inge5b718d72015-07-23 22:49:37 -0500942 elif token == "(":
943 if self.indecorator:
944 self.decoratorhasargs = True
945 elif token == ")":
946 if self.indecorator:
947 self.indecorator = False
948 self.decoratorhasargs = False
Tim Peters4efb6e92001-06-29 23:51:08 +0000949 elif type == tokenize.NEWLINE:
Armin Rigodd5c0232005-09-25 11:45:45 +0000950 self.passline = False # stop skipping when a NEWLINE is seen
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000951 self.last = srowcol[0]
Armin Rigodd5c0232005-09-25 11:45:45 +0000952 if self.islambda: # lambdas always end at the first NEWLINE
953 raise EndOfBlock
Meador Inge5b718d72015-07-23 22:49:37 -0500954 # hitting a NEWLINE when in a decorator without args
955 # ends the decorator
956 if self.indecorator and not self.decoratorhasargs:
957 self.indecorator = False
Johannes Gijsbers1542f342004-12-12 16:46:28 +0000958 elif self.passline:
959 pass
Tim Peters4efb6e92001-06-29 23:51:08 +0000960 elif type == tokenize.INDENT:
961 self.indent = self.indent + 1
Johannes Gijsbers1542f342004-12-12 16:46:28 +0000962 self.passline = True
Tim Peters4efb6e92001-06-29 23:51:08 +0000963 elif type == tokenize.DEDENT:
964 self.indent = self.indent - 1
Armin Rigodd5c0232005-09-25 11:45:45 +0000965 # the end of matching indent/dedent pairs end a block
966 # (note that this only works for "def"/"class" blocks,
967 # not e.g. for "if: else:" or "try: finally:" blocks)
968 if self.indent <= 0:
969 raise EndOfBlock
970 elif self.indent == 0 and type not in (tokenize.COMMENT, tokenize.NL):
971 # any other token on the same indentation level end the previous
972 # block as well, except the pseudo-tokens COMMENT and NL.
973 raise EndOfBlock
Tim Peters4efb6e92001-06-29 23:51:08 +0000974
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000975def getblock(lines):
976 """Extract the block of code at the top of the given list of lines."""
Armin Rigodd5c0232005-09-25 11:45:45 +0000977 blockfinder = BlockFinder()
Tim Peters4efb6e92001-06-29 23:51:08 +0000978 try:
Trent Nelson428de652008-03-18 22:41:35 +0000979 tokens = tokenize.generate_tokens(iter(lines).__next__)
980 for _token in tokens:
981 blockfinder.tokeneater(*_token)
Armin Rigodd5c0232005-09-25 11:45:45 +0000982 except (EndOfBlock, IndentationError):
983 pass
984 return lines[:blockfinder.last]
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000985
986def getsourcelines(object):
987 """Return a list of source lines and starting line number for an object.
988
989 The argument may be a module, class, method, function, traceback, frame,
990 or code object. The source code is returned as a list of the lines
991 corresponding to the object and the line number indicates where in the
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200992 original source file the first line of code was found. An OSError is
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000993 raised if the source code cannot be retrieved."""
Yury Selivanov081bbf62014-09-26 17:34:54 -0400994 object = unwrap(object)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000995 lines, lnum = findsource(object)
996
Vladimir Matveev91cb2982018-08-24 07:18:00 -0700997 if istraceback(object):
998 object = object.tb_frame
999
1000 # for module or frame that corresponds to module, return all source lines
1001 if (ismodule(object) or
1002 (isframe(object) and object.f_code.co_name == "<module>")):
Meador Inge5b718d72015-07-23 22:49:37 -05001003 return lines, 0
1004 else:
1005 return getblock(lines[lnum:]), lnum + 1
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001006
1007def getsource(object):
1008 """Return the text of the source code for an object.
1009
1010 The argument may be a module, class, method, function, traceback, frame,
1011 or code object. The source code is returned as a single string. An
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02001012 OSError is raised if the source code cannot be retrieved."""
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001013 lines, lnum = getsourcelines(object)
Neal Norwitz9d72bb42007-04-17 08:48:32 +00001014 return ''.join(lines)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001015
1016# --------------------------------------------------- class tree extraction
1017def walktree(classes, children, parent):
1018 """Recursive helper function for getclasstree()."""
1019 results = []
Raymond Hettingera1a992c2005-03-11 06:46:45 +00001020 classes.sort(key=attrgetter('__module__', '__name__'))
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001021 for c in classes:
1022 results.append((c, c.__bases__))
Raymond Hettinger54f02222002-06-01 14:18:47 +00001023 if c in children:
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001024 results.append(walktree(children[c], children, c))
1025 return results
1026
Georg Brandl5ce83a02009-06-01 17:23:51 +00001027def getclasstree(classes, unique=False):
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001028 """Arrange the given list of classes into a hierarchy of nested lists.
1029
1030 Where a nested list appears, it contains classes derived from the class
1031 whose entry immediately precedes the list. Each entry is a 2-tuple
1032 containing a class and a tuple of its base classes. If the 'unique'
1033 argument is true, exactly one entry appears in the returned structure
1034 for each class in the given list. Otherwise, classes using multiple
1035 inheritance and their descendants will appear multiple times."""
1036 children = {}
1037 roots = []
1038 for c in classes:
1039 if c.__bases__:
1040 for parent in c.__bases__:
Srinivas Reddy Thatiparthy (శ్రీనివాస్ రెడ్డి తాటిపర్తి)feaefc72018-02-09 15:29:19 +05301041 if parent not in children:
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001042 children[parent] = []
Serhiy Storchaka362c1b52013-09-05 17:14:32 +03001043 if c not in children[parent]:
1044 children[parent].append(c)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001045 if unique and parent in classes: break
1046 elif c not in roots:
1047 roots.append(c)
Raymond Hettingere0d49722002-06-02 18:55:56 +00001048 for parent in children:
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001049 if parent not in classes:
1050 roots.append(parent)
1051 return walktree(roots, children, None)
1052
1053# ------------------------------------------------ argument list extraction
Christian Heimes25bb7832008-01-11 16:17:00 +00001054Arguments = namedtuple('Arguments', 'args, varargs, varkw')
1055
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001056def getargs(co):
1057 """Get information about the arguments accepted by a code object.
1058
Guido van Rossum2e65f892007-02-28 22:03:49 +00001059 Three things are returned: (args, varargs, varkw), where
Georg Brandlc1c4bf82010-10-15 16:07:41 +00001060 'args' is the list of argument names. Keyword-only arguments are
1061 appended. 'varargs' and 'varkw' are the names of the * and **
1062 arguments or None."""
Jeremy Hylton64967882003-06-27 18:14:39 +00001063 if not iscode(co):
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00001064 raise TypeError('{!r} is not a code object'.format(co))
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001065
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001066 names = co.co_varnames
Pablo Galindo8c77b8c2019-04-29 13:36:57 +01001067 nargs = co.co_argcount
Guido van Rossum2e65f892007-02-28 22:03:49 +00001068 nkwargs = co.co_kwonlyargcount
Pablo Galindocd74e662019-06-01 18:08:04 +01001069 args = list(names[:nargs])
1070 kwonlyargs = list(names[nargs:nargs+nkwargs])
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001071 step = 0
1072
Guido van Rossum2e65f892007-02-28 22:03:49 +00001073 nargs += nkwargs
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001074 varargs = None
1075 if co.co_flags & CO_VARARGS:
1076 varargs = co.co_varnames[nargs]
1077 nargs = nargs + 1
1078 varkw = None
1079 if co.co_flags & CO_VARKEYWORDS:
1080 varkw = co.co_varnames[nargs]
Pablo Galindocd74e662019-06-01 18:08:04 +01001081 return Arguments(args + kwonlyargs, varargs, varkw)
Yury Selivanov37dc2b22016-01-11 15:15:01 -05001082
1083ArgSpec = namedtuple('ArgSpec', 'args varargs keywords defaults')
1084
1085def getargspec(func):
Nick Coghlan3c35fdb2016-12-02 20:29:57 +10001086 """Get the names and default values of a function's parameters.
Yury Selivanov37dc2b22016-01-11 15:15:01 -05001087
1088 A tuple of four things is returned: (args, varargs, keywords, defaults).
1089 'args' is a list of the argument names, including keyword-only argument names.
Nick Coghlan3c35fdb2016-12-02 20:29:57 +10001090 'varargs' and 'keywords' are the names of the * and ** parameters or None.
1091 'defaults' is an n-tuple of the default values of the last n parameters.
Yury Selivanov37dc2b22016-01-11 15:15:01 -05001092
Nick Coghlan3c35fdb2016-12-02 20:29:57 +10001093 This function is deprecated, as it does not support annotations or
1094 keyword-only parameters and will raise ValueError if either is present
1095 on the supplied callable.
1096
1097 For a more structured introspection API, use inspect.signature() instead.
1098
1099 Alternatively, use getfullargspec() for an API with a similar namedtuple
1100 based interface, but full support for annotations and keyword-only
1101 parameters.
Matthias Bussonnierded87d82018-10-19 16:40:45 -07001102
1103 Deprecated since Python 3.5, use `inspect.getfullargspec()`.
Yury Selivanov37dc2b22016-01-11 15:15:01 -05001104 """
Matthias Bussonnierded87d82018-10-19 16:40:45 -07001105 warnings.warn("inspect.getargspec() is deprecated since Python 3.0, "
Nick Coghlan3c35fdb2016-12-02 20:29:57 +10001106 "use inspect.signature() or inspect.getfullargspec()",
1107 DeprecationWarning, stacklevel=2)
Pablo Galindod5d2b452019-04-30 02:01:14 +01001108 args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults, ann = \
1109 getfullargspec(func)
1110 if kwonlyargs or ann:
1111 raise ValueError("Function has keyword-only parameters or annotations"
1112 ", use inspect.signature() API which can support them")
Yury Selivanov37dc2b22016-01-11 15:15:01 -05001113 return ArgSpec(args, varargs, varkw, defaults)
1114
Christian Heimes25bb7832008-01-11 16:17:00 +00001115FullArgSpec = namedtuple('FullArgSpec',
Pablo Galindod5d2b452019-04-30 02:01:14 +01001116 'args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults, annotations')
Guido van Rossum2e65f892007-02-28 22:03:49 +00001117
1118def getfullargspec(func):
Nick Coghlan3c35fdb2016-12-02 20:29:57 +10001119 """Get the names and default values of a callable object's parameters.
Guido van Rossum2e65f892007-02-28 22:03:49 +00001120
Brett Cannon504d8852007-09-07 02:12:14 +00001121 A tuple of seven things is returned:
Nick Coghlan3c35fdb2016-12-02 20:29:57 +10001122 (args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults, annotations).
1123 'args' is a list of the parameter names.
1124 'varargs' and 'varkw' are the names of the * and ** parameters or None.
1125 'defaults' is an n-tuple of the default values of the last n parameters.
1126 'kwonlyargs' is a list of keyword-only parameter names.
Guido van Rossum2e65f892007-02-28 22:03:49 +00001127 'kwonlydefaults' is a dictionary mapping names from kwonlyargs to defaults.
Nick Coghlan3c35fdb2016-12-02 20:29:57 +10001128 'annotations' is a dictionary mapping parameter names to annotations.
Guido van Rossuma8add0e2007-05-14 22:03:55 +00001129
Nick Coghlan3c35fdb2016-12-02 20:29:57 +10001130 Notable differences from inspect.signature():
1131 - the "self" parameter is always reported, even for bound methods
1132 - wrapper chains defined by __wrapped__ *not* unwrapped automatically
Jeremy Hylton64967882003-06-27 18:14:39 +00001133 """
Yury Selivanov57d240e2014-02-19 16:27:23 -05001134 try:
1135 # Re: `skip_bound_arg=False`
1136 #
Yury Selivanovd82eddc2014-01-29 11:24:39 -05001137 # There is a notable difference in behaviour between getfullargspec
1138 # and Signature: the former always returns 'self' parameter for bound
1139 # methods, whereas the Signature always shows the actual calling
1140 # signature of the passed object.
1141 #
1142 # To simulate this behaviour, we "unbind" bound methods, to trick
1143 # inspect.signature to always return their first parameter ("self",
1144 # usually)
Yury Selivanovd82eddc2014-01-29 11:24:39 -05001145
Yury Selivanov57d240e2014-02-19 16:27:23 -05001146 # Re: `follow_wrapper_chains=False`
1147 #
1148 # getfullargspec() historically ignored __wrapped__ attributes,
1149 # so we ensure that remains the case in 3.3+
Yury Selivanovd82eddc2014-01-29 11:24:39 -05001150
Yury Selivanov5a23bd02014-03-29 13:47:11 -04001151 sig = _signature_from_callable(func,
1152 follow_wrapper_chains=False,
1153 skip_bound_arg=False,
1154 sigcls=Signature)
Yury Selivanovd82eddc2014-01-29 11:24:39 -05001155 except Exception as ex:
1156 # Most of the times 'signature' will raise ValueError.
1157 # But, it can also raise AttributeError, and, maybe something
1158 # else. So to be fully backwards compatible, we catch all
1159 # possible exceptions here, and reraise a TypeError.
1160 raise TypeError('unsupported callable') from ex
1161
1162 args = []
1163 varargs = None
1164 varkw = None
Pablo Galindo8c77b8c2019-04-29 13:36:57 +01001165 posonlyargs = []
Yury Selivanovd82eddc2014-01-29 11:24:39 -05001166 kwonlyargs = []
Yury Selivanovd82eddc2014-01-29 11:24:39 -05001167 annotations = {}
1168 defaults = ()
1169 kwdefaults = {}
1170
1171 if sig.return_annotation is not sig.empty:
1172 annotations['return'] = sig.return_annotation
1173
1174 for param in sig.parameters.values():
1175 kind = param.kind
1176 name = param.name
1177
1178 if kind is _POSITIONAL_ONLY:
Pablo Galindo8c77b8c2019-04-29 13:36:57 +01001179 posonlyargs.append(name)
1180 if param.default is not param.empty:
1181 defaults += (param.default,)
Yury Selivanovd82eddc2014-01-29 11:24:39 -05001182 elif kind is _POSITIONAL_OR_KEYWORD:
1183 args.append(name)
1184 if param.default is not param.empty:
1185 defaults += (param.default,)
1186 elif kind is _VAR_POSITIONAL:
1187 varargs = name
1188 elif kind is _KEYWORD_ONLY:
1189 kwonlyargs.append(name)
1190 if param.default is not param.empty:
1191 kwdefaults[name] = param.default
1192 elif kind is _VAR_KEYWORD:
1193 varkw = name
1194
1195 if param.annotation is not param.empty:
1196 annotations[name] = param.annotation
1197
1198 if not kwdefaults:
1199 # compatibility with 'func.__kwdefaults__'
1200 kwdefaults = None
1201
1202 if not defaults:
1203 # compatibility with 'func.__defaults__'
1204 defaults = None
1205
Pablo Galindod5d2b452019-04-30 02:01:14 +01001206 return FullArgSpec(posonlyargs + args, varargs, varkw, defaults,
1207 kwonlyargs, kwdefaults, annotations)
Yury Selivanovd82eddc2014-01-29 11:24:39 -05001208
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001209
Christian Heimes25bb7832008-01-11 16:17:00 +00001210ArgInfo = namedtuple('ArgInfo', 'args varargs keywords locals')
1211
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001212def getargvalues(frame):
1213 """Get information about arguments passed into a particular frame.
1214
1215 A tuple of four things is returned: (args, varargs, varkw, locals).
Georg Brandlc1c4bf82010-10-15 16:07:41 +00001216 'args' is a list of the argument names.
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001217 'varargs' and 'varkw' are the names of the * and ** arguments or None.
1218 'locals' is the locals dictionary of the given frame."""
1219 args, varargs, varkw = getargs(frame.f_code)
Benjamin Peterson1a6e0d02008-10-25 15:49:17 +00001220 return ArgInfo(args, varargs, varkw, frame.f_locals)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001221
Guido van Rossum2e65f892007-02-28 22:03:49 +00001222def formatannotation(annotation, base_module=None):
Guido van Rossum52e50042016-10-22 07:55:18 -07001223 if getattr(annotation, '__module__', None) == 'typing':
1224 return repr(annotation).replace('typing.', '')
Guido van Rossum2e65f892007-02-28 22:03:49 +00001225 if isinstance(annotation, type):
Georg Brandl1a3284e2007-12-02 09:40:06 +00001226 if annotation.__module__ in ('builtins', base_module):
Serhiy Storchaka521e5862014-07-22 15:00:37 +03001227 return annotation.__qualname__
1228 return annotation.__module__+'.'+annotation.__qualname__
Guido van Rossum2e65f892007-02-28 22:03:49 +00001229 return repr(annotation)
Guido van Rossuma8add0e2007-05-14 22:03:55 +00001230
Guido van Rossum2e65f892007-02-28 22:03:49 +00001231def formatannotationrelativeto(object):
Guido van Rossuma8add0e2007-05-14 22:03:55 +00001232 module = getattr(object, '__module__', None)
1233 def _formatannotation(annotation):
1234 return formatannotation(annotation, module)
1235 return _formatannotation
Guido van Rossum2e65f892007-02-28 22:03:49 +00001236
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001237def formatargspec(args, varargs=None, varkw=None, defaults=None,
Pablo Galindod5d2b452019-04-30 02:01:14 +01001238 kwonlyargs=(), kwonlydefaults={}, annotations={},
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001239 formatarg=str,
1240 formatvarargs=lambda name: '*' + name,
1241 formatvarkw=lambda name: '**' + name,
1242 formatvalue=lambda value: '=' + repr(value),
Guido van Rossum2e65f892007-02-28 22:03:49 +00001243 formatreturns=lambda text: ' -> ' + text,
Georg Brandlc1c4bf82010-10-15 16:07:41 +00001244 formatannotation=formatannotation):
Berker Peksagfa3922c2015-07-31 04:11:29 +03001245 """Format an argument spec from the values returned by getfullargspec.
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001246
Guido van Rossum2e65f892007-02-28 22:03:49 +00001247 The first seven arguments are (args, varargs, varkw, defaults,
1248 kwonlyargs, kwonlydefaults, annotations). The other five arguments
1249 are the corresponding optional formatting functions that are called to
1250 turn names and values into strings. The last argument is an optional
Matthias Bussonnier46c5cd02018-06-11 22:08:16 +02001251 function to format the sequence of arguments.
1252
1253 Deprecated since Python 3.5: use the `signature` function and `Signature`
1254 objects.
1255 """
1256
1257 from warnings import warn
1258
1259 warn("`formatargspec` is deprecated since Python 3.5. Use `signature` and "
Zackery Spytz41254eb2018-06-11 21:16:18 -06001260 "the `Signature` object directly",
Matthias Bussonnier46c5cd02018-06-11 22:08:16 +02001261 DeprecationWarning,
1262 stacklevel=2)
1263
Guido van Rossum2e65f892007-02-28 22:03:49 +00001264 def formatargandannotation(arg):
1265 result = formatarg(arg)
1266 if arg in annotations:
1267 result += ': ' + formatannotation(annotations[arg])
1268 return result
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001269 specs = []
1270 if defaults:
Pablo Galindod5d2b452019-04-30 02:01:14 +01001271 firstdefault = len(args) - len(defaults)
1272 for i, arg in enumerate(args):
Georg Brandlc1c4bf82010-10-15 16:07:41 +00001273 spec = formatargandannotation(arg)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001274 if defaults and i >= firstdefault:
1275 spec = spec + formatvalue(defaults[i - firstdefault])
1276 specs.append(spec)
Raymond Hettinger936654b2002-06-01 03:06:31 +00001277 if varargs is not None:
Guido van Rossum2e65f892007-02-28 22:03:49 +00001278 specs.append(formatvarargs(formatargandannotation(varargs)))
1279 else:
1280 if kwonlyargs:
1281 specs.append('*')
1282 if kwonlyargs:
1283 for kwonlyarg in kwonlyargs:
1284 spec = formatargandannotation(kwonlyarg)
Benjamin Peterson9953a8d2009-01-17 04:15:01 +00001285 if kwonlydefaults and kwonlyarg in kwonlydefaults:
Guido van Rossum2e65f892007-02-28 22:03:49 +00001286 spec += formatvalue(kwonlydefaults[kwonlyarg])
1287 specs.append(spec)
Raymond Hettinger936654b2002-06-01 03:06:31 +00001288 if varkw is not None:
Guido van Rossum2e65f892007-02-28 22:03:49 +00001289 specs.append(formatvarkw(formatargandannotation(varkw)))
Neal Norwitz9d72bb42007-04-17 08:48:32 +00001290 result = '(' + ', '.join(specs) + ')'
Guido van Rossum2e65f892007-02-28 22:03:49 +00001291 if 'return' in annotations:
1292 result += formatreturns(formatannotation(annotations['return']))
1293 return result
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001294
1295def formatargvalues(args, varargs, varkw, locals,
1296 formatarg=str,
1297 formatvarargs=lambda name: '*' + name,
1298 formatvarkw=lambda name: '**' + name,
Georg Brandlc1c4bf82010-10-15 16:07:41 +00001299 formatvalue=lambda value: '=' + repr(value)):
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001300 """Format an argument spec from the 4 values returned by getargvalues.
1301
1302 The first four arguments are (args, varargs, varkw, locals). The
1303 next four arguments are the corresponding optional formatting functions
1304 that are called to turn names and values into strings. The ninth
1305 argument is an optional function to format the sequence of arguments."""
1306 def convert(name, locals=locals,
1307 formatarg=formatarg, formatvalue=formatvalue):
1308 return formatarg(name) + formatvalue(locals[name])
1309 specs = []
1310 for i in range(len(args)):
Georg Brandlc1c4bf82010-10-15 16:07:41 +00001311 specs.append(convert(args[i]))
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001312 if varargs:
1313 specs.append(formatvarargs(varargs) + formatvalue(locals[varargs]))
1314 if varkw:
1315 specs.append(formatvarkw(varkw) + formatvalue(locals[varkw]))
Neal Norwitz9d72bb42007-04-17 08:48:32 +00001316 return '(' + ', '.join(specs) + ')'
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001317
Benjamin Petersone109c702011-06-24 09:37:26 -05001318def _missing_arguments(f_name, argnames, pos, values):
1319 names = [repr(name) for name in argnames if name not in values]
1320 missing = len(names)
1321 if missing == 1:
1322 s = names[0]
1323 elif missing == 2:
1324 s = "{} and {}".format(*names)
1325 else:
Yury Selivanovdccfa132014-03-27 18:42:52 -04001326 tail = ", {} and {}".format(*names[-2:])
Benjamin Petersone109c702011-06-24 09:37:26 -05001327 del names[-2:]
1328 s = ", ".join(names) + tail
1329 raise TypeError("%s() missing %i required %s argument%s: %s" %
1330 (f_name, missing,
1331 "positional" if pos else "keyword-only",
1332 "" if missing == 1 else "s", s))
1333
1334def _too_many(f_name, args, kwonly, varargs, defcount, given, values):
Benjamin Petersonb204a422011-06-05 22:04:07 -05001335 atleast = len(args) - defcount
Benjamin Petersonb204a422011-06-05 22:04:07 -05001336 kwonly_given = len([arg for arg in kwonly if arg in values])
1337 if varargs:
1338 plural = atleast != 1
1339 sig = "at least %d" % (atleast,)
1340 elif defcount:
1341 plural = True
1342 sig = "from %d to %d" % (atleast, len(args))
1343 else:
1344 plural = len(args) != 1
1345 sig = str(len(args))
1346 kwonly_sig = ""
1347 if kwonly_given:
1348 msg = " positional argument%s (and %d keyword-only argument%s)"
1349 kwonly_sig = (msg % ("s" if given != 1 else "", kwonly_given,
1350 "s" if kwonly_given != 1 else ""))
1351 raise TypeError("%s() takes %s positional argument%s but %d%s %s given" %
1352 (f_name, sig, "s" if plural else "", given, kwonly_sig,
1353 "was" if given == 1 and not kwonly_given else "were"))
1354
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03001355def getcallargs(func, /, *positional, **named):
Benjamin Peterson25cd7eb2010-03-30 18:42:32 +00001356 """Get the mapping of arguments to values.
1357
1358 A dict is returned, with keys the function argument names (including the
1359 names of the * and ** arguments, if any), and values the respective bound
1360 values from 'positional' and 'named'."""
1361 spec = getfullargspec(func)
Pablo Galindod5d2b452019-04-30 02:01:14 +01001362 args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults, ann = spec
Benjamin Peterson25cd7eb2010-03-30 18:42:32 +00001363 f_name = func.__name__
1364 arg2value = {}
1365
Benjamin Petersonb204a422011-06-05 22:04:07 -05001366
Benjamin Peterson25cd7eb2010-03-30 18:42:32 +00001367 if ismethod(func) and func.__self__ is not None:
1368 # implicit 'self' (or 'cls' for classmethods) argument
1369 positional = (func.__self__,) + positional
1370 num_pos = len(positional)
Benjamin Peterson25cd7eb2010-03-30 18:42:32 +00001371 num_args = len(args)
1372 num_defaults = len(defaults) if defaults else 0
Benjamin Peterson25cd7eb2010-03-30 18:42:32 +00001373
Benjamin Petersonb204a422011-06-05 22:04:07 -05001374 n = min(num_pos, num_args)
1375 for i in range(n):
Pablo Galindod5d2b452019-04-30 02:01:14 +01001376 arg2value[args[i]] = positional[i]
Benjamin Petersonb204a422011-06-05 22:04:07 -05001377 if varargs:
1378 arg2value[varargs] = tuple(positional[n:])
1379 possible_kwargs = set(args + kwonlyargs)
Benjamin Peterson25cd7eb2010-03-30 18:42:32 +00001380 if varkw:
Benjamin Petersonb204a422011-06-05 22:04:07 -05001381 arg2value[varkw] = {}
1382 for kw, value in named.items():
1383 if kw not in possible_kwargs:
1384 if not varkw:
1385 raise TypeError("%s() got an unexpected keyword argument %r" %
1386 (f_name, kw))
1387 arg2value[varkw][kw] = value
1388 continue
1389 if kw in arg2value:
1390 raise TypeError("%s() got multiple values for argument %r" %
1391 (f_name, kw))
1392 arg2value[kw] = value
1393 if num_pos > num_args and not varargs:
Benjamin Petersone109c702011-06-24 09:37:26 -05001394 _too_many(f_name, args, kwonlyargs, varargs, num_defaults,
1395 num_pos, arg2value)
Benjamin Petersonb204a422011-06-05 22:04:07 -05001396 if num_pos < num_args:
Benjamin Petersone109c702011-06-24 09:37:26 -05001397 req = args[:num_args - num_defaults]
1398 for arg in req:
Benjamin Petersonb204a422011-06-05 22:04:07 -05001399 if arg not in arg2value:
Benjamin Petersone109c702011-06-24 09:37:26 -05001400 _missing_arguments(f_name, req, True, arg2value)
Benjamin Petersonb204a422011-06-05 22:04:07 -05001401 for i, arg in enumerate(args[num_args - num_defaults:]):
1402 if arg not in arg2value:
1403 arg2value[arg] = defaults[i]
Benjamin Petersone109c702011-06-24 09:37:26 -05001404 missing = 0
Benjamin Petersonb204a422011-06-05 22:04:07 -05001405 for kwarg in kwonlyargs:
1406 if kwarg not in arg2value:
Yury Selivanov875df202014-03-27 18:23:03 -04001407 if kwonlydefaults and kwarg in kwonlydefaults:
Benjamin Petersone109c702011-06-24 09:37:26 -05001408 arg2value[kwarg] = kwonlydefaults[kwarg]
1409 else:
1410 missing += 1
1411 if missing:
1412 _missing_arguments(f_name, kwonlyargs, False, arg2value)
Benjamin Peterson25cd7eb2010-03-30 18:42:32 +00001413 return arg2value
1414
Nick Coghlan2f92e542012-06-23 19:39:55 +10001415ClosureVars = namedtuple('ClosureVars', 'nonlocals globals builtins unbound')
1416
1417def getclosurevars(func):
1418 """
1419 Get the mapping of free variables to their current values.
1420
Meador Inge8fda3592012-07-19 21:33:21 -05001421 Returns a named tuple of dicts mapping the current nonlocal, global
Nick Coghlan2f92e542012-06-23 19:39:55 +10001422 and builtin references as seen by the body of the function. A final
1423 set of unbound names that could not be resolved is also provided.
1424 """
1425
1426 if ismethod(func):
1427 func = func.__func__
1428
1429 if not isfunction(func):
Serhiy Storchakaa4a30202017-11-28 22:54:42 +02001430 raise TypeError("{!r} is not a Python function".format(func))
Nick Coghlan2f92e542012-06-23 19:39:55 +10001431
1432 code = func.__code__
1433 # Nonlocal references are named in co_freevars and resolved
1434 # by looking them up in __closure__ by positional index
1435 if func.__closure__ is None:
1436 nonlocal_vars = {}
1437 else:
1438 nonlocal_vars = {
1439 var : cell.cell_contents
1440 for var, cell in zip(code.co_freevars, func.__closure__)
1441 }
1442
1443 # Global and builtin references are named in co_names and resolved
1444 # by looking them up in __globals__ or __builtins__
1445 global_ns = func.__globals__
1446 builtin_ns = global_ns.get("__builtins__", builtins.__dict__)
1447 if ismodule(builtin_ns):
1448 builtin_ns = builtin_ns.__dict__
1449 global_vars = {}
1450 builtin_vars = {}
1451 unbound_names = set()
1452 for name in code.co_names:
1453 if name in ("None", "True", "False"):
1454 # Because these used to be builtins instead of keywords, they
1455 # may still show up as name references. We ignore them.
1456 continue
1457 try:
1458 global_vars[name] = global_ns[name]
1459 except KeyError:
1460 try:
1461 builtin_vars[name] = builtin_ns[name]
1462 except KeyError:
1463 unbound_names.add(name)
1464
1465 return ClosureVars(nonlocal_vars, global_vars,
1466 builtin_vars, unbound_names)
1467
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001468# -------------------------------------------------- stack frame extraction
Christian Heimes25bb7832008-01-11 16:17:00 +00001469
1470Traceback = namedtuple('Traceback', 'filename lineno function code_context index')
1471
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001472def getframeinfo(frame, context=1):
1473 """Get information about a frame or traceback object.
1474
1475 A tuple of five things is returned: the filename, the line number of
1476 the current line, the function name, a list of lines of context from
1477 the source code, and the index of the current line within that list.
1478 The optional second argument specifies the number of lines of context
1479 to return, which are centered around the current line."""
1480 if istraceback(frame):
Andrew M. Kuchlingba8b6bc2004-06-05 14:11:59 +00001481 lineno = frame.tb_lineno
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001482 frame = frame.tb_frame
Andrew M. Kuchlingba8b6bc2004-06-05 14:11:59 +00001483 else:
1484 lineno = frame.f_lineno
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001485 if not isframe(frame):
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00001486 raise TypeError('{!r} is not a frame or traceback object'.format(frame))
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001487
Neil Schemenauerf06f8532002-03-23 23:51:04 +00001488 filename = getsourcefile(frame) or getfile(frame)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001489 if context > 0:
Guido van Rossum54e54c62001-09-04 19:14:14 +00001490 start = lineno - 1 - context//2
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001491 try:
1492 lines, lnum = findsource(frame)
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02001493 except OSError:
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +00001494 lines = index = None
1495 else:
Raymond Hettingera0501712004-06-15 11:22:53 +00001496 start = max(0, min(start, len(lines) - context))
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001497 lines = lines[start:start+context]
Ka-Ping Yee59ade082001-03-01 03:55:35 +00001498 index = lineno - 1 - start
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001499 else:
1500 lines = index = None
1501
Christian Heimes25bb7832008-01-11 16:17:00 +00001502 return Traceback(filename, lineno, frame.f_code.co_name, lines, index)
Ka-Ping Yee59ade082001-03-01 03:55:35 +00001503
1504def getlineno(frame):
1505 """Get the line number from a frame object, allowing for optimization."""
Michael W. Hudsondd32a912002-08-15 14:59:02 +00001506 # FrameType.f_lineno is now a descriptor that grovels co_lnotab
1507 return frame.f_lineno
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001508
Antoine Pitroucdcafb72014-08-24 10:50:28 -04001509FrameInfo = namedtuple('FrameInfo', ('frame',) + Traceback._fields)
1510
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001511def getouterframes(frame, context=1):
1512 """Get a list of records for a frame and all higher (calling) frames.
1513
1514 Each record contains a frame object, filename, line number, function
1515 name, a list of lines of context, and index within the context."""
1516 framelist = []
1517 while frame:
Antoine Pitroucdcafb72014-08-24 10:50:28 -04001518 frameinfo = (frame,) + getframeinfo(frame, context)
1519 framelist.append(FrameInfo(*frameinfo))
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001520 frame = frame.f_back
1521 return framelist
1522
1523def getinnerframes(tb, context=1):
1524 """Get a list of records for a traceback's frame and all lower frames.
1525
1526 Each record contains a frame object, filename, line number, function
1527 name, a list of lines of context, and index within the context."""
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001528 framelist = []
1529 while tb:
Antoine Pitroucdcafb72014-08-24 10:50:28 -04001530 frameinfo = (tb.tb_frame,) + getframeinfo(tb, context)
1531 framelist.append(FrameInfo(*frameinfo))
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001532 tb = tb.tb_next
1533 return framelist
1534
Benjamin Peterson42ac4752010-08-09 13:05:35 +00001535def currentframe():
Benjamin Petersona3a3fc62010-08-09 15:49:56 +00001536 """Return the frame of the caller or None if this is not possible."""
Benjamin Peterson42ac4752010-08-09 13:05:35 +00001537 return sys._getframe(1) if hasattr(sys, "_getframe") else None
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001538
1539def stack(context=1):
1540 """Return a list of records for the stack above the caller's frame."""
Jeremy Hyltonab919022003-06-27 18:41:20 +00001541 return getouterframes(sys._getframe(1), context)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001542
1543def trace(context=1):
Tim Peters85ba6732001-02-28 08:26:44 +00001544 """Return a list of records for the stack below the current exception."""
Fred Draked451ec12002-04-26 02:29:55 +00001545 return getinnerframes(sys.exc_info()[2], context)
Michael Foord95fc51d2010-11-20 15:07:30 +00001546
1547
1548# ------------------------------------------------ static version of getattr
1549
1550_sentinel = object()
1551
Michael Foorde5162652010-11-20 16:40:44 +00001552def _static_getmro(klass):
1553 return type.__dict__['__mro__'].__get__(klass)
1554
Michael Foord95fc51d2010-11-20 15:07:30 +00001555def _check_instance(obj, attr):
1556 instance_dict = {}
1557 try:
1558 instance_dict = object.__getattribute__(obj, "__dict__")
1559 except AttributeError:
1560 pass
Michael Foorddcebe0f2011-03-15 19:20:44 -04001561 return dict.get(instance_dict, attr, _sentinel)
Michael Foord95fc51d2010-11-20 15:07:30 +00001562
1563
1564def _check_class(klass, attr):
Michael Foorde5162652010-11-20 16:40:44 +00001565 for entry in _static_getmro(klass):
Michael Foorda51623b2011-12-18 22:01:40 +00001566 if _shadowed_dict(type(entry)) is _sentinel:
Michael Foorddcebe0f2011-03-15 19:20:44 -04001567 try:
1568 return entry.__dict__[attr]
1569 except KeyError:
1570 pass
Michael Foord95fc51d2010-11-20 15:07:30 +00001571 return _sentinel
1572
Michael Foord35184ed2010-11-20 16:58:30 +00001573def _is_type(obj):
1574 try:
1575 _static_getmro(obj)
1576 except TypeError:
1577 return False
1578 return True
1579
Michael Foorddcebe0f2011-03-15 19:20:44 -04001580def _shadowed_dict(klass):
1581 dict_attr = type.__dict__["__dict__"]
1582 for entry in _static_getmro(klass):
1583 try:
1584 class_dict = dict_attr.__get__(entry)["__dict__"]
1585 except KeyError:
1586 pass
1587 else:
Inada Naoki8f9cc872019-09-05 13:07:08 +09001588 if not (type(class_dict) is types.GetSetDescriptorType and
Michael Foorddcebe0f2011-03-15 19:20:44 -04001589 class_dict.__name__ == "__dict__" and
1590 class_dict.__objclass__ is entry):
Michael Foorda51623b2011-12-18 22:01:40 +00001591 return class_dict
1592 return _sentinel
Michael Foord95fc51d2010-11-20 15:07:30 +00001593
1594def getattr_static(obj, attr, default=_sentinel):
1595 """Retrieve attributes without triggering dynamic lookup via the
1596 descriptor protocol, __getattr__ or __getattribute__.
1597
1598 Note: this function may not be able to retrieve all attributes
1599 that getattr can fetch (like dynamically created attributes)
1600 and may find attributes that getattr can't (like descriptors
1601 that raise AttributeError). It can also return descriptor objects
1602 instead of instance members in some cases. See the
1603 documentation for details.
1604 """
1605 instance_result = _sentinel
Michael Foord35184ed2010-11-20 16:58:30 +00001606 if not _is_type(obj):
Michael Foordcc7ebb82010-11-20 16:20:16 +00001607 klass = type(obj)
Michael Foorda51623b2011-12-18 22:01:40 +00001608 dict_attr = _shadowed_dict(klass)
1609 if (dict_attr is _sentinel or
Inada Naoki8f9cc872019-09-05 13:07:08 +09001610 type(dict_attr) is types.MemberDescriptorType):
Michael Foorddcebe0f2011-03-15 19:20:44 -04001611 instance_result = _check_instance(obj, attr)
Michael Foord95fc51d2010-11-20 15:07:30 +00001612 else:
1613 klass = obj
1614
1615 klass_result = _check_class(klass, attr)
1616
1617 if instance_result is not _sentinel and klass_result is not _sentinel:
1618 if (_check_class(type(klass_result), '__get__') is not _sentinel and
1619 _check_class(type(klass_result), '__set__') is not _sentinel):
1620 return klass_result
1621
1622 if instance_result is not _sentinel:
1623 return instance_result
1624 if klass_result is not _sentinel:
1625 return klass_result
1626
1627 if obj is klass:
1628 # for types we check the metaclass too
Michael Foorde5162652010-11-20 16:40:44 +00001629 for entry in _static_getmro(type(klass)):
Michael Foord3ba95f82011-12-22 01:13:37 +00001630 if _shadowed_dict(type(entry)) is _sentinel:
1631 try:
1632 return entry.__dict__[attr]
1633 except KeyError:
1634 pass
Michael Foord95fc51d2010-11-20 15:07:30 +00001635 if default is not _sentinel:
1636 return default
1637 raise AttributeError(attr)
Nick Coghlane0f04652010-11-21 03:44:04 +00001638
1639
Nick Coghlan04e2e3f2012-06-23 19:52:05 +10001640# ------------------------------------------------ generator introspection
1641
Nick Coghlan7921b9f2010-11-30 06:36:04 +00001642GEN_CREATED = 'GEN_CREATED'
1643GEN_RUNNING = 'GEN_RUNNING'
1644GEN_SUSPENDED = 'GEN_SUSPENDED'
1645GEN_CLOSED = 'GEN_CLOSED'
Nick Coghlane0f04652010-11-21 03:44:04 +00001646
1647def getgeneratorstate(generator):
1648 """Get current state of a generator-iterator.
1649
1650 Possible states are:
1651 GEN_CREATED: Waiting to start execution.
1652 GEN_RUNNING: Currently being executed by the interpreter.
1653 GEN_SUSPENDED: Currently suspended at a yield expression.
1654 GEN_CLOSED: Execution has completed.
1655 """
1656 if generator.gi_running:
1657 return GEN_RUNNING
1658 if generator.gi_frame is None:
1659 return GEN_CLOSED
1660 if generator.gi_frame.f_lasti == -1:
1661 return GEN_CREATED
1662 return GEN_SUSPENDED
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07001663
1664
Nick Coghlan04e2e3f2012-06-23 19:52:05 +10001665def getgeneratorlocals(generator):
1666 """
1667 Get the mapping of generator local variables to their current values.
1668
1669 A dict is returned, with the keys the local variable names and values the
1670 bound values."""
1671
1672 if not isgenerator(generator):
Serhiy Storchakaa4a30202017-11-28 22:54:42 +02001673 raise TypeError("{!r} is not a Python generator".format(generator))
Nick Coghlan04e2e3f2012-06-23 19:52:05 +10001674
1675 frame = getattr(generator, "gi_frame", None)
1676 if frame is not None:
1677 return generator.gi_frame.f_locals
1678 else:
1679 return {}
1680
Yury Selivanov5376ba92015-06-22 12:19:30 -04001681
1682# ------------------------------------------------ coroutine introspection
1683
1684CORO_CREATED = 'CORO_CREATED'
1685CORO_RUNNING = 'CORO_RUNNING'
1686CORO_SUSPENDED = 'CORO_SUSPENDED'
1687CORO_CLOSED = 'CORO_CLOSED'
1688
1689def getcoroutinestate(coroutine):
1690 """Get current state of a coroutine object.
1691
1692 Possible states are:
1693 CORO_CREATED: Waiting to start execution.
1694 CORO_RUNNING: Currently being executed by the interpreter.
1695 CORO_SUSPENDED: Currently suspended at an await expression.
1696 CORO_CLOSED: Execution has completed.
1697 """
1698 if coroutine.cr_running:
1699 return CORO_RUNNING
1700 if coroutine.cr_frame is None:
1701 return CORO_CLOSED
1702 if coroutine.cr_frame.f_lasti == -1:
1703 return CORO_CREATED
1704 return CORO_SUSPENDED
1705
1706
1707def getcoroutinelocals(coroutine):
1708 """
1709 Get the mapping of coroutine local variables to their current values.
1710
1711 A dict is returned, with the keys the local variable names and values the
1712 bound values."""
1713 frame = getattr(coroutine, "cr_frame", None)
1714 if frame is not None:
1715 return frame.f_locals
1716 else:
1717 return {}
1718
1719
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07001720###############################################################################
1721### Function Signature Object (PEP 362)
1722###############################################################################
1723
1724
1725_WrapperDescriptor = type(type.__call__)
1726_MethodWrapper = type(all.__call__)
Larry Hastings5c661892014-01-24 06:17:25 -08001727_ClassMethodWrapper = type(int.__dict__['from_bytes'])
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07001728
1729_NonUserDefinedCallables = (_WrapperDescriptor,
1730 _MethodWrapper,
Larry Hastings5c661892014-01-24 06:17:25 -08001731 _ClassMethodWrapper,
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07001732 types.BuiltinFunctionType)
1733
1734
Yury Selivanov421f0c72014-01-29 12:05:40 -05001735def _signature_get_user_defined_method(cls, method_name):
Yury Selivanov5a23bd02014-03-29 13:47:11 -04001736 """Private helper. Checks if ``cls`` has an attribute
1737 named ``method_name`` and returns it only if it is a
1738 pure python function.
1739 """
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07001740 try:
1741 meth = getattr(cls, method_name)
1742 except AttributeError:
1743 return
1744 else:
1745 if not isinstance(meth, _NonUserDefinedCallables):
1746 # Once '__signature__' will be added to 'C'-level
1747 # callables, this check won't be necessary
1748 return meth
1749
1750
Yury Selivanov62560fb2014-01-28 12:26:24 -05001751def _signature_get_partial(wrapped_sig, partial, extra_args=()):
Yury Selivanov5a23bd02014-03-29 13:47:11 -04001752 """Private helper to calculate how 'wrapped_sig' signature will
1753 look like after applying a 'functools.partial' object (or alike)
1754 on it.
1755 """
Yury Selivanov62560fb2014-01-28 12:26:24 -05001756
Yury Selivanov3f73ca22014-04-08 11:30:45 -04001757 old_params = wrapped_sig.parameters
Inada Naoki21105512020-03-02 18:54:49 +09001758 new_params = OrderedDict(old_params.items())
Yury Selivanovda5fe4f2014-01-27 17:28:37 -05001759
1760 partial_args = partial.args or ()
1761 partial_keywords = partial.keywords or {}
1762
1763 if extra_args:
1764 partial_args = extra_args + partial_args
1765
1766 try:
1767 ba = wrapped_sig.bind_partial(*partial_args, **partial_keywords)
1768 except TypeError as ex:
1769 msg = 'partial object {!r} has incorrect arguments'.format(partial)
1770 raise ValueError(msg) from ex
1771
Yury Selivanovda5fe4f2014-01-27 17:28:37 -05001772
Yury Selivanov3f73ca22014-04-08 11:30:45 -04001773 transform_to_kwonly = False
1774 for param_name, param in old_params.items():
1775 try:
1776 arg_value = ba.arguments[param_name]
1777 except KeyError:
1778 pass
1779 else:
1780 if param.kind is _POSITIONAL_ONLY:
1781 # If positional-only parameter is bound by partial,
1782 # it effectively disappears from the signature
Inada Naoki21105512020-03-02 18:54:49 +09001783 new_params.pop(param_name)
Yury Selivanov3f73ca22014-04-08 11:30:45 -04001784 continue
1785
1786 if param.kind is _POSITIONAL_OR_KEYWORD:
1787 if param_name in partial_keywords:
1788 # This means that this parameter, and all parameters
1789 # after it should be keyword-only (and var-positional
1790 # should be removed). Here's why. Consider the following
1791 # function:
1792 # foo(a, b, *args, c):
1793 # pass
1794 #
1795 # "partial(foo, a='spam')" will have the following
1796 # signature: "(*, a='spam', b, c)". Because attempting
1797 # to call that partial with "(10, 20)" arguments will
1798 # raise a TypeError, saying that "a" argument received
1799 # multiple values.
1800 transform_to_kwonly = True
1801 # Set the new default value
Inada Naoki21105512020-03-02 18:54:49 +09001802 new_params[param_name] = param.replace(default=arg_value)
Yury Selivanov3f73ca22014-04-08 11:30:45 -04001803 else:
1804 # was passed as a positional argument
Inada Naoki21105512020-03-02 18:54:49 +09001805 new_params.pop(param.name)
Yury Selivanov3f73ca22014-04-08 11:30:45 -04001806 continue
1807
1808 if param.kind is _KEYWORD_ONLY:
1809 # Set the new default value
Inada Naoki21105512020-03-02 18:54:49 +09001810 new_params[param_name] = param.replace(default=arg_value)
Yury Selivanov3f73ca22014-04-08 11:30:45 -04001811
1812 if transform_to_kwonly:
1813 assert param.kind is not _POSITIONAL_ONLY
1814
1815 if param.kind is _POSITIONAL_OR_KEYWORD:
Inada Naoki21105512020-03-02 18:54:49 +09001816 new_param = new_params[param_name].replace(kind=_KEYWORD_ONLY)
1817 new_params[param_name] = new_param
1818 new_params.move_to_end(param_name)
Yury Selivanov3f73ca22014-04-08 11:30:45 -04001819 elif param.kind in (_KEYWORD_ONLY, _VAR_KEYWORD):
Inada Naoki21105512020-03-02 18:54:49 +09001820 new_params.move_to_end(param_name)
1821 elif param.kind is _VAR_POSITIONAL:
1822 new_params.pop(param.name)
Yury Selivanovda5fe4f2014-01-27 17:28:37 -05001823
1824 return wrapped_sig.replace(parameters=new_params.values())
1825
1826
Yury Selivanov62560fb2014-01-28 12:26:24 -05001827def _signature_bound_method(sig):
Yury Selivanov5a23bd02014-03-29 13:47:11 -04001828 """Private helper to transform signatures for unbound
1829 functions to bound methods.
1830 """
Yury Selivanov62560fb2014-01-28 12:26:24 -05001831
1832 params = tuple(sig.parameters.values())
1833
1834 if not params or params[0].kind in (_VAR_KEYWORD, _KEYWORD_ONLY):
1835 raise ValueError('invalid method signature')
1836
1837 kind = params[0].kind
1838 if kind in (_POSITIONAL_OR_KEYWORD, _POSITIONAL_ONLY):
1839 # Drop first parameter:
1840 # '(p1, p2[, ...])' -> '(p2[, ...])'
1841 params = params[1:]
1842 else:
1843 if kind is not _VAR_POSITIONAL:
1844 # Unless we add a new parameter type we never
1845 # get here
1846 raise ValueError('invalid argument type')
1847 # It's a var-positional parameter.
1848 # Do nothing. '(*args[, ...])' -> '(*args[, ...])'
1849
1850 return sig.replace(parameters=params)
1851
1852
Yury Selivanovb77511d2014-01-29 10:46:14 -05001853def _signature_is_builtin(obj):
Yury Selivanov5a23bd02014-03-29 13:47:11 -04001854 """Private helper to test if `obj` is a callable that might
1855 support Argument Clinic's __text_signature__ protocol.
1856 """
Yury Selivanov1d241832014-02-02 12:51:20 -05001857 return (isbuiltin(obj) or
Yury Selivanovb77511d2014-01-29 10:46:14 -05001858 ismethoddescriptor(obj) or
Yury Selivanov1d241832014-02-02 12:51:20 -05001859 isinstance(obj, _NonUserDefinedCallables) or
Yury Selivanovb77511d2014-01-29 10:46:14 -05001860 # Can't test 'isinstance(type)' here, as it would
1861 # also be True for regular python classes
1862 obj in (type, object))
1863
1864
Yury Selivanov63da7c72014-01-31 14:48:37 -05001865def _signature_is_functionlike(obj):
Yury Selivanov5a23bd02014-03-29 13:47:11 -04001866 """Private helper to test if `obj` is a duck type of FunctionType.
1867 A good example of such objects are functions compiled with
1868 Cython, which have all attributes that a pure Python function
1869 would have, but have their code statically compiled.
1870 """
Yury Selivanov63da7c72014-01-31 14:48:37 -05001871
1872 if not callable(obj) or isclass(obj):
1873 # All function-like objects are obviously callables,
1874 # and not classes.
1875 return False
1876
1877 name = getattr(obj, '__name__', None)
1878 code = getattr(obj, '__code__', None)
1879 defaults = getattr(obj, '__defaults__', _void) # Important to use _void ...
1880 kwdefaults = getattr(obj, '__kwdefaults__', _void) # ... and not None here
1881 annotations = getattr(obj, '__annotations__', None)
1882
1883 return (isinstance(code, types.CodeType) and
1884 isinstance(name, str) and
1885 (defaults is None or isinstance(defaults, tuple)) and
1886 (kwdefaults is None or isinstance(kwdefaults, dict)) and
1887 isinstance(annotations, dict))
1888
1889
Yury Selivanovd82eddc2014-01-29 11:24:39 -05001890def _signature_get_bound_param(spec):
Yury Selivanov5a23bd02014-03-29 13:47:11 -04001891 """ Private helper to get first parameter name from a
1892 __text_signature__ of a builtin method, which should
1893 be in the following format: '($param1, ...)'.
1894 Assumptions are that the first argument won't have
1895 a default value or an annotation.
1896 """
Yury Selivanovd82eddc2014-01-29 11:24:39 -05001897
1898 assert spec.startswith('($')
1899
1900 pos = spec.find(',')
1901 if pos == -1:
1902 pos = spec.find(')')
1903
1904 cpos = spec.find(':')
1905 assert cpos == -1 or cpos > pos
1906
1907 cpos = spec.find('=')
1908 assert cpos == -1 or cpos > pos
1909
1910 return spec[2:pos]
1911
1912
Larry Hastings2623c8c2014-02-08 22:15:29 -08001913def _signature_strip_non_python_syntax(signature):
1914 """
Yury Selivanov5a23bd02014-03-29 13:47:11 -04001915 Private helper function. Takes a signature in Argument Clinic's
1916 extended signature format.
1917
Larry Hastings2623c8c2014-02-08 22:15:29 -08001918 Returns a tuple of three things:
1919 * that signature re-rendered in standard Python syntax,
1920 * the index of the "self" parameter (generally 0), or None if
1921 the function does not have a "self" parameter, and
1922 * the index of the last "positional only" parameter,
1923 or None if the signature has no positional-only parameters.
1924 """
1925
1926 if not signature:
1927 return signature, None, None
1928
1929 self_parameter = None
1930 last_positional_only = None
1931
1932 lines = [l.encode('ascii') for l in signature.split('\n')]
1933 generator = iter(lines).__next__
1934 token_stream = tokenize.tokenize(generator)
1935
1936 delayed_comma = False
1937 skip_next_comma = False
1938 text = []
1939 add = text.append
1940
1941 current_parameter = 0
1942 OP = token.OP
1943 ERRORTOKEN = token.ERRORTOKEN
1944
1945 # token stream always starts with ENCODING token, skip it
1946 t = next(token_stream)
1947 assert t.type == tokenize.ENCODING
1948
1949 for t in token_stream:
1950 type, string = t.type, t.string
1951
1952 if type == OP:
1953 if string == ',':
1954 if skip_next_comma:
1955 skip_next_comma = False
1956 else:
1957 assert not delayed_comma
1958 delayed_comma = True
1959 current_parameter += 1
1960 continue
1961
1962 if string == '/':
1963 assert not skip_next_comma
1964 assert last_positional_only is None
1965 skip_next_comma = True
1966 last_positional_only = current_parameter - 1
1967 continue
1968
1969 if (type == ERRORTOKEN) and (string == '$'):
1970 assert self_parameter is None
1971 self_parameter = current_parameter
1972 continue
1973
1974 if delayed_comma:
1975 delayed_comma = False
1976 if not ((type == OP) and (string == ')')):
1977 add(', ')
1978 add(string)
1979 if (string == ','):
1980 add(' ')
1981 clean_signature = ''.join(text)
1982 return clean_signature, self_parameter, last_positional_only
1983
1984
Yury Selivanov57d240e2014-02-19 16:27:23 -05001985def _signature_fromstr(cls, obj, s, skip_bound_arg=True):
Yury Selivanov5a23bd02014-03-29 13:47:11 -04001986 """Private helper to parse content of '__text_signature__'
1987 and return a Signature based on it.
1988 """
INADA Naoki37420de2018-01-27 10:10:06 +09001989 # Lazy import ast because it's relatively heavy and
1990 # it's not used for other than this function.
1991 import ast
Yury Selivanov5a23bd02014-03-29 13:47:11 -04001992
Yury Selivanov7d2bfed2014-02-03 02:46:07 -05001993 Parameter = cls._parameter_cls
1994
Larry Hastings2623c8c2014-02-08 22:15:29 -08001995 clean_signature, self_parameter, last_positional_only = \
1996 _signature_strip_non_python_syntax(s)
Yury Selivanov7d2bfed2014-02-03 02:46:07 -05001997
Larry Hastings2623c8c2014-02-08 22:15:29 -08001998 program = "def foo" + clean_signature + ": pass"
Yury Selivanov7d2bfed2014-02-03 02:46:07 -05001999
2000 try:
Larry Hastings2623c8c2014-02-08 22:15:29 -08002001 module = ast.parse(program)
Yury Selivanov7d2bfed2014-02-03 02:46:07 -05002002 except SyntaxError:
2003 module = None
2004
2005 if not isinstance(module, ast.Module):
2006 raise ValueError("{!r} builtin has invalid signature".format(obj))
2007
2008 f = module.body[0]
2009
2010 parameters = []
2011 empty = Parameter.empty
2012 invalid = object()
2013
2014 module = None
2015 module_dict = {}
2016 module_name = getattr(obj, '__module__', None)
2017 if module_name:
2018 module = sys.modules.get(module_name, None)
2019 if module:
2020 module_dict = module.__dict__
INADA Naoki6f85b822018-10-05 01:47:09 +09002021 sys_module_dict = sys.modules.copy()
Yury Selivanov7d2bfed2014-02-03 02:46:07 -05002022
2023 def parse_name(node):
2024 assert isinstance(node, ast.arg)
Srinivas Reddy Thatiparthy (శ్రీనివాస్ రెడ్డి తాటిపర్తి)feaefc72018-02-09 15:29:19 +05302025 if node.annotation is not None:
Yury Selivanov7d2bfed2014-02-03 02:46:07 -05002026 raise ValueError("Annotations are not currently supported")
2027 return node.arg
2028
2029 def wrap_value(s):
2030 try:
2031 value = eval(s, module_dict)
2032 except NameError:
2033 try:
2034 value = eval(s, sys_module_dict)
2035 except NameError:
2036 raise RuntimeError()
2037
Serhiy Storchaka3f228112018-09-27 17:42:37 +03002038 if isinstance(value, (str, int, float, bytes, bool, type(None))):
2039 return ast.Constant(value)
Yury Selivanov7d2bfed2014-02-03 02:46:07 -05002040 raise RuntimeError()
2041
2042 class RewriteSymbolics(ast.NodeTransformer):
2043 def visit_Attribute(self, node):
2044 a = []
2045 n = node
2046 while isinstance(n, ast.Attribute):
2047 a.append(n.attr)
2048 n = n.value
2049 if not isinstance(n, ast.Name):
2050 raise RuntimeError()
2051 a.append(n.id)
2052 value = ".".join(reversed(a))
2053 return wrap_value(value)
2054
2055 def visit_Name(self, node):
2056 if not isinstance(node.ctx, ast.Load):
2057 raise ValueError()
2058 return wrap_value(node.id)
2059
2060 def p(name_node, default_node, default=empty):
2061 name = parse_name(name_node)
2062 if name is invalid:
2063 return None
2064 if default_node and default_node is not _empty:
2065 try:
2066 default_node = RewriteSymbolics().visit(default_node)
2067 o = ast.literal_eval(default_node)
2068 except ValueError:
2069 o = invalid
2070 if o is invalid:
2071 return None
2072 default = o if o is not invalid else default
2073 parameters.append(Parameter(name, kind, default=default, annotation=empty))
2074
2075 # non-keyword-only parameters
2076 args = reversed(f.args.args)
2077 defaults = reversed(f.args.defaults)
2078 iter = itertools.zip_longest(args, defaults, fillvalue=None)
Larry Hastings2623c8c2014-02-08 22:15:29 -08002079 if last_positional_only is not None:
2080 kind = Parameter.POSITIONAL_ONLY
2081 else:
2082 kind = Parameter.POSITIONAL_OR_KEYWORD
2083 for i, (name, default) in enumerate(reversed(list(iter))):
Yury Selivanov7d2bfed2014-02-03 02:46:07 -05002084 p(name, default)
Larry Hastings2623c8c2014-02-08 22:15:29 -08002085 if i == last_positional_only:
2086 kind = Parameter.POSITIONAL_OR_KEYWORD
Yury Selivanov7d2bfed2014-02-03 02:46:07 -05002087
2088 # *args
2089 if f.args.vararg:
2090 kind = Parameter.VAR_POSITIONAL
2091 p(f.args.vararg, empty)
2092
2093 # keyword-only arguments
2094 kind = Parameter.KEYWORD_ONLY
2095 for name, default in zip(f.args.kwonlyargs, f.args.kw_defaults):
2096 p(name, default)
2097
2098 # **kwargs
2099 if f.args.kwarg:
2100 kind = Parameter.VAR_KEYWORD
2101 p(f.args.kwarg, empty)
2102
Larry Hastings2623c8c2014-02-08 22:15:29 -08002103 if self_parameter is not None:
Yury Selivanov8c185ee2014-02-21 01:32:42 -05002104 # Possibly strip the bound argument:
2105 # - We *always* strip first bound argument if
2106 # it is a module.
2107 # - We don't strip first bound argument if
2108 # skip_bound_arg is False.
Yury Selivanov7d2bfed2014-02-03 02:46:07 -05002109 assert parameters
Yury Selivanov8c185ee2014-02-21 01:32:42 -05002110 _self = getattr(obj, '__self__', None)
2111 self_isbound = _self is not None
2112 self_ismodule = ismodule(_self)
2113 if self_isbound and (self_ismodule or skip_bound_arg):
Yury Selivanov7d2bfed2014-02-03 02:46:07 -05002114 parameters.pop(0)
2115 else:
2116 # for builtins, self parameter is always positional-only!
2117 p = parameters[0].replace(kind=Parameter.POSITIONAL_ONLY)
2118 parameters[0] = p
2119
2120 return cls(parameters, return_annotation=cls.empty)
2121
2122
Yury Selivanov57d240e2014-02-19 16:27:23 -05002123def _signature_from_builtin(cls, func, skip_bound_arg=True):
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002124 """Private helper function to get signature for
2125 builtin callables.
2126 """
2127
Yury Selivanov57d240e2014-02-19 16:27:23 -05002128 if not _signature_is_builtin(func):
2129 raise TypeError("{!r} is not a Python builtin "
2130 "function".format(func))
2131
2132 s = getattr(func, "__text_signature__", None)
2133 if not s:
2134 raise ValueError("no signature found for builtin {!r}".format(func))
2135
2136 return _signature_fromstr(cls, func, s, skip_bound_arg)
2137
2138
Serhiy Storchakad53cf992019-05-06 22:40:27 +03002139def _signature_from_function(cls, func, skip_bound_arg=True):
Yury Selivanovcf45f022015-05-20 14:38:50 -04002140 """Private helper: constructs Signature for the given python function."""
2141
2142 is_duck_function = False
2143 if not isfunction(func):
2144 if _signature_is_functionlike(func):
2145 is_duck_function = True
2146 else:
2147 # If it's not a pure Python function, and not a duck type
2148 # of pure function:
2149 raise TypeError('{!r} is not a Python function'.format(func))
2150
Serhiy Storchakad53cf992019-05-06 22:40:27 +03002151 s = getattr(func, "__text_signature__", None)
2152 if s:
2153 return _signature_fromstr(cls, func, s, skip_bound_arg)
2154
Yury Selivanovcf45f022015-05-20 14:38:50 -04002155 Parameter = cls._parameter_cls
2156
2157 # Parameter information.
2158 func_code = func.__code__
2159 pos_count = func_code.co_argcount
2160 arg_names = func_code.co_varnames
Pablo Galindo8c77b8c2019-04-29 13:36:57 +01002161 posonly_count = func_code.co_posonlyargcount
Pablo Galindocd74e662019-06-01 18:08:04 +01002162 positional = arg_names[:pos_count]
Yury Selivanovcf45f022015-05-20 14:38:50 -04002163 keyword_only_count = func_code.co_kwonlyargcount
Pablo Galindocd74e662019-06-01 18:08:04 +01002164 keyword_only = arg_names[pos_count:pos_count + keyword_only_count]
Yury Selivanovcf45f022015-05-20 14:38:50 -04002165 annotations = func.__annotations__
2166 defaults = func.__defaults__
2167 kwdefaults = func.__kwdefaults__
2168
2169 if defaults:
2170 pos_default_count = len(defaults)
2171 else:
2172 pos_default_count = 0
2173
2174 parameters = []
2175
Pablo Galindocd74e662019-06-01 18:08:04 +01002176 non_default_count = pos_count - pos_default_count
Pablo Galindo8c77b8c2019-04-29 13:36:57 +01002177 posonly_left = posonly_count
2178
Yury Selivanovcf45f022015-05-20 14:38:50 -04002179 # Non-keyword-only parameters w/o defaults.
Pablo Galindocd74e662019-06-01 18:08:04 +01002180 for name in positional[:non_default_count]:
Pablo Galindo8c77b8c2019-04-29 13:36:57 +01002181 kind = _POSITIONAL_ONLY if posonly_left else _POSITIONAL_OR_KEYWORD
Yury Selivanovcf45f022015-05-20 14:38:50 -04002182 annotation = annotations.get(name, _empty)
2183 parameters.append(Parameter(name, annotation=annotation,
Pablo Galindo8c77b8c2019-04-29 13:36:57 +01002184 kind=kind))
2185 if posonly_left:
2186 posonly_left -= 1
Yury Selivanovcf45f022015-05-20 14:38:50 -04002187
2188 # ... w/ defaults.
Pablo Galindocd74e662019-06-01 18:08:04 +01002189 for offset, name in enumerate(positional[non_default_count:]):
Pablo Galindo8c77b8c2019-04-29 13:36:57 +01002190 kind = _POSITIONAL_ONLY if posonly_left else _POSITIONAL_OR_KEYWORD
Yury Selivanovcf45f022015-05-20 14:38:50 -04002191 annotation = annotations.get(name, _empty)
2192 parameters.append(Parameter(name, annotation=annotation,
Pablo Galindo8c77b8c2019-04-29 13:36:57 +01002193 kind=kind,
Yury Selivanovcf45f022015-05-20 14:38:50 -04002194 default=defaults[offset]))
Pablo Galindo8c77b8c2019-04-29 13:36:57 +01002195 if posonly_left:
2196 posonly_left -= 1
Yury Selivanovcf45f022015-05-20 14:38:50 -04002197
2198 # *args
2199 if func_code.co_flags & CO_VARARGS:
Pablo Galindocd74e662019-06-01 18:08:04 +01002200 name = arg_names[pos_count + keyword_only_count]
Yury Selivanovcf45f022015-05-20 14:38:50 -04002201 annotation = annotations.get(name, _empty)
2202 parameters.append(Parameter(name, annotation=annotation,
2203 kind=_VAR_POSITIONAL))
2204
2205 # Keyword-only parameters.
2206 for name in keyword_only:
2207 default = _empty
2208 if kwdefaults is not None:
2209 default = kwdefaults.get(name, _empty)
2210
2211 annotation = annotations.get(name, _empty)
2212 parameters.append(Parameter(name, annotation=annotation,
2213 kind=_KEYWORD_ONLY,
2214 default=default))
2215 # **kwargs
2216 if func_code.co_flags & CO_VARKEYWORDS:
Pablo Galindocd74e662019-06-01 18:08:04 +01002217 index = pos_count + keyword_only_count
Yury Selivanovcf45f022015-05-20 14:38:50 -04002218 if func_code.co_flags & CO_VARARGS:
2219 index += 1
2220
2221 name = arg_names[index]
2222 annotation = annotations.get(name, _empty)
2223 parameters.append(Parameter(name, annotation=annotation,
2224 kind=_VAR_KEYWORD))
2225
2226 # Is 'func' is a pure Python function - don't validate the
2227 # parameters list (for correct order and defaults), it should be OK.
2228 return cls(parameters,
2229 return_annotation=annotations.get('return', _empty),
2230 __validate_parameters__=is_duck_function)
2231
2232
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002233def _signature_from_callable(obj, *,
2234 follow_wrapper_chains=True,
2235 skip_bound_arg=True,
2236 sigcls):
2237
2238 """Private helper function to get signature for arbitrary
2239 callable objects.
2240 """
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002241
2242 if not callable(obj):
2243 raise TypeError('{!r} is not a callable object'.format(obj))
2244
2245 if isinstance(obj, types.MethodType):
2246 # In this case we skip the first parameter of the underlying
2247 # function (usually `self` or `cls`).
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002248 sig = _signature_from_callable(
Yury Selivanovda396452014-03-27 12:09:24 -04002249 obj.__func__,
2250 follow_wrapper_chains=follow_wrapper_chains,
2251 skip_bound_arg=skip_bound_arg,
2252 sigcls=sigcls)
2253
Yury Selivanov57d240e2014-02-19 16:27:23 -05002254 if skip_bound_arg:
2255 return _signature_bound_method(sig)
2256 else:
2257 return sig
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002258
Nick Coghlane8c45d62013-07-28 20:00:01 +10002259 # Was this function wrapped by a decorator?
Yury Selivanov57d240e2014-02-19 16:27:23 -05002260 if follow_wrapper_chains:
2261 obj = unwrap(obj, stop=(lambda f: hasattr(f, "__signature__")))
Yury Selivanov46c759d2015-05-27 21:56:53 -04002262 if isinstance(obj, types.MethodType):
2263 # If the unwrapped object is a *method*, we might want to
2264 # skip its first parameter (self).
2265 # See test_signature_wrapped_bound_method for details.
Yury Selivanov507cd3c2015-05-27 21:59:03 -04002266 return _signature_from_callable(
Yury Selivanov46c759d2015-05-27 21:56:53 -04002267 obj,
2268 follow_wrapper_chains=follow_wrapper_chains,
Yury Selivanov507cd3c2015-05-27 21:59:03 -04002269 skip_bound_arg=skip_bound_arg,
2270 sigcls=sigcls)
Nick Coghlane8c45d62013-07-28 20:00:01 +10002271
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002272 try:
2273 sig = obj.__signature__
2274 except AttributeError:
2275 pass
2276 else:
2277 if sig is not None:
Yury Selivanov42407ab2014-06-23 10:23:50 -07002278 if not isinstance(sig, Signature):
2279 raise TypeError(
2280 'unexpected object {!r} in __signature__ '
2281 'attribute'.format(sig))
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002282 return sig
2283
Yury Selivanovda5fe4f2014-01-27 17:28:37 -05002284 try:
2285 partialmethod = obj._partialmethod
2286 except AttributeError:
2287 pass
2288 else:
Yury Selivanov0486f812014-01-29 12:18:59 -05002289 if isinstance(partialmethod, functools.partialmethod):
2290 # Unbound partialmethod (see functools.partialmethod)
2291 # This means, that we need to calculate the signature
2292 # as if it's a regular partial object, but taking into
2293 # account that the first positional argument
2294 # (usually `self`, or `cls`) will not be passed
2295 # automatically (as for boundmethods)
Yury Selivanovda5fe4f2014-01-27 17:28:37 -05002296
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002297 wrapped_sig = _signature_from_callable(
Yury Selivanovda396452014-03-27 12:09:24 -04002298 partialmethod.func,
2299 follow_wrapper_chains=follow_wrapper_chains,
2300 skip_bound_arg=skip_bound_arg,
2301 sigcls=sigcls)
2302
Yury Selivanov0486f812014-01-29 12:18:59 -05002303 sig = _signature_get_partial(wrapped_sig, partialmethod, (None,))
Yury Selivanov0486f812014-01-29 12:18:59 -05002304 first_wrapped_param = tuple(wrapped_sig.parameters.values())[0]
Dong-hee Na378d7062017-05-18 04:00:51 +09002305 if first_wrapped_param.kind is Parameter.VAR_POSITIONAL:
2306 # First argument of the wrapped callable is `*args`, as in
2307 # `partialmethod(lambda *args)`.
2308 return sig
2309 else:
2310 sig_params = tuple(sig.parameters.values())
Yury Selivanov8a387212018-03-06 12:59:45 -05002311 assert (not sig_params or
2312 first_wrapped_param is not sig_params[0])
Dong-hee Na378d7062017-05-18 04:00:51 +09002313 new_params = (first_wrapped_param,) + sig_params
2314 return sig.replace(parameters=new_params)
Yury Selivanovda5fe4f2014-01-27 17:28:37 -05002315
Yury Selivanov63da7c72014-01-31 14:48:37 -05002316 if isfunction(obj) or _signature_is_functionlike(obj):
2317 # If it's a pure Python function, or an object that is duck type
2318 # of a Python function (Cython functions, for instance), then:
Serhiy Storchakad53cf992019-05-06 22:40:27 +03002319 return _signature_from_function(sigcls, obj,
2320 skip_bound_arg=skip_bound_arg)
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002321
Yury Selivanova773de02014-02-21 18:30:53 -05002322 if _signature_is_builtin(obj):
Yury Selivanovda396452014-03-27 12:09:24 -04002323 return _signature_from_builtin(sigcls, obj,
Yury Selivanova773de02014-02-21 18:30:53 -05002324 skip_bound_arg=skip_bound_arg)
2325
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002326 if isinstance(obj, functools.partial):
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002327 wrapped_sig = _signature_from_callable(
Yury Selivanovda396452014-03-27 12:09:24 -04002328 obj.func,
2329 follow_wrapper_chains=follow_wrapper_chains,
2330 skip_bound_arg=skip_bound_arg,
2331 sigcls=sigcls)
Yury Selivanov62560fb2014-01-28 12:26:24 -05002332 return _signature_get_partial(wrapped_sig, obj)
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002333
2334 sig = None
2335 if isinstance(obj, type):
2336 # obj is a class or a metaclass
2337
2338 # First, let's see if it has an overloaded __call__ defined
2339 # in its metaclass
Yury Selivanov421f0c72014-01-29 12:05:40 -05002340 call = _signature_get_user_defined_method(type(obj), '__call__')
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002341 if call is not None:
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002342 sig = _signature_from_callable(
Yury Selivanovda396452014-03-27 12:09:24 -04002343 call,
2344 follow_wrapper_chains=follow_wrapper_chains,
2345 skip_bound_arg=skip_bound_arg,
2346 sigcls=sigcls)
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002347 else:
2348 # Now we check if the 'obj' class has a '__new__' method
Yury Selivanov421f0c72014-01-29 12:05:40 -05002349 new = _signature_get_user_defined_method(obj, '__new__')
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002350 if new is not None:
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002351 sig = _signature_from_callable(
Yury Selivanovda396452014-03-27 12:09:24 -04002352 new,
2353 follow_wrapper_chains=follow_wrapper_chains,
2354 skip_bound_arg=skip_bound_arg,
2355 sigcls=sigcls)
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002356 else:
2357 # Finally, we should have at least __init__ implemented
Yury Selivanov421f0c72014-01-29 12:05:40 -05002358 init = _signature_get_user_defined_method(obj, '__init__')
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002359 if init is not None:
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002360 sig = _signature_from_callable(
Yury Selivanovda396452014-03-27 12:09:24 -04002361 init,
2362 follow_wrapper_chains=follow_wrapper_chains,
2363 skip_bound_arg=skip_bound_arg,
2364 sigcls=sigcls)
Yury Selivanove7dcc5e2014-01-27 19:29:45 -05002365
2366 if sig is None:
Yury Selivanov7d2bfed2014-02-03 02:46:07 -05002367 # At this point we know, that `obj` is a class, with no user-
2368 # defined '__init__', '__new__', or class-level '__call__'
2369
Larry Hastings2623c8c2014-02-08 22:15:29 -08002370 for base in obj.__mro__[:-1]:
Yury Selivanov7d2bfed2014-02-03 02:46:07 -05002371 # Since '__text_signature__' is implemented as a
2372 # descriptor that extracts text signature from the
2373 # class docstring, if 'obj' is derived from a builtin
2374 # class, its own '__text_signature__' may be 'None'.
Larry Hastings2623c8c2014-02-08 22:15:29 -08002375 # Therefore, we go through the MRO (except the last
2376 # class in there, which is 'object') to find the first
Yury Selivanov7d2bfed2014-02-03 02:46:07 -05002377 # class with non-empty text signature.
2378 try:
2379 text_sig = base.__text_signature__
2380 except AttributeError:
2381 pass
2382 else:
2383 if text_sig:
2384 # If 'obj' class has a __text_signature__ attribute:
2385 # return a signature based on it
Yury Selivanovda396452014-03-27 12:09:24 -04002386 return _signature_fromstr(sigcls, obj, text_sig)
Yury Selivanov7d2bfed2014-02-03 02:46:07 -05002387
2388 # No '__text_signature__' was found for the 'obj' class.
2389 # Last option is to check if its '__init__' is
2390 # object.__init__ or type.__init__.
Larry Hastings2623c8c2014-02-08 22:15:29 -08002391 if type not in obj.__mro__:
Yury Selivanove7dcc5e2014-01-27 19:29:45 -05002392 # We have a class (not metaclass), but no user-defined
2393 # __init__ or __new__ for it
Yury Selivanovbf304fc2015-05-30 17:08:36 -04002394 if (obj.__init__ is object.__init__ and
2395 obj.__new__ is object.__new__):
Yury Selivanov7d2bfed2014-02-03 02:46:07 -05002396 # Return a signature of 'object' builtin.
Gregory P. Smith5b9ff7a2019-09-13 17:13:51 +01002397 return sigcls.from_callable(object)
Yury Selivanovbf304fc2015-05-30 17:08:36 -04002398 else:
2399 raise ValueError(
2400 'no signature found for builtin type {!r}'.format(obj))
Yury Selivanove7dcc5e2014-01-27 19:29:45 -05002401
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002402 elif not isinstance(obj, _NonUserDefinedCallables):
2403 # An object with __call__
2404 # We also check that the 'obj' is not an instance of
2405 # _WrapperDescriptor or _MethodWrapper to avoid
2406 # infinite recursion (and even potential segfault)
Yury Selivanov421f0c72014-01-29 12:05:40 -05002407 call = _signature_get_user_defined_method(type(obj), '__call__')
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002408 if call is not None:
Larry Hastings2623c8c2014-02-08 22:15:29 -08002409 try:
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002410 sig = _signature_from_callable(
Yury Selivanovda396452014-03-27 12:09:24 -04002411 call,
2412 follow_wrapper_chains=follow_wrapper_chains,
2413 skip_bound_arg=skip_bound_arg,
2414 sigcls=sigcls)
Larry Hastings2623c8c2014-02-08 22:15:29 -08002415 except ValueError as ex:
2416 msg = 'no signature found for {!r}'.format(obj)
2417 raise ValueError(msg) from ex
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002418
2419 if sig is not None:
2420 # For classes and objects we skip the first parameter of their
2421 # __call__, __new__, or __init__ methods
Yury Selivanov57d240e2014-02-19 16:27:23 -05002422 if skip_bound_arg:
2423 return _signature_bound_method(sig)
2424 else:
2425 return sig
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002426
2427 if isinstance(obj, types.BuiltinFunctionType):
2428 # Raise a nicer error message for builtins
2429 msg = 'no signature found for builtin function {!r}'.format(obj)
2430 raise ValueError(msg)
2431
2432 raise ValueError('callable {!r} is not supported by signature'.format(obj))
2433
2434
2435class _void:
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002436 """A private marker - used in Parameter & Signature."""
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002437
2438
2439class _empty:
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002440 """Marker object for Signature.empty and Parameter.empty."""
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002441
2442
Yury Selivanov21e83a52014-03-27 11:23:13 -04002443class _ParameterKind(enum.IntEnum):
2444 POSITIONAL_ONLY = 0
2445 POSITIONAL_OR_KEYWORD = 1
2446 VAR_POSITIONAL = 2
2447 KEYWORD_ONLY = 3
2448 VAR_KEYWORD = 4
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002449
2450 def __str__(self):
Yury Selivanov21e83a52014-03-27 11:23:13 -04002451 return self._name_
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002452
Dong-hee Na4aa30062018-06-08 12:46:31 +09002453 @property
2454 def description(self):
2455 return _PARAM_NAME_MAPPING[self]
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002456
Yury Selivanov21e83a52014-03-27 11:23:13 -04002457_POSITIONAL_ONLY = _ParameterKind.POSITIONAL_ONLY
2458_POSITIONAL_OR_KEYWORD = _ParameterKind.POSITIONAL_OR_KEYWORD
2459_VAR_POSITIONAL = _ParameterKind.VAR_POSITIONAL
2460_KEYWORD_ONLY = _ParameterKind.KEYWORD_ONLY
2461_VAR_KEYWORD = _ParameterKind.VAR_KEYWORD
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002462
Dong-hee Naa9cab432018-05-30 00:04:08 +09002463_PARAM_NAME_MAPPING = {
2464 _POSITIONAL_ONLY: 'positional-only',
2465 _POSITIONAL_OR_KEYWORD: 'positional or keyword',
2466 _VAR_POSITIONAL: 'variadic positional',
2467 _KEYWORD_ONLY: 'keyword-only',
2468 _VAR_KEYWORD: 'variadic keyword'
2469}
2470
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002471
2472class Parameter:
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002473 """Represents a parameter in a function signature.
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002474
2475 Has the following public attributes:
2476
2477 * name : str
2478 The name of the parameter as a string.
2479 * default : object
2480 The default value for the parameter if specified. If the
Yury Selivanov8757ead2014-01-28 16:39:25 -05002481 parameter has no default value, this attribute is set to
2482 `Parameter.empty`.
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002483 * annotation
2484 The annotation for the parameter if specified. If the
Yury Selivanov8757ead2014-01-28 16:39:25 -05002485 parameter has no annotation, this attribute is set to
2486 `Parameter.empty`.
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002487 * kind : str
2488 Describes how argument values are bound to the parameter.
2489 Possible values: `Parameter.POSITIONAL_ONLY`,
2490 `Parameter.POSITIONAL_OR_KEYWORD`, `Parameter.VAR_POSITIONAL`,
2491 `Parameter.KEYWORD_ONLY`, `Parameter.VAR_KEYWORD`.
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002492 """
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002493
Yury Selivanov3f73ca22014-04-08 11:30:45 -04002494 __slots__ = ('_name', '_kind', '_default', '_annotation')
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002495
2496 POSITIONAL_ONLY = _POSITIONAL_ONLY
2497 POSITIONAL_OR_KEYWORD = _POSITIONAL_OR_KEYWORD
2498 VAR_POSITIONAL = _VAR_POSITIONAL
2499 KEYWORD_ONLY = _KEYWORD_ONLY
2500 VAR_KEYWORD = _VAR_KEYWORD
2501
2502 empty = _empty
2503
Yury Selivanov3f73ca22014-04-08 11:30:45 -04002504 def __init__(self, name, kind, *, default=_empty, annotation=_empty):
Dong-hee Naa9cab432018-05-30 00:04:08 +09002505 try:
2506 self._kind = _ParameterKind(kind)
2507 except ValueError:
2508 raise ValueError(f'value {kind!r} is not a valid Parameter.kind')
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002509 if default is not _empty:
Dong-hee Naa9cab432018-05-30 00:04:08 +09002510 if self._kind in (_VAR_POSITIONAL, _VAR_KEYWORD):
2511 msg = '{} parameters cannot have default values'
Dong-hee Na4aa30062018-06-08 12:46:31 +09002512 msg = msg.format(self._kind.description)
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002513 raise ValueError(msg)
2514 self._default = default
2515 self._annotation = annotation
2516
Yury Selivanov2393dca2014-01-27 15:07:58 -05002517 if name is _empty:
2518 raise ValueError('name is a required attribute for Parameter')
2519
2520 if not isinstance(name, str):
Dong-hee Naa9cab432018-05-30 00:04:08 +09002521 msg = 'name must be a str, not a {}'.format(type(name).__name__)
2522 raise TypeError(msg)
Yury Selivanov2393dca2014-01-27 15:07:58 -05002523
Nick Coghlanb4b966e2016-06-04 14:40:03 -07002524 if name[0] == '.' and name[1:].isdigit():
2525 # These are implicit arguments generated by comprehensions. In
2526 # order to provide a friendlier interface to users, we recast
2527 # their name as "implicitN" and treat them as positional-only.
2528 # See issue 19611.
Dong-hee Naa9cab432018-05-30 00:04:08 +09002529 if self._kind != _POSITIONAL_OR_KEYWORD:
2530 msg = (
2531 'implicit arguments must be passed as '
2532 'positional or keyword arguments, not {}'
Nick Coghlanb4b966e2016-06-04 14:40:03 -07002533 )
Dong-hee Na4aa30062018-06-08 12:46:31 +09002534 msg = msg.format(self._kind.description)
Dong-hee Naa9cab432018-05-30 00:04:08 +09002535 raise ValueError(msg)
Nick Coghlanb4b966e2016-06-04 14:40:03 -07002536 self._kind = _POSITIONAL_ONLY
2537 name = 'implicit{}'.format(name[1:])
2538
Yury Selivanov2393dca2014-01-27 15:07:58 -05002539 if not name.isidentifier():
2540 raise ValueError('{!r} is not a valid parameter name'.format(name))
2541
2542 self._name = name
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002543
Yury Selivanova5d63dd2014-03-27 11:31:43 -04002544 def __reduce__(self):
2545 return (type(self),
2546 (self._name, self._kind),
Yury Selivanov3f73ca22014-04-08 11:30:45 -04002547 {'_default': self._default,
Yury Selivanova5d63dd2014-03-27 11:31:43 -04002548 '_annotation': self._annotation})
2549
2550 def __setstate__(self, state):
Yury Selivanova5d63dd2014-03-27 11:31:43 -04002551 self._default = state['_default']
2552 self._annotation = state['_annotation']
2553
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002554 @property
2555 def name(self):
2556 return self._name
2557
2558 @property
2559 def default(self):
2560 return self._default
2561
2562 @property
2563 def annotation(self):
2564 return self._annotation
2565
2566 @property
2567 def kind(self):
2568 return self._kind
2569
Yury Selivanov3f73ca22014-04-08 11:30:45 -04002570 def replace(self, *, name=_void, kind=_void,
2571 annotation=_void, default=_void):
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002572 """Creates a customized copy of the Parameter."""
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002573
2574 if name is _void:
2575 name = self._name
2576
2577 if kind is _void:
2578 kind = self._kind
2579
2580 if annotation is _void:
2581 annotation = self._annotation
2582
2583 if default is _void:
2584 default = self._default
2585
Yury Selivanov3f73ca22014-04-08 11:30:45 -04002586 return type(self)(name, kind, default=default, annotation=annotation)
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002587
2588 def __str__(self):
2589 kind = self.kind
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002590 formatted = self._name
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002591
2592 # Add annotation and default value
2593 if self._annotation is not _empty:
Dong-hee Na762b9572017-11-16 03:30:59 +09002594 formatted = '{}: {}'.format(formatted,
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002595 formatannotation(self._annotation))
2596
2597 if self._default is not _empty:
Dong-hee Na762b9572017-11-16 03:30:59 +09002598 if self._annotation is not _empty:
2599 formatted = '{} = {}'.format(formatted, repr(self._default))
2600 else:
2601 formatted = '{}={}'.format(formatted, repr(self._default))
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002602
2603 if kind == _VAR_POSITIONAL:
2604 formatted = '*' + formatted
2605 elif kind == _VAR_KEYWORD:
2606 formatted = '**' + formatted
2607
2608 return formatted
2609
2610 def __repr__(self):
Yury Selivanovf229bc52015-05-15 12:53:56 -04002611 return '<{} "{}">'.format(self.__class__.__name__, self)
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002612
Yury Selivanov67ae50e2014-04-08 11:46:50 -04002613 def __hash__(self):
Yury Selivanov08d4a4f2014-09-12 15:48:02 -04002614 return hash((self.name, self.kind, self.annotation, self.default))
Yury Selivanov67ae50e2014-04-08 11:46:50 -04002615
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002616 def __eq__(self, other):
Serhiy Storchaka2489bd52015-07-18 23:20:50 +03002617 if self is other:
2618 return True
Serhiy Storchaka3018cc42015-07-18 23:19:05 +03002619 if not isinstance(other, Parameter):
2620 return NotImplemented
2621 return (self._name == other._name and
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002622 self._kind == other._kind and
2623 self._default == other._default and
2624 self._annotation == other._annotation)
2625
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002626
2627class BoundArguments:
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002628 """Result of `Signature.bind` call. Holds the mapping of arguments
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002629 to the function's parameters.
2630
2631 Has the following public attributes:
2632
Rémi Lapeyre2cca8ef2020-01-28 13:47:03 +01002633 * arguments : dict
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002634 An ordered mutable mapping of parameters' names to arguments' values.
2635 Does not contain arguments' default values.
2636 * signature : Signature
2637 The Signature object that created this instance.
2638 * args : tuple
2639 Tuple of positional arguments values.
2640 * kwargs : dict
2641 Dict of keyword arguments values.
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002642 """
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002643
Yury Selivanov6abe0322015-05-13 17:18:41 -04002644 __slots__ = ('arguments', '_signature', '__weakref__')
2645
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002646 def __init__(self, signature, arguments):
2647 self.arguments = arguments
2648 self._signature = signature
2649
2650 @property
2651 def signature(self):
2652 return self._signature
2653
2654 @property
2655 def args(self):
2656 args = []
2657 for param_name, param in self._signature.parameters.items():
Yury Selivanov3f73ca22014-04-08 11:30:45 -04002658 if param.kind in (_VAR_KEYWORD, _KEYWORD_ONLY):
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002659 break
2660
2661 try:
2662 arg = self.arguments[param_name]
2663 except KeyError:
2664 # We're done here. Other arguments
2665 # will be mapped in 'BoundArguments.kwargs'
2666 break
2667 else:
2668 if param.kind == _VAR_POSITIONAL:
2669 # *args
2670 args.extend(arg)
2671 else:
2672 # plain argument
2673 args.append(arg)
2674
2675 return tuple(args)
2676
2677 @property
2678 def kwargs(self):
2679 kwargs = {}
2680 kwargs_started = False
2681 for param_name, param in self._signature.parameters.items():
2682 if not kwargs_started:
Yury Selivanov3f73ca22014-04-08 11:30:45 -04002683 if param.kind in (_VAR_KEYWORD, _KEYWORD_ONLY):
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002684 kwargs_started = True
2685 else:
2686 if param_name not in self.arguments:
2687 kwargs_started = True
2688 continue
2689
2690 if not kwargs_started:
2691 continue
2692
2693 try:
2694 arg = self.arguments[param_name]
2695 except KeyError:
2696 pass
2697 else:
2698 if param.kind == _VAR_KEYWORD:
2699 # **kwargs
2700 kwargs.update(arg)
2701 else:
2702 # plain keyword argument
2703 kwargs[param_name] = arg
2704
2705 return kwargs
2706
Yury Selivanovb907a512015-05-16 13:45:09 -04002707 def apply_defaults(self):
2708 """Set default values for missing arguments.
2709
2710 For variable-positional arguments (*args) the default is an
2711 empty tuple.
2712
2713 For variable-keyword arguments (**kwargs) the default is an
2714 empty dict.
2715 """
2716 arguments = self.arguments
Yury Selivanovb907a512015-05-16 13:45:09 -04002717 new_arguments = []
2718 for name, param in self._signature.parameters.items():
2719 try:
2720 new_arguments.append((name, arguments[name]))
2721 except KeyError:
2722 if param.default is not _empty:
2723 val = param.default
2724 elif param.kind is _VAR_POSITIONAL:
2725 val = ()
2726 elif param.kind is _VAR_KEYWORD:
2727 val = {}
2728 else:
2729 # This BoundArguments was likely produced by
2730 # Signature.bind_partial().
2731 continue
2732 new_arguments.append((name, val))
Rémi Lapeyre2cca8ef2020-01-28 13:47:03 +01002733 self.arguments = dict(new_arguments)
Yury Selivanovb907a512015-05-16 13:45:09 -04002734
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002735 def __eq__(self, other):
Serhiy Storchaka2489bd52015-07-18 23:20:50 +03002736 if self is other:
2737 return True
Serhiy Storchaka3018cc42015-07-18 23:19:05 +03002738 if not isinstance(other, BoundArguments):
2739 return NotImplemented
2740 return (self.signature == other.signature and
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002741 self.arguments == other.arguments)
2742
Yury Selivanov6abe0322015-05-13 17:18:41 -04002743 def __setstate__(self, state):
2744 self._signature = state['_signature']
2745 self.arguments = state['arguments']
2746
2747 def __getstate__(self):
2748 return {'_signature': self._signature, 'arguments': self.arguments}
2749
Yury Selivanov3f6538f2015-05-14 18:47:17 -04002750 def __repr__(self):
2751 args = []
2752 for arg, value in self.arguments.items():
2753 args.append('{}={!r}'.format(arg, value))
Yury Selivanovf229bc52015-05-15 12:53:56 -04002754 return '<{} ({})>'.format(self.__class__.__name__, ', '.join(args))
Yury Selivanov3f6538f2015-05-14 18:47:17 -04002755
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002756
2757class Signature:
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002758 """A Signature object represents the overall signature of a function.
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002759 It stores a Parameter object for each parameter accepted by the
2760 function, as well as information specific to the function itself.
2761
2762 A Signature object has the following public attributes and methods:
2763
Jens Reidel611836a2020-03-18 03:22:46 +01002764 * parameters : OrderedDict
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002765 An ordered mapping of parameters' names to the corresponding
2766 Parameter objects (keyword-only arguments are in the same order
2767 as listed in `code.co_varnames`).
2768 * return_annotation : object
2769 The annotation for the return type of the function if specified.
2770 If the function has no annotation for its return type, this
Yury Selivanov8757ead2014-01-28 16:39:25 -05002771 attribute is set to `Signature.empty`.
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002772 * bind(*args, **kwargs) -> BoundArguments
2773 Creates a mapping from positional and keyword arguments to
2774 parameters.
2775 * bind_partial(*args, **kwargs) -> BoundArguments
2776 Creates a partial mapping from positional and keyword arguments
2777 to parameters (simulating 'functools.partial' behavior.)
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002778 """
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002779
2780 __slots__ = ('_return_annotation', '_parameters')
2781
2782 _parameter_cls = Parameter
2783 _bound_arguments_cls = BoundArguments
2784
2785 empty = _empty
2786
2787 def __init__(self, parameters=None, *, return_annotation=_empty,
2788 __validate_parameters__=True):
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002789 """Constructs Signature from the given list of Parameter
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002790 objects and 'return_annotation'. All arguments are optional.
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002791 """
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002792
2793 if parameters is None:
Jens Reidel611836a2020-03-18 03:22:46 +01002794 params = OrderedDict()
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002795 else:
2796 if __validate_parameters__:
Jens Reidel611836a2020-03-18 03:22:46 +01002797 params = OrderedDict()
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002798 top_kind = _POSITIONAL_ONLY
Yury Selivanov07a9e452014-01-29 10:58:16 -05002799 kind_defaults = False
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002800
Rémi Lapeyre2cca8ef2020-01-28 13:47:03 +01002801 for param in parameters:
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002802 kind = param.kind
Yury Selivanov2393dca2014-01-27 15:07:58 -05002803 name = param.name
2804
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002805 if kind < top_kind:
Dong-hee Naa9cab432018-05-30 00:04:08 +09002806 msg = (
2807 'wrong parameter order: {} parameter before {} '
2808 'parameter'
2809 )
Dong-hee Na4aa30062018-06-08 12:46:31 +09002810 msg = msg.format(top_kind.description,
2811 kind.description)
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002812 raise ValueError(msg)
Yury Selivanov07a9e452014-01-29 10:58:16 -05002813 elif kind > top_kind:
2814 kind_defaults = False
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002815 top_kind = kind
2816
Yury Selivanov3f73ca22014-04-08 11:30:45 -04002817 if kind in (_POSITIONAL_ONLY, _POSITIONAL_OR_KEYWORD):
Yury Selivanov07a9e452014-01-29 10:58:16 -05002818 if param.default is _empty:
2819 if kind_defaults:
2820 # No default for this parameter, but the
2821 # previous parameter of the same kind had
2822 # a default
2823 msg = 'non-default argument follows default ' \
2824 'argument'
2825 raise ValueError(msg)
2826 else:
2827 # There is a default for this parameter.
2828 kind_defaults = True
2829
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002830 if name in params:
2831 msg = 'duplicate parameter name: {!r}'.format(name)
2832 raise ValueError(msg)
Yury Selivanov2393dca2014-01-27 15:07:58 -05002833
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002834 params[name] = param
2835 else:
Jens Reidel611836a2020-03-18 03:22:46 +01002836 params = OrderedDict((param.name, param) for param in parameters)
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002837
2838 self._parameters = types.MappingProxyType(params)
2839 self._return_annotation = return_annotation
2840
2841 @classmethod
2842 def from_function(cls, func):
Matthias Bussonnierded87d82018-10-19 16:40:45 -07002843 """Constructs Signature for the given python function.
Yury Selivanov57c74fc2015-05-20 23:07:02 -04002844
Matthias Bussonnierded87d82018-10-19 16:40:45 -07002845 Deprecated since Python 3.5, use `Signature.from_callable()`.
2846 """
2847
2848 warnings.warn("inspect.Signature.from_function() is deprecated since "
2849 "Python 3.5, use Signature.from_callable()",
Berker Peksagb5601582015-05-21 23:40:54 +03002850 DeprecationWarning, stacklevel=2)
Yury Selivanovcf45f022015-05-20 14:38:50 -04002851 return _signature_from_function(cls, func)
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002852
Larry Hastings44e2eaa2013-11-23 15:37:55 -08002853 @classmethod
2854 def from_builtin(cls, func):
Matthias Bussonnierded87d82018-10-19 16:40:45 -07002855 """Constructs Signature for the given builtin function.
Yury Selivanov57c74fc2015-05-20 23:07:02 -04002856
Matthias Bussonnierded87d82018-10-19 16:40:45 -07002857 Deprecated since Python 3.5, use `Signature.from_callable()`.
2858 """
2859
2860 warnings.warn("inspect.Signature.from_builtin() is deprecated since "
2861 "Python 3.5, use Signature.from_callable()",
Berker Peksagb5601582015-05-21 23:40:54 +03002862 DeprecationWarning, stacklevel=2)
Yury Selivanov57d240e2014-02-19 16:27:23 -05002863 return _signature_from_builtin(cls, func)
Larry Hastings44e2eaa2013-11-23 15:37:55 -08002864
Yury Selivanovda396452014-03-27 12:09:24 -04002865 @classmethod
Yury Selivanovbcd4fc12015-05-20 14:30:08 -04002866 def from_callable(cls, obj, *, follow_wrapped=True):
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002867 """Constructs Signature for the given callable object."""
Yury Selivanovbcd4fc12015-05-20 14:30:08 -04002868 return _signature_from_callable(obj, sigcls=cls,
2869 follow_wrapper_chains=follow_wrapped)
Yury Selivanovda396452014-03-27 12:09:24 -04002870
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002871 @property
2872 def parameters(self):
2873 return self._parameters
2874
2875 @property
2876 def return_annotation(self):
2877 return self._return_annotation
2878
2879 def replace(self, *, parameters=_void, return_annotation=_void):
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002880 """Creates a customized copy of the Signature.
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002881 Pass 'parameters' and/or 'return_annotation' arguments
2882 to override them in the new copy.
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002883 """
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002884
2885 if parameters is _void:
2886 parameters = self.parameters.values()
2887
2888 if return_annotation is _void:
2889 return_annotation = self._return_annotation
2890
2891 return type(self)(parameters,
2892 return_annotation=return_annotation)
2893
Yury Selivanov08d4a4f2014-09-12 15:48:02 -04002894 def _hash_basis(self):
2895 params = tuple(param for param in self.parameters.values()
2896 if param.kind != _KEYWORD_ONLY)
2897
2898 kwo_params = {param.name: param for param in self.parameters.values()
2899 if param.kind == _KEYWORD_ONLY}
2900
2901 return params, kwo_params, self.return_annotation
2902
Yury Selivanov67ae50e2014-04-08 11:46:50 -04002903 def __hash__(self):
Yury Selivanov08d4a4f2014-09-12 15:48:02 -04002904 params, kwo_params, return_annotation = self._hash_basis()
2905 kwo_params = frozenset(kwo_params.values())
2906 return hash((params, kwo_params, return_annotation))
Yury Selivanov67ae50e2014-04-08 11:46:50 -04002907
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002908 def __eq__(self, other):
Serhiy Storchaka2489bd52015-07-18 23:20:50 +03002909 if self is other:
2910 return True
Serhiy Storchaka3018cc42015-07-18 23:19:05 +03002911 if not isinstance(other, Signature):
2912 return NotImplemented
Serhiy Storchaka2489bd52015-07-18 23:20:50 +03002913 return self._hash_basis() == other._hash_basis()
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002914
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002915 def _bind(self, args, kwargs, *, partial=False):
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002916 """Private method. Don't use directly."""
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002917
Rémi Lapeyre2cca8ef2020-01-28 13:47:03 +01002918 arguments = {}
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002919
2920 parameters = iter(self.parameters.values())
2921 parameters_ex = ()
2922 arg_vals = iter(args)
2923
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002924 while True:
2925 # Let's iterate through the positional arguments and corresponding
2926 # parameters
2927 try:
2928 arg_val = next(arg_vals)
2929 except StopIteration:
2930 # No more positional arguments
2931 try:
2932 param = next(parameters)
2933 except StopIteration:
2934 # No more parameters. That's it. Just need to check that
2935 # we have no `kwargs` after this while loop
2936 break
2937 else:
2938 if param.kind == _VAR_POSITIONAL:
2939 # That's OK, just empty *args. Let's start parsing
2940 # kwargs
2941 break
2942 elif param.name in kwargs:
2943 if param.kind == _POSITIONAL_ONLY:
2944 msg = '{arg!r} parameter is positional only, ' \
2945 'but was passed as a keyword'
2946 msg = msg.format(arg=param.name)
2947 raise TypeError(msg) from None
2948 parameters_ex = (param,)
2949 break
2950 elif (param.kind == _VAR_KEYWORD or
2951 param.default is not _empty):
2952 # That's fine too - we have a default value for this
2953 # parameter. So, lets start parsing `kwargs`, starting
2954 # with the current parameter
2955 parameters_ex = (param,)
2956 break
2957 else:
Yury Selivanov38b0d5a2014-01-28 17:27:39 -05002958 # No default, not VAR_KEYWORD, not VAR_POSITIONAL,
2959 # not in `kwargs`
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002960 if partial:
2961 parameters_ex = (param,)
2962 break
2963 else:
Yury Selivanov86872752015-05-19 00:27:49 -04002964 msg = 'missing a required argument: {arg!r}'
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002965 msg = msg.format(arg=param.name)
2966 raise TypeError(msg) from None
2967 else:
2968 # We have a positional argument to process
2969 try:
2970 param = next(parameters)
2971 except StopIteration:
2972 raise TypeError('too many positional arguments') from None
2973 else:
2974 if param.kind in (_VAR_KEYWORD, _KEYWORD_ONLY):
2975 # Looks like we have no parameter for this positional
2976 # argument
Yury Selivanov86872752015-05-19 00:27:49 -04002977 raise TypeError(
2978 'too many positional arguments') from None
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002979
2980 if param.kind == _VAR_POSITIONAL:
2981 # We have an '*args'-like argument, let's fill it with
2982 # all positional arguments we have left and move on to
2983 # the next phase
2984 values = [arg_val]
2985 values.extend(arg_vals)
2986 arguments[param.name] = tuple(values)
2987 break
2988
Pablo Galindof3ef06a2019-10-15 12:40:02 +01002989 if param.name in kwargs and param.kind != _POSITIONAL_ONLY:
Yury Selivanov86872752015-05-19 00:27:49 -04002990 raise TypeError(
2991 'multiple values for argument {arg!r}'.format(
2992 arg=param.name)) from None
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002993
2994 arguments[param.name] = arg_val
2995
2996 # Now, we iterate through the remaining parameters to process
2997 # keyword arguments
2998 kwargs_param = None
2999 for param in itertools.chain(parameters_ex, parameters):
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07003000 if param.kind == _VAR_KEYWORD:
3001 # Memorize that we have a '**kwargs'-like parameter
3002 kwargs_param = param
3003 continue
3004
Yury Selivanov38b0d5a2014-01-28 17:27:39 -05003005 if param.kind == _VAR_POSITIONAL:
3006 # Named arguments don't refer to '*args'-like parameters.
3007 # We only arrive here if the positional arguments ended
3008 # before reaching the last parameter before *args.
3009 continue
3010
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07003011 param_name = param.name
3012 try:
3013 arg_val = kwargs.pop(param_name)
3014 except KeyError:
3015 # We have no value for this parameter. It's fine though,
3016 # if it has a default value, or it is an '*args'-like
3017 # parameter, left alone by the processing of positional
3018 # arguments.
3019 if (not partial and param.kind != _VAR_POSITIONAL and
3020 param.default is _empty):
Yury Selivanov86872752015-05-19 00:27:49 -04003021 raise TypeError('missing a required argument: {arg!r}'. \
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07003022 format(arg=param_name)) from None
3023
3024 else:
Yury Selivanov9b9ac952014-01-28 20:54:28 -05003025 if param.kind == _POSITIONAL_ONLY:
3026 # This should never happen in case of a properly built
3027 # Signature object (but let's have this check here
3028 # to ensure correct behaviour just in case)
3029 raise TypeError('{arg!r} parameter is positional only, '
3030 'but was passed as a keyword'. \
3031 format(arg=param.name))
3032
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07003033 arguments[param_name] = arg_val
3034
3035 if kwargs:
3036 if kwargs_param is not None:
3037 # Process our '**kwargs'-like parameter
3038 arguments[kwargs_param.name] = kwargs
3039 else:
Yury Selivanov86872752015-05-19 00:27:49 -04003040 raise TypeError(
3041 'got an unexpected keyword argument {arg!r}'.format(
3042 arg=next(iter(kwargs))))
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07003043
3044 return self._bound_arguments_cls(self, arguments)
3045
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03003046 def bind(self, /, *args, **kwargs):
Yury Selivanov5a23bd02014-03-29 13:47:11 -04003047 """Get a BoundArguments object, that maps the passed `args`
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07003048 and `kwargs` to the function's signature. Raises `TypeError`
3049 if the passed arguments can not be bound.
Yury Selivanov5a23bd02014-03-29 13:47:11 -04003050 """
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03003051 return self._bind(args, kwargs)
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07003052
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03003053 def bind_partial(self, /, *args, **kwargs):
Yury Selivanov5a23bd02014-03-29 13:47:11 -04003054 """Get a BoundArguments object, that partially maps the
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07003055 passed `args` and `kwargs` to the function's signature.
3056 Raises `TypeError` if the passed arguments can not be bound.
Yury Selivanov5a23bd02014-03-29 13:47:11 -04003057 """
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03003058 return self._bind(args, kwargs, partial=True)
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07003059
Yury Selivanova5d63dd2014-03-27 11:31:43 -04003060 def __reduce__(self):
3061 return (type(self),
3062 (tuple(self._parameters.values()),),
3063 {'_return_annotation': self._return_annotation})
3064
3065 def __setstate__(self, state):
3066 self._return_annotation = state['_return_annotation']
3067
Yury Selivanov374375d2014-03-27 12:41:53 -04003068 def __repr__(self):
Yury Selivanovf229bc52015-05-15 12:53:56 -04003069 return '<{} {}>'.format(self.__class__.__name__, self)
Yury Selivanov374375d2014-03-27 12:41:53 -04003070
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07003071 def __str__(self):
3072 result = []
Yury Selivanov2393dca2014-01-27 15:07:58 -05003073 render_pos_only_separator = False
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07003074 render_kw_only_separator = True
Yury Selivanov2393dca2014-01-27 15:07:58 -05003075 for param in self.parameters.values():
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07003076 formatted = str(param)
3077
3078 kind = param.kind
Yury Selivanov2393dca2014-01-27 15:07:58 -05003079
3080 if kind == _POSITIONAL_ONLY:
3081 render_pos_only_separator = True
3082 elif render_pos_only_separator:
3083 # It's not a positional-only parameter, and the flag
3084 # is set to 'True' (there were pos-only params before.)
3085 result.append('/')
3086 render_pos_only_separator = False
3087
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07003088 if kind == _VAR_POSITIONAL:
3089 # OK, we have an '*args'-like parameter, so we won't need
3090 # a '*' to separate keyword-only arguments
3091 render_kw_only_separator = False
3092 elif kind == _KEYWORD_ONLY and render_kw_only_separator:
3093 # We have a keyword-only parameter to render and we haven't
3094 # rendered an '*args'-like parameter before, so add a '*'
3095 # separator to the parameters list ("foo(arg1, *, arg2)" case)
3096 result.append('*')
3097 # This condition should be only triggered once, so
3098 # reset the flag
3099 render_kw_only_separator = False
3100
3101 result.append(formatted)
3102
Yury Selivanov2393dca2014-01-27 15:07:58 -05003103 if render_pos_only_separator:
3104 # There were only positional-only parameters, hence the
3105 # flag was not reset to 'False'
3106 result.append('/')
3107
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07003108 rendered = '({})'.format(', '.join(result))
3109
3110 if self.return_annotation is not _empty:
3111 anno = formatannotation(self.return_annotation)
3112 rendered += ' -> {}'.format(anno)
3113
3114 return rendered
Nick Coghlanf94a16b2013-09-22 22:46:49 +10003115
Yury Selivanovda396452014-03-27 12:09:24 -04003116
Yury Selivanovbcd4fc12015-05-20 14:30:08 -04003117def signature(obj, *, follow_wrapped=True):
Yury Selivanov5a23bd02014-03-29 13:47:11 -04003118 """Get a signature object for the passed callable."""
Yury Selivanovbcd4fc12015-05-20 14:30:08 -04003119 return Signature.from_callable(obj, follow_wrapped=follow_wrapped)
Yury Selivanovda396452014-03-27 12:09:24 -04003120
3121
Nick Coghlanf94a16b2013-09-22 22:46:49 +10003122def _main():
3123 """ Logic for inspecting an object given at command line """
3124 import argparse
3125 import importlib
3126
3127 parser = argparse.ArgumentParser()
3128 parser.add_argument(
3129 'object',
3130 help="The object to be analysed. "
3131 "It supports the 'module:qualname' syntax")
3132 parser.add_argument(
3133 '-d', '--details', action='store_true',
3134 help='Display info about the module rather than its source code')
3135
3136 args = parser.parse_args()
3137
3138 target = args.object
3139 mod_name, has_attrs, attrs = target.partition(":")
3140 try:
3141 obj = module = importlib.import_module(mod_name)
3142 except Exception as exc:
3143 msg = "Failed to import {} ({}: {})".format(mod_name,
3144 type(exc).__name__,
3145 exc)
3146 print(msg, file=sys.stderr)
Alan Yeee3c59a72019-09-09 07:15:43 -07003147 sys.exit(2)
Nick Coghlanf94a16b2013-09-22 22:46:49 +10003148
3149 if has_attrs:
3150 parts = attrs.split(".")
3151 obj = module
3152 for part in parts:
3153 obj = getattr(obj, part)
3154
3155 if module.__name__ in sys.builtin_module_names:
3156 print("Can't get info for builtin modules.", file=sys.stderr)
Alan Yeee3c59a72019-09-09 07:15:43 -07003157 sys.exit(1)
Nick Coghlanf94a16b2013-09-22 22:46:49 +10003158
3159 if args.details:
3160 print('Target: {}'.format(target))
3161 print('Origin: {}'.format(getsourcefile(module)))
3162 print('Cached: {}'.format(module.__cached__))
3163 if obj is module:
3164 print('Loader: {}'.format(repr(module.__loader__)))
3165 if hasattr(module, '__path__'):
3166 print('Submodule search path: {}'.format(module.__path__))
3167 else:
3168 try:
3169 __, lineno = findsource(obj)
3170 except Exception:
3171 pass
3172 else:
3173 print('Line: {}'.format(lineno))
3174
3175 print('\n')
3176 else:
3177 print(getsource(obj))
3178
3179
3180if __name__ == "__main__":
3181 _main()