blob: a4f28f7557050312fef62d85774cd3c3b9304cba [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
Antoine Pitroua8723a02015-04-15 00:41:29 +020035import dis
Yury Selivanov75445082015-05-11 22:57:16 -040036import collections.abc
Yury Selivanov21e83a52014-03-27 11:23:13 -040037import enum
Brett Cannoncb66eb02012-05-11 12:58:42 -040038import importlib.machinery
39import itertools
Christian Heimes7131fd92008-02-19 14:21:46 +000040import linecache
Brett Cannoncb66eb02012-05-11 12:58:42 -040041import os
42import re
43import sys
44import tokenize
Larry Hastings2623c8c2014-02-08 22:15:29 -080045import token
Brett Cannoncb66eb02012-05-11 12:58:42 -040046import types
Brett Cannon2b88fcf2012-06-02 22:28:42 -040047import warnings
Larry Hastings7c7cbfc2012-06-22 15:19:35 -070048import functools
Nick Coghlan2f92e542012-06-23 19:39:55 +100049import builtins
Raymond Hettingera1a992c2005-03-11 06:46:45 +000050from operator import attrgetter
Larry Hastings7c7cbfc2012-06-22 15:19:35 -070051from collections import namedtuple, OrderedDict
Nick Coghlan09c81232010-08-17 10:18:16 +000052
53# Create constants for the compiler flags in Include/code.h
Antoine Pitroua8723a02015-04-15 00:41:29 +020054# We try to get them from dis to avoid duplication
55mod_dict = globals()
56for k, v in dis.COMPILER_FLAG_NAMES.items():
57 mod_dict["CO_" + v] = k
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +000058
Christian Heimesbe5b30b2008-03-03 19:18:51 +000059# See Include/object.h
60TPFLAGS_IS_ABSTRACT = 1 << 20
61
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +000062# ----------------------------------------------------------- type-checking
63def ismodule(object):
64 """Return true if the object is a module.
65
66 Module objects provide these attributes:
Barry Warsaw28a691b2010-04-17 00:19:56 +000067 __cached__ pathname to byte compiled file
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +000068 __doc__ documentation string
69 __file__ filename (missing for built-in modules)"""
Tim Peters28bc59f2001-09-16 08:40:16 +000070 return isinstance(object, types.ModuleType)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +000071
72def isclass(object):
73 """Return true if the object is a class.
74
75 Class objects provide these attributes:
76 __doc__ documentation string
77 __module__ name of module in which this class was defined"""
Benjamin Petersonc4656002009-01-17 22:41:18 +000078 return isinstance(object, type)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +000079
80def ismethod(object):
81 """Return true if the object is an instance method.
82
83 Instance method objects provide these attributes:
84 __doc__ documentation string
85 __name__ name with which this method was defined
Christian Heimesff737952007-11-27 10:40:20 +000086 __func__ function object containing implementation of method
87 __self__ instance to which this method is bound"""
Tim Peters28bc59f2001-09-16 08:40:16 +000088 return isinstance(object, types.MethodType)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +000089
Tim Peters536d2262001-09-20 05:13:38 +000090def ismethoddescriptor(object):
Tim Petersf1d90b92001-09-20 05:47:55 +000091 """Return true if the object is a method descriptor.
92
93 But not if ismethod() or isclass() or isfunction() are true.
Tim Peters536d2262001-09-20 05:13:38 +000094
95 This is new in Python 2.2, and, for example, is true of int.__add__.
96 An object passing this test has a __get__ attribute but not a __set__
97 attribute, but beyond that the set of attributes varies. __name__ is
98 usually sensible, and __doc__ often is.
99
Tim Petersf1d90b92001-09-20 05:47:55 +0000100 Methods implemented via descriptors that also pass one of the other
101 tests return false from the ismethoddescriptor() test, simply because
102 the other tests promise more -- you can, e.g., count on having the
Christian Heimesff737952007-11-27 10:40:20 +0000103 __func__ attribute (etc) when an object passes ismethod()."""
Antoine Pitrou86a8a9a2011-12-21 09:57:40 +0100104 if isclass(object) or ismethod(object) or isfunction(object):
105 # mutual exclusion
106 return False
107 tp = type(object)
108 return hasattr(tp, "__get__") and not hasattr(tp, "__set__")
Tim Peters536d2262001-09-20 05:13:38 +0000109
Martin v. Löwise59e2ba2003-05-03 09:09:02 +0000110def isdatadescriptor(object):
111 """Return true if the object is a data descriptor.
112
Aaron Hall, MBA4054b172018-05-20 19:46:42 -0400113 Data descriptors have a __set__ or a __delete__ attribute. Examples are
Martin v. Löwise59e2ba2003-05-03 09:09:02 +0000114 properties (defined in Python) and getsets and members (defined in C).
115 Typically, data descriptors will also have __name__ and __doc__ attributes
116 (properties, getsets, and members have both of these attributes), but this
117 is not guaranteed."""
Antoine Pitrou86a8a9a2011-12-21 09:57:40 +0100118 if isclass(object) or ismethod(object) or isfunction(object):
119 # mutual exclusion
120 return False
121 tp = type(object)
Aaron Hall, MBA4054b172018-05-20 19:46:42 -0400122 return hasattr(tp, "__set__") or hasattr(tp, "__delete__")
Martin v. Löwise59e2ba2003-05-03 09:09:02 +0000123
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000124if hasattr(types, 'MemberDescriptorType'):
125 # CPython and equivalent
126 def ismemberdescriptor(object):
127 """Return true if the object is a member descriptor.
128
129 Member descriptors are specialized descriptors defined in extension
130 modules."""
131 return isinstance(object, types.MemberDescriptorType)
132else:
133 # Other implementations
134 def ismemberdescriptor(object):
135 """Return true if the object is a member descriptor.
136
137 Member descriptors are specialized descriptors defined in extension
138 modules."""
139 return False
140
141if hasattr(types, 'GetSetDescriptorType'):
142 # CPython and equivalent
143 def isgetsetdescriptor(object):
144 """Return true if the object is a getset descriptor.
145
146 getset descriptors are specialized descriptors defined in extension
147 modules."""
148 return isinstance(object, types.GetSetDescriptorType)
149else:
150 # Other implementations
151 def isgetsetdescriptor(object):
152 """Return true if the object is a getset descriptor.
153
154 getset descriptors are specialized descriptors defined in extension
155 modules."""
156 return False
157
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000158def isfunction(object):
159 """Return true if the object is a user-defined function.
160
161 Function objects provide these attributes:
162 __doc__ documentation string
163 __name__ name with which this function was defined
Neal Norwitz221085d2007-02-25 20:55:47 +0000164 __code__ code object containing compiled function bytecode
165 __defaults__ tuple of any default values for arguments
166 __globals__ global namespace in which this function was defined
167 __annotations__ dict of parameter annotations
168 __kwdefaults__ dict of keyword only parameters with defaults"""
Tim Peters28bc59f2001-09-16 08:40:16 +0000169 return isinstance(object, types.FunctionType)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000170
Jeroen Demeyerfcef60f2019-04-02 16:03:42 +0200171def _has_code_flag(f, flag):
172 """Return true if ``f`` is a function (or a method or functools.partial
173 wrapper wrapping a function) whose code object has the given ``flag``
174 set in its flags."""
175 while ismethod(f):
176 f = f.__func__
177 f = functools._unwrap_partial(f)
178 if not isfunction(f):
179 return False
180 return bool(f.__code__.co_flags & flag)
181
Pablo Galindo7cd25432018-10-26 12:19:14 +0100182def isgeneratorfunction(obj):
Christian Heimes7131fd92008-02-19 14:21:46 +0000183 """Return true if the object is a user-defined generator function.
184
Martin Panter0f0eac42016-09-07 11:04:41 +0000185 Generator function objects provide the same attributes as functions.
186 See help(isfunction) for a list of attributes."""
Jeroen Demeyerfcef60f2019-04-02 16:03:42 +0200187 return _has_code_flag(obj, CO_GENERATOR)
Yury Selivanov75445082015-05-11 22:57:16 -0400188
Pablo Galindo7cd25432018-10-26 12:19:14 +0100189def iscoroutinefunction(obj):
Yury Selivanov75445082015-05-11 22:57:16 -0400190 """Return true if the object is a coroutine function.
191
Yury Selivanov4778e132016-11-08 12:23:09 -0500192 Coroutine functions are defined with "async def" syntax.
Yury Selivanov75445082015-05-11 22:57:16 -0400193 """
Jeroen Demeyerfcef60f2019-04-02 16:03:42 +0200194 return _has_code_flag(obj, CO_COROUTINE)
Yury Selivanov75445082015-05-11 22:57:16 -0400195
Pablo Galindo7cd25432018-10-26 12:19:14 +0100196def isasyncgenfunction(obj):
Yury Selivanov4778e132016-11-08 12:23:09 -0500197 """Return true if the object is an asynchronous generator function.
198
199 Asynchronous generator functions are defined with "async def"
200 syntax and have "yield" expressions in their body.
201 """
Jeroen Demeyerfcef60f2019-04-02 16:03:42 +0200202 return _has_code_flag(obj, CO_ASYNC_GENERATOR)
Yury Selivanoveb636452016-09-08 22:01:51 -0700203
204def isasyncgen(object):
Yury Selivanov4778e132016-11-08 12:23:09 -0500205 """Return true if the object is an asynchronous generator."""
Yury Selivanoveb636452016-09-08 22:01:51 -0700206 return isinstance(object, types.AsyncGeneratorType)
207
Christian Heimes7131fd92008-02-19 14:21:46 +0000208def isgenerator(object):
209 """Return true if the object is a generator.
210
211 Generator objects provide these attributes:
Ezio Melotti30b9d5d2013-08-17 15:50:46 +0300212 __iter__ defined to support iteration over container
Christian Heimes7131fd92008-02-19 14:21:46 +0000213 close raises a new GeneratorExit exception inside the
214 generator to terminate the iteration
215 gi_code code object
216 gi_frame frame object or possibly None once the generator has
217 been exhausted
218 gi_running set to 1 when generator is executing, 0 otherwise
219 next return the next item from the container
220 send resumes the generator and "sends" a value that becomes
221 the result of the current yield-expression
222 throw used to raise an exception inside the generator"""
Yury Selivanov5376ba92015-06-22 12:19:30 -0400223 return isinstance(object, types.GeneratorType)
Yury Selivanov75445082015-05-11 22:57:16 -0400224
225def iscoroutine(object):
226 """Return true if the object is a coroutine."""
Yury Selivanov5376ba92015-06-22 12:19:30 -0400227 return isinstance(object, types.CoroutineType)
Christian Heimes7131fd92008-02-19 14:21:46 +0000228
Yury Selivanovfdbeb2b2015-07-03 13:11:35 -0400229def isawaitable(object):
Yury Selivanovc0215df2016-11-08 19:57:44 -0500230 """Return true if object can be passed to an ``await`` expression."""
Yury Selivanovfdbeb2b2015-07-03 13:11:35 -0400231 return (isinstance(object, types.CoroutineType) or
232 isinstance(object, types.GeneratorType) and
Yury Selivanovc0215df2016-11-08 19:57:44 -0500233 bool(object.gi_code.co_flags & CO_ITERABLE_COROUTINE) or
Yury Selivanovfdbeb2b2015-07-03 13:11:35 -0400234 isinstance(object, collections.abc.Awaitable))
235
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000236def istraceback(object):
237 """Return true if the object is a traceback.
238
239 Traceback objects provide these attributes:
240 tb_frame frame object at this level
241 tb_lasti index of last attempted instruction in bytecode
242 tb_lineno current line number in Python source code
243 tb_next next inner traceback object (called by this level)"""
Tim Peters28bc59f2001-09-16 08:40:16 +0000244 return isinstance(object, types.TracebackType)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000245
246def isframe(object):
247 """Return true if the object is a frame object.
248
249 Frame objects provide these attributes:
250 f_back next outer frame object (this frame's caller)
251 f_builtins built-in namespace seen by this frame
252 f_code code object being executed in this frame
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000253 f_globals global namespace seen by this frame
254 f_lasti index of last attempted instruction in bytecode
255 f_lineno current line number in Python source code
256 f_locals local namespace seen by this frame
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000257 f_trace tracing function for this frame, or None"""
Tim Peters28bc59f2001-09-16 08:40:16 +0000258 return isinstance(object, types.FrameType)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000259
260def iscode(object):
261 """Return true if the object is a code object.
262
263 Code objects provide these attributes:
Xiang Zhanga6902e62017-04-13 10:38:28 +0800264 co_argcount number of arguments (not including *, ** args
265 or keyword only arguments)
266 co_code string of raw compiled bytecode
267 co_cellvars tuple of names of cell variables
268 co_consts tuple of constants used in the bytecode
269 co_filename name of file in which this code object was created
270 co_firstlineno number of first line in Python source code
271 co_flags bitmap: 1=optimized | 2=newlocals | 4=*arg | 8=**arg
272 | 16=nested | 32=generator | 64=nofree | 128=coroutine
273 | 256=iterable_coroutine | 512=async_generator
274 co_freevars tuple of names of free variables
Pablo Galindo8c77b8c2019-04-29 13:36:57 +0100275 co_posonlyargcount number of positional only arguments
Xiang Zhanga6902e62017-04-13 10:38:28 +0800276 co_kwonlyargcount number of keyword only arguments (not including ** arg)
277 co_lnotab encoded mapping of line numbers to bytecode indices
278 co_name name with which this code object was defined
279 co_names tuple of names of local variables
280 co_nlocals number of local variables
281 co_stacksize virtual machine stack space required
282 co_varnames tuple of names of arguments and local variables"""
Tim Peters28bc59f2001-09-16 08:40:16 +0000283 return isinstance(object, types.CodeType)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000284
285def isbuiltin(object):
286 """Return true if the object is a built-in function or method.
287
288 Built-in functions and methods provide these attributes:
289 __doc__ documentation string
290 __name__ original name of this function or method
291 __self__ instance to which a method is bound, or None"""
Tim Peters28bc59f2001-09-16 08:40:16 +0000292 return isinstance(object, types.BuiltinFunctionType)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000293
294def isroutine(object):
295 """Return true if the object is any kind of function or method."""
Tim Peters536d2262001-09-20 05:13:38 +0000296 return (isbuiltin(object)
297 or isfunction(object)
298 or ismethod(object)
299 or ismethoddescriptor(object))
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000300
Christian Heimesbe5b30b2008-03-03 19:18:51 +0000301def isabstract(object):
302 """Return true if the object is an abstract base class (ABC)."""
Natefcfe80e2017-04-24 10:06:15 -0700303 if not isinstance(object, type):
304 return False
305 if object.__flags__ & TPFLAGS_IS_ABSTRACT:
306 return True
307 if not issubclass(type(object), abc.ABCMeta):
308 return False
309 if hasattr(object, '__abstractmethods__'):
310 # It looks like ABCMeta.__new__ has finished running;
311 # TPFLAGS_IS_ABSTRACT should have been accurate.
312 return False
313 # It looks like ABCMeta.__new__ has not finished running yet; we're
314 # probably in __init_subclass__. We'll look for abstractmethods manually.
315 for name, value in object.__dict__.items():
316 if getattr(value, "__isabstractmethod__", False):
317 return True
318 for base in object.__bases__:
319 for name in getattr(base, "__abstractmethods__", ()):
320 value = getattr(object, name, None)
321 if getattr(value, "__isabstractmethod__", False):
322 return True
323 return False
Christian Heimesbe5b30b2008-03-03 19:18:51 +0000324
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000325def getmembers(object, predicate=None):
326 """Return all members of an object as (name, value) pairs sorted by name.
327 Optionally, only return members that satisfy a given predicate."""
Antoine Pitrou86a8a9a2011-12-21 09:57:40 +0100328 if isclass(object):
329 mro = (object,) + getmro(object)
330 else:
331 mro = ()
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000332 results = []
Ethan Furmane03ea372013-09-25 07:14:41 -0700333 processed = set()
334 names = dir(object)
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700335 # :dd any DynamicClassAttributes to the list of names if object is a class;
Ethan Furmane03ea372013-09-25 07:14:41 -0700336 # this may result in duplicate entries if, for example, a virtual
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700337 # attribute with the same name as a DynamicClassAttribute exists
Ethan Furmane03ea372013-09-25 07:14:41 -0700338 try:
339 for base in object.__bases__:
340 for k, v in base.__dict__.items():
341 if isinstance(v, types.DynamicClassAttribute):
342 names.append(k)
343 except AttributeError:
344 pass
345 for key in names:
Ethan Furman63c141c2013-10-18 00:27:39 -0700346 # First try to get the value via getattr. Some descriptors don't
347 # like calling their __get__ (see bug #1785), so fall back to
348 # looking in the __dict__.
349 try:
350 value = getattr(object, key)
351 # handle the duplicate key
352 if key in processed:
353 raise AttributeError
354 except AttributeError:
355 for base in mro:
356 if key in base.__dict__:
357 value = base.__dict__[key]
358 break
359 else:
360 # could be a (currently) missing slot member, or a buggy
361 # __dir__; discard and move on
Antoine Pitrou86a8a9a2011-12-21 09:57:40 +0100362 continue
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000363 if not predicate or predicate(value):
364 results.append((key, value))
Ethan Furmane03ea372013-09-25 07:14:41 -0700365 processed.add(key)
366 results.sort(key=lambda pair: pair[0])
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000367 return results
368
Christian Heimes25bb7832008-01-11 16:17:00 +0000369Attribute = namedtuple('Attribute', 'name kind defining_class object')
370
Tim Peters13b49d32001-09-23 02:00:29 +0000371def classify_class_attrs(cls):
372 """Return list of attribute-descriptor tuples.
373
374 For each name in dir(cls), the return list contains a 4-tuple
375 with these elements:
376
377 0. The name (a string).
378
379 1. The kind of attribute this is, one of these strings:
380 'class method' created via classmethod()
381 'static method' created via staticmethod()
382 'property' created via property()
Ethan Furmane03ea372013-09-25 07:14:41 -0700383 'method' any other flavor of method or descriptor
Tim Peters13b49d32001-09-23 02:00:29 +0000384 'data' not a method
385
386 2. The class which defined this attribute (a class).
387
Ethan Furmane03ea372013-09-25 07:14:41 -0700388 3. The object as obtained by calling getattr; if this fails, or if the
389 resulting object does not live anywhere in the class' mro (including
390 metaclasses) then the object is looked up in the defining class's
391 dict (found by walking the mro).
Ethan Furman668dede2013-09-14 18:53:26 -0700392
393 If one of the items in dir(cls) is stored in the metaclass it will now
394 be discovered and not have None be listed as the class in which it was
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700395 defined. Any items whose home class cannot be discovered are skipped.
Tim Peters13b49d32001-09-23 02:00:29 +0000396 """
397
398 mro = getmro(cls)
Ethan Furman668dede2013-09-14 18:53:26 -0700399 metamro = getmro(type(cls)) # for attributes stored in the metaclass
Jon Dufresne39726282017-05-18 07:35:54 -0700400 metamro = tuple(cls for cls in metamro if cls not in (type, object))
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700401 class_bases = (cls,) + mro
402 all_bases = class_bases + metamro
Tim Peters13b49d32001-09-23 02:00:29 +0000403 names = dir(cls)
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700404 # :dd any DynamicClassAttributes to the list of names;
Ethan Furmane03ea372013-09-25 07:14:41 -0700405 # this may result in duplicate entries if, for example, a virtual
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700406 # attribute with the same name as a DynamicClassAttribute exists.
Ethan Furman63c141c2013-10-18 00:27:39 -0700407 for base in mro:
Ethan Furmane03ea372013-09-25 07:14:41 -0700408 for k, v in base.__dict__.items():
409 if isinstance(v, types.DynamicClassAttribute):
410 names.append(k)
Tim Peters13b49d32001-09-23 02:00:29 +0000411 result = []
Ethan Furmane03ea372013-09-25 07:14:41 -0700412 processed = set()
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700413
Tim Peters13b49d32001-09-23 02:00:29 +0000414 for name in names:
Antoine Pitrou86a8a9a2011-12-21 09:57:40 +0100415 # Get the object associated with the name, and where it was defined.
Ethan Furmane03ea372013-09-25 07:14:41 -0700416 # Normal objects will be looked up with both getattr and directly in
417 # its class' dict (in case getattr fails [bug #1785], and also to look
418 # for a docstring).
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700419 # For DynamicClassAttributes on the second pass we only look in the
Ethan Furmane03ea372013-09-25 07:14:41 -0700420 # class's dict.
421 #
Tim Peters13b49d32001-09-23 02:00:29 +0000422 # Getting an obj from the __dict__ sometimes reveals more than
423 # using getattr. Static and class methods are dramatic examples.
Antoine Pitrou86a8a9a2011-12-21 09:57:40 +0100424 homecls = None
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700425 get_obj = None
426 dict_obj = None
Ethan Furmane03ea372013-09-25 07:14:41 -0700427 if name not in processed:
428 try:
Ethan Furmana8b07072013-10-18 01:22:08 -0700429 if name == '__dict__':
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700430 raise Exception("__dict__ is special, don't want the proxy")
Ethan Furmane03ea372013-09-25 07:14:41 -0700431 get_obj = getattr(cls, name)
432 except Exception as exc:
433 pass
434 else:
Ethan Furmane03ea372013-09-25 07:14:41 -0700435 homecls = getattr(get_obj, "__objclass__", homecls)
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700436 if homecls not in class_bases:
Ethan Furmane03ea372013-09-25 07:14:41 -0700437 # if the resulting object does not live somewhere in the
Ethan Furman63c141c2013-10-18 00:27:39 -0700438 # mro, drop it and search the mro manually
Ethan Furmane03ea372013-09-25 07:14:41 -0700439 homecls = None
Ethan Furman63c141c2013-10-18 00:27:39 -0700440 last_cls = None
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700441 # first look in the classes
442 for srch_cls in class_bases:
Ethan Furman63c141c2013-10-18 00:27:39 -0700443 srch_obj = getattr(srch_cls, name, None)
Yury Selivanovbf341fb2015-05-21 15:41:57 -0400444 if srch_obj is get_obj:
Ethan Furman63c141c2013-10-18 00:27:39 -0700445 last_cls = srch_cls
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700446 # then check the metaclasses
447 for srch_cls in metamro:
448 try:
449 srch_obj = srch_cls.__getattr__(cls, name)
450 except AttributeError:
451 continue
Yury Selivanovbf341fb2015-05-21 15:41:57 -0400452 if srch_obj is get_obj:
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700453 last_cls = srch_cls
Ethan Furman63c141c2013-10-18 00:27:39 -0700454 if last_cls is not None:
455 homecls = last_cls
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700456 for base in all_bases:
Ethan Furmane03ea372013-09-25 07:14:41 -0700457 if name in base.__dict__:
458 dict_obj = base.__dict__[name]
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700459 if homecls not in metamro:
460 homecls = base
Ethan Furmane03ea372013-09-25 07:14:41 -0700461 break
Ethan Furman63c141c2013-10-18 00:27:39 -0700462 if homecls is None:
463 # unable to locate the attribute anywhere, most likely due to
464 # buggy custom __dir__; discard and move on
465 continue
Yury Selivanovbf341fb2015-05-21 15:41:57 -0400466 obj = get_obj if get_obj is not None else dict_obj
Ethan Furmane03ea372013-09-25 07:14:41 -0700467 # Classify the object or its descriptor.
Serhiy Storchaka3327a2d2017-12-15 14:13:41 +0200468 if isinstance(dict_obj, (staticmethod, types.BuiltinMethodType)):
Tim Peters13b49d32001-09-23 02:00:29 +0000469 kind = "static method"
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700470 obj = dict_obj
Serhiy Storchaka3327a2d2017-12-15 14:13:41 +0200471 elif isinstance(dict_obj, (classmethod, types.ClassMethodDescriptorType)):
Tim Peters13b49d32001-09-23 02:00:29 +0000472 kind = "class method"
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700473 obj = dict_obj
474 elif isinstance(dict_obj, property):
Tim Peters13b49d32001-09-23 02:00:29 +0000475 kind = "property"
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700476 obj = dict_obj
Yury Selivanov0860a0b2014-01-31 14:28:44 -0500477 elif isroutine(obj):
Tim Peters13b49d32001-09-23 02:00:29 +0000478 kind = "method"
Antoine Pitrou86a8a9a2011-12-21 09:57:40 +0100479 else:
Ethan Furmane03ea372013-09-25 07:14:41 -0700480 kind = "data"
Christian Heimes25bb7832008-01-11 16:17:00 +0000481 result.append(Attribute(name, kind, homecls, obj))
Ethan Furmane03ea372013-09-25 07:14:41 -0700482 processed.add(name)
Tim Peters13b49d32001-09-23 02:00:29 +0000483 return result
484
Tim Peterse0b2d7a2001-09-22 06:10:55 +0000485# ----------------------------------------------------------- class helpers
Tim Peterse0b2d7a2001-09-22 06:10:55 +0000486
487def getmro(cls):
488 "Return tuple of base classes (including cls) in method resolution order."
Benjamin Petersonb82c8e52010-11-04 00:38:49 +0000489 return cls.__mro__
Tim Peterse0b2d7a2001-09-22 06:10:55 +0000490
Nick Coghlane8c45d62013-07-28 20:00:01 +1000491# -------------------------------------------------------- function helpers
492
493def unwrap(func, *, stop=None):
494 """Get the object wrapped by *func*.
495
496 Follows the chain of :attr:`__wrapped__` attributes returning the last
497 object in the chain.
498
499 *stop* is an optional callback accepting an object in the wrapper chain
500 as its sole argument that allows the unwrapping to be terminated early if
501 the callback returns a true value. If the callback never returns a true
502 value, the last object in the chain is returned as usual. For example,
503 :func:`signature` uses this to stop unwrapping if any object in the
504 chain has a ``__signature__`` attribute defined.
505
506 :exc:`ValueError` is raised if a cycle is encountered.
507
508 """
509 if stop is None:
510 def _is_wrapper(f):
511 return hasattr(f, '__wrapped__')
512 else:
513 def _is_wrapper(f):
514 return hasattr(f, '__wrapped__') and not stop(f)
515 f = func # remember the original func for error reporting
Thomas Kluyverf9169ce2017-05-23 04:27:52 +0100516 # Memoise by id to tolerate non-hashable objects, but store objects to
517 # ensure they aren't destroyed, which would allow their IDs to be reused.
518 memo = {id(f): f}
519 recursion_limit = sys.getrecursionlimit()
Nick Coghlane8c45d62013-07-28 20:00:01 +1000520 while _is_wrapper(func):
521 func = func.__wrapped__
522 id_func = id(func)
Thomas Kluyverf9169ce2017-05-23 04:27:52 +0100523 if (id_func in memo) or (len(memo) >= recursion_limit):
Nick Coghlane8c45d62013-07-28 20:00:01 +1000524 raise ValueError('wrapper loop when unwrapping {!r}'.format(f))
Thomas Kluyverf9169ce2017-05-23 04:27:52 +0100525 memo[id_func] = func
Nick Coghlane8c45d62013-07-28 20:00:01 +1000526 return func
527
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000528# -------------------------------------------------- source code extraction
529def indentsize(line):
530 """Return the indent size, in spaces, at the start of a line of text."""
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000531 expline = line.expandtabs()
532 return len(expline) - len(expline.lstrip())
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000533
Serhiy Storchaka5cf2b722015-04-03 22:38:53 +0300534def _findclass(func):
535 cls = sys.modules.get(func.__module__)
536 if cls is None:
537 return None
538 for name in func.__qualname__.split('.')[:-1]:
539 cls = getattr(cls, name)
540 if not isclass(cls):
541 return None
542 return cls
543
544def _finddoc(obj):
545 if isclass(obj):
546 for base in obj.__mro__:
547 if base is not object:
548 try:
549 doc = base.__doc__
550 except AttributeError:
551 continue
552 if doc is not None:
553 return doc
554 return None
555
556 if ismethod(obj):
557 name = obj.__func__.__name__
558 self = obj.__self__
559 if (isclass(self) and
560 getattr(getattr(self, name, None), '__func__') is obj.__func__):
561 # classmethod
562 cls = self
563 else:
564 cls = self.__class__
565 elif isfunction(obj):
566 name = obj.__name__
567 cls = _findclass(obj)
568 if cls is None or getattr(cls, name) is not obj:
569 return None
570 elif isbuiltin(obj):
571 name = obj.__name__
572 self = obj.__self__
573 if (isclass(self) and
574 self.__qualname__ + '.' + name == obj.__qualname__):
575 # classmethod
576 cls = self
577 else:
578 cls = self.__class__
Serhiy Storchakaac4bdcc2015-10-29 08:15:50 +0200579 # Should be tested before isdatadescriptor().
580 elif isinstance(obj, property):
581 func = obj.fget
582 name = func.__name__
583 cls = _findclass(func)
584 if cls is None or getattr(cls, name) is not obj:
585 return None
Serhiy Storchaka5cf2b722015-04-03 22:38:53 +0300586 elif ismethoddescriptor(obj) or isdatadescriptor(obj):
587 name = obj.__name__
588 cls = obj.__objclass__
589 if getattr(cls, name) is not obj:
590 return None
Raymond Hettingerd1e768a2019-03-25 13:01:13 -0700591 if ismemberdescriptor(obj):
592 slots = getattr(cls, '__slots__', None)
593 if isinstance(slots, dict) and name in slots:
594 return slots[name]
Serhiy Storchaka5cf2b722015-04-03 22:38:53 +0300595 else:
596 return None
Serhiy Storchaka5cf2b722015-04-03 22:38:53 +0300597 for base in cls.__mro__:
598 try:
599 doc = getattr(base, name).__doc__
600 except AttributeError:
601 continue
602 if doc is not None:
603 return doc
604 return None
605
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000606def getdoc(object):
607 """Get the documentation string for an object.
608
609 All tabs are expanded to spaces. To clean up docstrings that are
610 indented to line up with blocks of code, any whitespace than can be
611 uniformly removed from the second line onwards is removed."""
Tim Peters24008312002-03-17 18:56:20 +0000612 try:
613 doc = object.__doc__
614 except AttributeError:
615 return None
Serhiy Storchaka5cf2b722015-04-03 22:38:53 +0300616 if doc is None:
617 try:
618 doc = _finddoc(object)
619 except (AttributeError, TypeError):
620 return None
Guido van Rossum3172c5d2007-10-16 18:12:55 +0000621 if not isinstance(doc, str):
Tim Peters24008312002-03-17 18:56:20 +0000622 return None
Georg Brandl0c77a822008-06-10 16:37:50 +0000623 return cleandoc(doc)
624
625def cleandoc(doc):
626 """Clean up indentation from docstrings.
627
628 Any whitespace that can be uniformly removed from the second line
629 onwards is removed."""
Tim Peters24008312002-03-17 18:56:20 +0000630 try:
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000631 lines = doc.expandtabs().split('\n')
Tim Peters24008312002-03-17 18:56:20 +0000632 except UnicodeError:
633 return None
634 else:
Ka-Ping Yeea59ef7b2002-11-30 03:53:15 +0000635 # Find minimum indentation of any non-blank lines after first line.
Christian Heimesa37d4c62007-12-04 23:02:19 +0000636 margin = sys.maxsize
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000637 for line in lines[1:]:
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000638 content = len(line.lstrip())
Ka-Ping Yeea59ef7b2002-11-30 03:53:15 +0000639 if content:
640 indent = len(line) - content
641 margin = min(margin, indent)
642 # Remove indentation.
643 if lines:
644 lines[0] = lines[0].lstrip()
Christian Heimesa37d4c62007-12-04 23:02:19 +0000645 if margin < sys.maxsize:
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000646 for i in range(1, len(lines)): lines[i] = lines[i][margin:]
Ka-Ping Yeea59ef7b2002-11-30 03:53:15 +0000647 # Remove any trailing or leading blank lines.
648 while lines and not lines[-1]:
649 lines.pop()
650 while lines and not lines[0]:
651 lines.pop(0)
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000652 return '\n'.join(lines)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000653
654def getfile(object):
Ka-Ping Yeec113c242001-03-02 02:08:53 +0000655 """Work out which source or compiled file an object was defined in."""
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000656 if ismodule(object):
Jason R. Coombsb9650a02018-03-05 18:29:08 -0500657 if getattr(object, '__file__', None):
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000658 return object.__file__
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +0000659 raise TypeError('{!r} is a built-in module'.format(object))
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000660 if isclass(object):
Yury Selivanov2eed8b72014-01-27 13:24:56 -0500661 if hasattr(object, '__module__'):
662 object = sys.modules.get(object.__module__)
Jason R. Coombsb9650a02018-03-05 18:29:08 -0500663 if getattr(object, '__file__', None):
Yury Selivanov2eed8b72014-01-27 13:24:56 -0500664 return object.__file__
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +0000665 raise TypeError('{!r} is a built-in class'.format(object))
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000666 if ismethod(object):
Christian Heimesff737952007-11-27 10:40:20 +0000667 object = object.__func__
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000668 if isfunction(object):
Neal Norwitz221085d2007-02-25 20:55:47 +0000669 object = object.__code__
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000670 if istraceback(object):
671 object = object.tb_frame
672 if isframe(object):
673 object = object.f_code
674 if iscode(object):
675 return object.co_filename
Thomas Kluyvere968bc732017-10-24 13:42:36 +0100676 raise TypeError('module, class, method, function, traceback, frame, or '
677 'code object was expected, got {}'.format(
678 type(object).__name__))
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000679
Ka-Ping Yee4d6fc7f2001-04-10 11:43:00 +0000680def getmodulename(path):
681 """Return the module name for a given file, or None."""
Nick Coghlan76e07702012-07-18 23:14:57 +1000682 fname = os.path.basename(path)
683 # Check for paths that look like an actual module file
684 suffixes = [(-len(suffix), suffix)
685 for suffix in importlib.machinery.all_suffixes()]
686 suffixes.sort() # try longest suffixes first, in case they overlap
687 for neglen, suffix in suffixes:
688 if fname.endswith(suffix):
689 return fname[:neglen]
690 return None
Ka-Ping Yee4d6fc7f2001-04-10 11:43:00 +0000691
Ka-Ping Yeec113c242001-03-02 02:08:53 +0000692def getsourcefile(object):
R. David Murraya1b37402010-06-17 02:04:29 +0000693 """Return the filename that can be used to locate an object's source.
694 Return None if no way can be identified to get the source.
695 """
Ka-Ping Yeec113c242001-03-02 02:08:53 +0000696 filename = getfile(object)
Brett Cannoncb66eb02012-05-11 12:58:42 -0400697 all_bytecode_suffixes = importlib.machinery.DEBUG_BYTECODE_SUFFIXES[:]
698 all_bytecode_suffixes += importlib.machinery.OPTIMIZED_BYTECODE_SUFFIXES[:]
699 if any(filename.endswith(s) for s in all_bytecode_suffixes):
700 filename = (os.path.splitext(filename)[0] +
701 importlib.machinery.SOURCE_SUFFIXES[0])
702 elif any(filename.endswith(s) for s in
703 importlib.machinery.EXTENSION_SUFFIXES):
704 return None
Thomas Wouters477c8d52006-05-27 19:21:47 +0000705 if os.path.exists(filename):
706 return filename
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000707 # only return a non-existent filename if the module has a PEP 302 loader
Brett Cannon4c14b5d2013-05-04 13:56:58 -0400708 if getattr(getmodule(object, filename), '__loader__', None) is not None:
Ka-Ping Yeec113c242001-03-02 02:08:53 +0000709 return filename
R. David Murraya1b37402010-06-17 02:04:29 +0000710 # or it is in the linecache
711 if filename in linecache.cache:
712 return filename
Ka-Ping Yeec113c242001-03-02 02:08:53 +0000713
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000714def getabsfile(object, _filename=None):
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000715 """Return an absolute path to the source or compiled file for an object.
Ka-Ping Yeec113c242001-03-02 02:08:53 +0000716
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000717 The idea is for each object to have a unique origin, so this routine
718 normalizes the result as much as possible."""
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000719 if _filename is None:
720 _filename = getsourcefile(object) or getfile(object)
721 return os.path.normcase(os.path.abspath(_filename))
Ka-Ping Yeec113c242001-03-02 02:08:53 +0000722
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000723modulesbyfile = {}
Thomas Wouters89f507f2006-12-13 04:49:30 +0000724_filesbymodname = {}
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000725
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000726def getmodule(object, _filename=None):
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000727 """Return the module an object was defined in, or None if not found."""
Ka-Ping Yee202c99b2001-04-13 09:15:08 +0000728 if ismodule(object):
729 return object
Johannes Gijsbers93245262004-09-11 15:53:22 +0000730 if hasattr(object, '__module__'):
Ka-Ping Yee8b58b842001-03-01 13:56:16 +0000731 return sys.modules.get(object.__module__)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000732 # Try the filename to modulename cache
733 if _filename is not None and _filename in modulesbyfile:
734 return sys.modules.get(modulesbyfile[_filename])
735 # Try the cache again with the absolute file name
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000736 try:
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000737 file = getabsfile(object, _filename)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000738 except TypeError:
739 return None
Raymond Hettinger54f02222002-06-01 14:18:47 +0000740 if file in modulesbyfile:
Ka-Ping Yeeb38bbbd2003-03-28 16:29:50 +0000741 return sys.modules.get(modulesbyfile[file])
Thomas Wouters89f507f2006-12-13 04:49:30 +0000742 # Update the filename to module name cache and check yet again
743 # Copy sys.modules in order to cope with changes while iterating
Éric Araujoa74f8ef2011-11-29 16:58:53 +0100744 for modname, module in list(sys.modules.items()):
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000745 if ismodule(module) and hasattr(module, '__file__'):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000746 f = module.__file__
747 if f == _filesbymodname.get(modname, None):
748 # Have already mapped this module, so skip it
749 continue
750 _filesbymodname[modname] = f
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000751 f = getabsfile(module)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000752 # Always map to the name the module knows itself by
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000753 modulesbyfile[f] = modulesbyfile[
754 os.path.realpath(f)] = module.__name__
Raymond Hettinger54f02222002-06-01 14:18:47 +0000755 if file in modulesbyfile:
Ka-Ping Yeeb38bbbd2003-03-28 16:29:50 +0000756 return sys.modules.get(modulesbyfile[file])
Thomas Wouters89f507f2006-12-13 04:49:30 +0000757 # Check the main module
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000758 main = sys.modules['__main__']
Brett Cannon4a671fe2003-06-15 22:33:28 +0000759 if not hasattr(object, '__name__'):
760 return None
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000761 if hasattr(main, object.__name__):
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000762 mainobject = getattr(main, object.__name__)
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000763 if mainobject is object:
764 return main
Thomas Wouters89f507f2006-12-13 04:49:30 +0000765 # Check builtins
Georg Brandl1a3284e2007-12-02 09:40:06 +0000766 builtin = sys.modules['builtins']
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000767 if hasattr(builtin, object.__name__):
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000768 builtinobject = getattr(builtin, object.__name__)
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000769 if builtinobject is object:
770 return builtin
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000771
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000772def findsource(object):
773 """Return the entire source file and starting line number for an object.
774
775 The argument may be a module, class, method, function, traceback, frame,
776 or code object. The source code is returned as a list of all the lines
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200777 in the file and the line number indexes a line in that list. An OSError
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000778 is raised if the source code cannot be retrieved."""
Benjamin Peterson9620cc02011-06-11 15:53:11 -0500779
Yury Selivanovef1e7502014-12-08 16:05:34 -0500780 file = getsourcefile(object)
781 if file:
782 # Invalidate cache if needed.
783 linecache.checkcache(file)
784 else:
785 file = getfile(object)
786 # Allow filenames in form of "<something>" to pass through.
787 # `doctest` monkeypatches `linecache` module to enable
788 # inspection, so let `linecache.getlines` to be called.
789 if not (file.startswith('<') and file.endswith('>')):
790 raise OSError('source code not available')
Benjamin Peterson9620cc02011-06-11 15:53:11 -0500791
Thomas Wouters89f507f2006-12-13 04:49:30 +0000792 module = getmodule(object, file)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000793 if module:
794 lines = linecache.getlines(file, module.__dict__)
795 else:
796 lines = linecache.getlines(file)
Neil Schemenauerf06f8532002-03-23 23:51:04 +0000797 if not lines:
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200798 raise OSError('could not get source code')
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000799
800 if ismodule(object):
801 return lines, 0
802
803 if isclass(object):
804 name = object.__name__
Thomas Wouters89f507f2006-12-13 04:49:30 +0000805 pat = re.compile(r'^(\s*)class\s*' + name + r'\b')
806 # make some effort to find the best matching class definition:
807 # use the one with the least indentation, which is the one
808 # that's most probably not inside a function definition.
809 candidates = []
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000810 for i in range(len(lines)):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000811 match = pat.match(lines[i])
812 if match:
813 # if it's at toplevel, it's already the best one
814 if lines[i][0] == 'c':
815 return lines, i
816 # else add whitespace to candidate list
817 candidates.append((match.group(1), i))
818 if candidates:
819 # this will sort by whitespace, and by line number,
820 # less whitespace first
821 candidates.sort()
822 return lines, candidates[0][1]
Jeremy Hyltonab919022003-06-27 18:41:20 +0000823 else:
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200824 raise OSError('could not find class definition')
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000825
826 if ismethod(object):
Christian Heimesff737952007-11-27 10:40:20 +0000827 object = object.__func__
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000828 if isfunction(object):
Neal Norwitz221085d2007-02-25 20:55:47 +0000829 object = object.__code__
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000830 if istraceback(object):
831 object = object.tb_frame
832 if isframe(object):
833 object = object.f_code
834 if iscode(object):
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000835 if not hasattr(object, 'co_firstlineno'):
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200836 raise OSError('could not find function definition')
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000837 lnum = object.co_firstlineno - 1
Yury Selivanove4e811d2015-07-21 19:01:52 +0300838 pat = re.compile(r'^(\s*def\s)|(\s*async\s+def\s)|(.*(?<!\w)lambda(:|\s))|^(\s*@)')
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000839 while lnum > 0:
Ka-Ping Yeea6e59712001-03-10 09:31:55 +0000840 if pat.match(lines[lnum]): break
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000841 lnum = lnum - 1
842 return lines, lnum
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200843 raise OSError('could not find code object')
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000844
845def getcomments(object):
Jeremy Hyltonb4c17c82002-03-28 23:01:56 +0000846 """Get lines of comments immediately preceding an object's source code.
847
848 Returns None when source can't be found.
849 """
850 try:
851 lines, lnum = findsource(object)
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200852 except (OSError, TypeError):
Jeremy Hyltonb4c17c82002-03-28 23:01:56 +0000853 return None
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000854
855 if ismodule(object):
856 # Look for a comment block at the top of the file.
857 start = 0
Ka-Ping Yeeb910efe2001-04-12 13:17:17 +0000858 if lines and lines[0][:2] == '#!': start = 1
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000859 while start < len(lines) and lines[start].strip() in ('', '#'):
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000860 start = start + 1
Ka-Ping Yeeb910efe2001-04-12 13:17:17 +0000861 if start < len(lines) and lines[start][:1] == '#':
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000862 comments = []
863 end = start
864 while end < len(lines) and lines[end][:1] == '#':
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000865 comments.append(lines[end].expandtabs())
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000866 end = end + 1
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000867 return ''.join(comments)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000868
869 # Look for a preceding block of comments at the same indentation.
870 elif lnum > 0:
871 indent = indentsize(lines[lnum])
872 end = lnum - 1
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000873 if end >= 0 and lines[end].lstrip()[:1] == '#' and \
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000874 indentsize(lines[end]) == indent:
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000875 comments = [lines[end].expandtabs().lstrip()]
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000876 if end > 0:
877 end = end - 1
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000878 comment = lines[end].expandtabs().lstrip()
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000879 while comment[:1] == '#' and indentsize(lines[end]) == indent:
880 comments[:0] = [comment]
881 end = end - 1
882 if end < 0: break
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000883 comment = lines[end].expandtabs().lstrip()
884 while comments and comments[0].strip() == '#':
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000885 comments[:1] = []
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000886 while comments and comments[-1].strip() == '#':
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000887 comments[-1:] = []
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000888 return ''.join(comments)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000889
Tim Peters4efb6e92001-06-29 23:51:08 +0000890class EndOfBlock(Exception): pass
891
892class BlockFinder:
893 """Provide a tokeneater() method to detect the end of a code block."""
894 def __init__(self):
895 self.indent = 0
Johannes Gijsbersa5855d52005-03-12 16:37:11 +0000896 self.islambda = False
Johannes Gijsbers1542f342004-12-12 16:46:28 +0000897 self.started = False
898 self.passline = False
Meador Inge5b718d72015-07-23 22:49:37 -0500899 self.indecorator = False
900 self.decoratorhasargs = False
Armin Rigodd5c0232005-09-25 11:45:45 +0000901 self.last = 1
Tim Peters4efb6e92001-06-29 23:51:08 +0000902
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000903 def tokeneater(self, type, token, srowcol, erowcol, line):
Meador Inge5b718d72015-07-23 22:49:37 -0500904 if not self.started and not self.indecorator:
905 # skip any decorators
906 if token == "@":
907 self.indecorator = True
Armin Rigodd5c0232005-09-25 11:45:45 +0000908 # look for the first "def", "class" or "lambda"
Meador Inge5b718d72015-07-23 22:49:37 -0500909 elif token in ("def", "class", "lambda"):
Johannes Gijsbersa5855d52005-03-12 16:37:11 +0000910 if token == "lambda":
911 self.islambda = True
Johannes Gijsbers1542f342004-12-12 16:46:28 +0000912 self.started = True
Armin Rigodd5c0232005-09-25 11:45:45 +0000913 self.passline = True # skip to the end of the line
Meador Inge5b718d72015-07-23 22:49:37 -0500914 elif token == "(":
915 if self.indecorator:
916 self.decoratorhasargs = True
917 elif token == ")":
918 if self.indecorator:
919 self.indecorator = False
920 self.decoratorhasargs = False
Tim Peters4efb6e92001-06-29 23:51:08 +0000921 elif type == tokenize.NEWLINE:
Armin Rigodd5c0232005-09-25 11:45:45 +0000922 self.passline = False # stop skipping when a NEWLINE is seen
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000923 self.last = srowcol[0]
Armin Rigodd5c0232005-09-25 11:45:45 +0000924 if self.islambda: # lambdas always end at the first NEWLINE
925 raise EndOfBlock
Meador Inge5b718d72015-07-23 22:49:37 -0500926 # hitting a NEWLINE when in a decorator without args
927 # ends the decorator
928 if self.indecorator and not self.decoratorhasargs:
929 self.indecorator = False
Johannes Gijsbers1542f342004-12-12 16:46:28 +0000930 elif self.passline:
931 pass
Tim Peters4efb6e92001-06-29 23:51:08 +0000932 elif type == tokenize.INDENT:
933 self.indent = self.indent + 1
Johannes Gijsbers1542f342004-12-12 16:46:28 +0000934 self.passline = True
Tim Peters4efb6e92001-06-29 23:51:08 +0000935 elif type == tokenize.DEDENT:
936 self.indent = self.indent - 1
Armin Rigodd5c0232005-09-25 11:45:45 +0000937 # the end of matching indent/dedent pairs end a block
938 # (note that this only works for "def"/"class" blocks,
939 # not e.g. for "if: else:" or "try: finally:" blocks)
940 if self.indent <= 0:
941 raise EndOfBlock
942 elif self.indent == 0 and type not in (tokenize.COMMENT, tokenize.NL):
943 # any other token on the same indentation level end the previous
944 # block as well, except the pseudo-tokens COMMENT and NL.
945 raise EndOfBlock
Tim Peters4efb6e92001-06-29 23:51:08 +0000946
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000947def getblock(lines):
948 """Extract the block of code at the top of the given list of lines."""
Armin Rigodd5c0232005-09-25 11:45:45 +0000949 blockfinder = BlockFinder()
Tim Peters4efb6e92001-06-29 23:51:08 +0000950 try:
Trent Nelson428de652008-03-18 22:41:35 +0000951 tokens = tokenize.generate_tokens(iter(lines).__next__)
952 for _token in tokens:
953 blockfinder.tokeneater(*_token)
Armin Rigodd5c0232005-09-25 11:45:45 +0000954 except (EndOfBlock, IndentationError):
955 pass
956 return lines[:blockfinder.last]
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000957
958def getsourcelines(object):
959 """Return a list of source lines and starting line number for an object.
960
961 The argument may be a module, class, method, function, traceback, frame,
962 or code object. The source code is returned as a list of the lines
963 corresponding to the object and the line number indicates where in the
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200964 original source file the first line of code was found. An OSError is
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000965 raised if the source code cannot be retrieved."""
Yury Selivanov081bbf62014-09-26 17:34:54 -0400966 object = unwrap(object)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000967 lines, lnum = findsource(object)
968
Vladimir Matveev91cb2982018-08-24 07:18:00 -0700969 if istraceback(object):
970 object = object.tb_frame
971
972 # for module or frame that corresponds to module, return all source lines
973 if (ismodule(object) or
974 (isframe(object) and object.f_code.co_name == "<module>")):
Meador Inge5b718d72015-07-23 22:49:37 -0500975 return lines, 0
976 else:
977 return getblock(lines[lnum:]), lnum + 1
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000978
979def getsource(object):
980 """Return the text of the source code for an object.
981
982 The argument may be a module, class, method, function, traceback, frame,
983 or code object. The source code is returned as a single string. An
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200984 OSError is raised if the source code cannot be retrieved."""
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000985 lines, lnum = getsourcelines(object)
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000986 return ''.join(lines)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000987
988# --------------------------------------------------- class tree extraction
989def walktree(classes, children, parent):
990 """Recursive helper function for getclasstree()."""
991 results = []
Raymond Hettingera1a992c2005-03-11 06:46:45 +0000992 classes.sort(key=attrgetter('__module__', '__name__'))
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000993 for c in classes:
994 results.append((c, c.__bases__))
Raymond Hettinger54f02222002-06-01 14:18:47 +0000995 if c in children:
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000996 results.append(walktree(children[c], children, c))
997 return results
998
Georg Brandl5ce83a02009-06-01 17:23:51 +0000999def getclasstree(classes, unique=False):
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001000 """Arrange the given list of classes into a hierarchy of nested lists.
1001
1002 Where a nested list appears, it contains classes derived from the class
1003 whose entry immediately precedes the list. Each entry is a 2-tuple
1004 containing a class and a tuple of its base classes. If the 'unique'
1005 argument is true, exactly one entry appears in the returned structure
1006 for each class in the given list. Otherwise, classes using multiple
1007 inheritance and their descendants will appear multiple times."""
1008 children = {}
1009 roots = []
1010 for c in classes:
1011 if c.__bases__:
1012 for parent in c.__bases__:
Srinivas Reddy Thatiparthy (శ్రీనివాస్ రెడ్డి తాటిపర్తి)feaefc72018-02-09 15:29:19 +05301013 if parent not in children:
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001014 children[parent] = []
Serhiy Storchaka362c1b52013-09-05 17:14:32 +03001015 if c not in children[parent]:
1016 children[parent].append(c)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001017 if unique and parent in classes: break
1018 elif c not in roots:
1019 roots.append(c)
Raymond Hettingere0d49722002-06-02 18:55:56 +00001020 for parent in children:
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001021 if parent not in classes:
1022 roots.append(parent)
1023 return walktree(roots, children, None)
1024
1025# ------------------------------------------------ argument list extraction
Christian Heimes25bb7832008-01-11 16:17:00 +00001026Arguments = namedtuple('Arguments', 'args, varargs, varkw')
1027
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001028def getargs(co):
1029 """Get information about the arguments accepted by a code object.
1030
Guido van Rossum2e65f892007-02-28 22:03:49 +00001031 Three things are returned: (args, varargs, varkw), where
Georg Brandlc1c4bf82010-10-15 16:07:41 +00001032 'args' is the list of argument names. Keyword-only arguments are
1033 appended. 'varargs' and 'varkw' are the names of the * and **
1034 arguments or None."""
Jeremy Hylton64967882003-06-27 18:14:39 +00001035 if not iscode(co):
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00001036 raise TypeError('{!r} is not a code object'.format(co))
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001037
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001038 names = co.co_varnames
Pablo Galindo8c77b8c2019-04-29 13:36:57 +01001039 nargs = co.co_argcount
1040 nposonlyargs = co.co_posonlyargcount
Guido van Rossum2e65f892007-02-28 22:03:49 +00001041 nkwargs = co.co_kwonlyargcount
Pablo Galindo8c77b8c2019-04-29 13:36:57 +01001042 nposargs = nargs + nposonlyargs
1043 posonlyargs = list(names[:nposonlyargs])
1044 args = list(names[nposonlyargs:nposonlyargs+nargs])
1045 kwonlyargs = list(names[nposargs:nposargs+nkwargs])
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001046 step = 0
1047
Pablo Galindo8c77b8c2019-04-29 13:36:57 +01001048 nargs += nposonlyargs
Guido van Rossum2e65f892007-02-28 22:03:49 +00001049 nargs += nkwargs
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001050 varargs = None
1051 if co.co_flags & CO_VARARGS:
1052 varargs = co.co_varnames[nargs]
1053 nargs = nargs + 1
1054 varkw = None
1055 if co.co_flags & CO_VARKEYWORDS:
1056 varkw = co.co_varnames[nargs]
Pablo Galindo8c77b8c2019-04-29 13:36:57 +01001057 return Arguments(posonlyargs + args + kwonlyargs, varargs, varkw)
Yury Selivanov37dc2b22016-01-11 15:15:01 -05001058
1059ArgSpec = namedtuple('ArgSpec', 'args varargs keywords defaults')
1060
1061def getargspec(func):
Nick Coghlan3c35fdb2016-12-02 20:29:57 +10001062 """Get the names and default values of a function's parameters.
Yury Selivanov37dc2b22016-01-11 15:15:01 -05001063
1064 A tuple of four things is returned: (args, varargs, keywords, defaults).
1065 'args' is a list of the argument names, including keyword-only argument names.
Nick Coghlan3c35fdb2016-12-02 20:29:57 +10001066 'varargs' and 'keywords' are the names of the * and ** parameters or None.
1067 'defaults' is an n-tuple of the default values of the last n parameters.
Yury Selivanov37dc2b22016-01-11 15:15:01 -05001068
Nick Coghlan3c35fdb2016-12-02 20:29:57 +10001069 This function is deprecated, as it does not support annotations or
1070 keyword-only parameters and will raise ValueError if either is present
1071 on the supplied callable.
1072
1073 For a more structured introspection API, use inspect.signature() instead.
1074
1075 Alternatively, use getfullargspec() for an API with a similar namedtuple
1076 based interface, but full support for annotations and keyword-only
1077 parameters.
Matthias Bussonnierded87d82018-10-19 16:40:45 -07001078
1079 Deprecated since Python 3.5, use `inspect.getfullargspec()`.
Yury Selivanov37dc2b22016-01-11 15:15:01 -05001080 """
Matthias Bussonnierded87d82018-10-19 16:40:45 -07001081 warnings.warn("inspect.getargspec() is deprecated since Python 3.0, "
Nick Coghlan3c35fdb2016-12-02 20:29:57 +10001082 "use inspect.signature() or inspect.getfullargspec()",
1083 DeprecationWarning, stacklevel=2)
Pablo Galindod5d2b452019-04-30 02:01:14 +01001084 args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults, ann = \
1085 getfullargspec(func)
1086 if kwonlyargs or ann:
1087 raise ValueError("Function has keyword-only parameters or annotations"
1088 ", use inspect.signature() API which can support them")
Yury Selivanov37dc2b22016-01-11 15:15:01 -05001089 return ArgSpec(args, varargs, varkw, defaults)
1090
Christian Heimes25bb7832008-01-11 16:17:00 +00001091FullArgSpec = namedtuple('FullArgSpec',
Pablo Galindod5d2b452019-04-30 02:01:14 +01001092 'args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults, annotations')
Guido van Rossum2e65f892007-02-28 22:03:49 +00001093
1094def getfullargspec(func):
Nick Coghlan3c35fdb2016-12-02 20:29:57 +10001095 """Get the names and default values of a callable object's parameters.
Guido van Rossum2e65f892007-02-28 22:03:49 +00001096
Brett Cannon504d8852007-09-07 02:12:14 +00001097 A tuple of seven things is returned:
Nick Coghlan3c35fdb2016-12-02 20:29:57 +10001098 (args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults, annotations).
1099 'args' is a list of the parameter names.
1100 'varargs' and 'varkw' are the names of the * and ** parameters or None.
1101 'defaults' is an n-tuple of the default values of the last n parameters.
1102 'kwonlyargs' is a list of keyword-only parameter names.
Guido van Rossum2e65f892007-02-28 22:03:49 +00001103 'kwonlydefaults' is a dictionary mapping names from kwonlyargs to defaults.
Nick Coghlan3c35fdb2016-12-02 20:29:57 +10001104 'annotations' is a dictionary mapping parameter names to annotations.
Guido van Rossuma8add0e2007-05-14 22:03:55 +00001105
Nick Coghlan3c35fdb2016-12-02 20:29:57 +10001106 Notable differences from inspect.signature():
1107 - the "self" parameter is always reported, even for bound methods
1108 - wrapper chains defined by __wrapped__ *not* unwrapped automatically
Jeremy Hylton64967882003-06-27 18:14:39 +00001109 """
Yury Selivanov57d240e2014-02-19 16:27:23 -05001110 try:
1111 # Re: `skip_bound_arg=False`
1112 #
Yury Selivanovd82eddc2014-01-29 11:24:39 -05001113 # There is a notable difference in behaviour between getfullargspec
1114 # and Signature: the former always returns 'self' parameter for bound
1115 # methods, whereas the Signature always shows the actual calling
1116 # signature of the passed object.
1117 #
1118 # To simulate this behaviour, we "unbind" bound methods, to trick
1119 # inspect.signature to always return their first parameter ("self",
1120 # usually)
Yury Selivanovd82eddc2014-01-29 11:24:39 -05001121
Yury Selivanov57d240e2014-02-19 16:27:23 -05001122 # Re: `follow_wrapper_chains=False`
1123 #
1124 # getfullargspec() historically ignored __wrapped__ attributes,
1125 # so we ensure that remains the case in 3.3+
Yury Selivanovd82eddc2014-01-29 11:24:39 -05001126
Yury Selivanov5a23bd02014-03-29 13:47:11 -04001127 sig = _signature_from_callable(func,
1128 follow_wrapper_chains=False,
1129 skip_bound_arg=False,
1130 sigcls=Signature)
Yury Selivanovd82eddc2014-01-29 11:24:39 -05001131 except Exception as ex:
1132 # Most of the times 'signature' will raise ValueError.
1133 # But, it can also raise AttributeError, and, maybe something
1134 # else. So to be fully backwards compatible, we catch all
1135 # possible exceptions here, and reraise a TypeError.
1136 raise TypeError('unsupported callable') from ex
1137
1138 args = []
1139 varargs = None
1140 varkw = None
Pablo Galindo8c77b8c2019-04-29 13:36:57 +01001141 posonlyargs = []
Yury Selivanovd82eddc2014-01-29 11:24:39 -05001142 kwonlyargs = []
1143 defaults = ()
1144 annotations = {}
1145 defaults = ()
1146 kwdefaults = {}
1147
1148 if sig.return_annotation is not sig.empty:
1149 annotations['return'] = sig.return_annotation
1150
1151 for param in sig.parameters.values():
1152 kind = param.kind
1153 name = param.name
1154
1155 if kind is _POSITIONAL_ONLY:
Pablo Galindo8c77b8c2019-04-29 13:36:57 +01001156 posonlyargs.append(name)
1157 if param.default is not param.empty:
1158 defaults += (param.default,)
Yury Selivanovd82eddc2014-01-29 11:24:39 -05001159 elif kind is _POSITIONAL_OR_KEYWORD:
1160 args.append(name)
1161 if param.default is not param.empty:
1162 defaults += (param.default,)
1163 elif kind is _VAR_POSITIONAL:
1164 varargs = name
1165 elif kind is _KEYWORD_ONLY:
1166 kwonlyargs.append(name)
1167 if param.default is not param.empty:
1168 kwdefaults[name] = param.default
1169 elif kind is _VAR_KEYWORD:
1170 varkw = name
1171
1172 if param.annotation is not param.empty:
1173 annotations[name] = param.annotation
1174
1175 if not kwdefaults:
1176 # compatibility with 'func.__kwdefaults__'
1177 kwdefaults = None
1178
1179 if not defaults:
1180 # compatibility with 'func.__defaults__'
1181 defaults = None
1182
Pablo Galindod5d2b452019-04-30 02:01:14 +01001183 return FullArgSpec(posonlyargs + args, varargs, varkw, defaults,
1184 kwonlyargs, kwdefaults, annotations)
Yury Selivanovd82eddc2014-01-29 11:24:39 -05001185
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001186
Christian Heimes25bb7832008-01-11 16:17:00 +00001187ArgInfo = namedtuple('ArgInfo', 'args varargs keywords locals')
1188
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001189def getargvalues(frame):
1190 """Get information about arguments passed into a particular frame.
1191
1192 A tuple of four things is returned: (args, varargs, varkw, locals).
Georg Brandlc1c4bf82010-10-15 16:07:41 +00001193 'args' is a list of the argument names.
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001194 'varargs' and 'varkw' are the names of the * and ** arguments or None.
1195 'locals' is the locals dictionary of the given frame."""
1196 args, varargs, varkw = getargs(frame.f_code)
Benjamin Peterson1a6e0d02008-10-25 15:49:17 +00001197 return ArgInfo(args, varargs, varkw, frame.f_locals)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001198
Guido van Rossum2e65f892007-02-28 22:03:49 +00001199def formatannotation(annotation, base_module=None):
Guido van Rossum52e50042016-10-22 07:55:18 -07001200 if getattr(annotation, '__module__', None) == 'typing':
1201 return repr(annotation).replace('typing.', '')
Guido van Rossum2e65f892007-02-28 22:03:49 +00001202 if isinstance(annotation, type):
Georg Brandl1a3284e2007-12-02 09:40:06 +00001203 if annotation.__module__ in ('builtins', base_module):
Serhiy Storchaka521e5862014-07-22 15:00:37 +03001204 return annotation.__qualname__
1205 return annotation.__module__+'.'+annotation.__qualname__
Guido van Rossum2e65f892007-02-28 22:03:49 +00001206 return repr(annotation)
Guido van Rossuma8add0e2007-05-14 22:03:55 +00001207
Guido van Rossum2e65f892007-02-28 22:03:49 +00001208def formatannotationrelativeto(object):
Guido van Rossuma8add0e2007-05-14 22:03:55 +00001209 module = getattr(object, '__module__', None)
1210 def _formatannotation(annotation):
1211 return formatannotation(annotation, module)
1212 return _formatannotation
Guido van Rossum2e65f892007-02-28 22:03:49 +00001213
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001214def formatargspec(args, varargs=None, varkw=None, defaults=None,
Pablo Galindod5d2b452019-04-30 02:01:14 +01001215 kwonlyargs=(), kwonlydefaults={}, annotations={},
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001216 formatarg=str,
1217 formatvarargs=lambda name: '*' + name,
1218 formatvarkw=lambda name: '**' + name,
1219 formatvalue=lambda value: '=' + repr(value),
Guido van Rossum2e65f892007-02-28 22:03:49 +00001220 formatreturns=lambda text: ' -> ' + text,
Georg Brandlc1c4bf82010-10-15 16:07:41 +00001221 formatannotation=formatannotation):
Berker Peksagfa3922c2015-07-31 04:11:29 +03001222 """Format an argument spec from the values returned by getfullargspec.
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001223
Guido van Rossum2e65f892007-02-28 22:03:49 +00001224 The first seven arguments are (args, varargs, varkw, defaults,
1225 kwonlyargs, kwonlydefaults, annotations). The other five arguments
1226 are the corresponding optional formatting functions that are called to
1227 turn names and values into strings. The last argument is an optional
Matthias Bussonnier46c5cd02018-06-11 22:08:16 +02001228 function to format the sequence of arguments.
1229
1230 Deprecated since Python 3.5: use the `signature` function and `Signature`
1231 objects.
1232 """
1233
1234 from warnings import warn
1235
1236 warn("`formatargspec` is deprecated since Python 3.5. Use `signature` and "
Zackery Spytz41254eb2018-06-11 21:16:18 -06001237 "the `Signature` object directly",
Matthias Bussonnier46c5cd02018-06-11 22:08:16 +02001238 DeprecationWarning,
1239 stacklevel=2)
1240
Guido van Rossum2e65f892007-02-28 22:03:49 +00001241 def formatargandannotation(arg):
1242 result = formatarg(arg)
1243 if arg in annotations:
1244 result += ': ' + formatannotation(annotations[arg])
1245 return result
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001246 specs = []
1247 if defaults:
Pablo Galindod5d2b452019-04-30 02:01:14 +01001248 firstdefault = len(args) - len(defaults)
1249 for i, arg in enumerate(args):
Georg Brandlc1c4bf82010-10-15 16:07:41 +00001250 spec = formatargandannotation(arg)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001251 if defaults and i >= firstdefault:
1252 spec = spec + formatvalue(defaults[i - firstdefault])
1253 specs.append(spec)
Raymond Hettinger936654b2002-06-01 03:06:31 +00001254 if varargs is not None:
Guido van Rossum2e65f892007-02-28 22:03:49 +00001255 specs.append(formatvarargs(formatargandannotation(varargs)))
1256 else:
1257 if kwonlyargs:
1258 specs.append('*')
1259 if kwonlyargs:
1260 for kwonlyarg in kwonlyargs:
1261 spec = formatargandannotation(kwonlyarg)
Benjamin Peterson9953a8d2009-01-17 04:15:01 +00001262 if kwonlydefaults and kwonlyarg in kwonlydefaults:
Guido van Rossum2e65f892007-02-28 22:03:49 +00001263 spec += formatvalue(kwonlydefaults[kwonlyarg])
1264 specs.append(spec)
Raymond Hettinger936654b2002-06-01 03:06:31 +00001265 if varkw is not None:
Guido van Rossum2e65f892007-02-28 22:03:49 +00001266 specs.append(formatvarkw(formatargandannotation(varkw)))
Neal Norwitz9d72bb42007-04-17 08:48:32 +00001267 result = '(' + ', '.join(specs) + ')'
Guido van Rossum2e65f892007-02-28 22:03:49 +00001268 if 'return' in annotations:
1269 result += formatreturns(formatannotation(annotations['return']))
1270 return result
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001271
1272def formatargvalues(args, varargs, varkw, locals,
1273 formatarg=str,
1274 formatvarargs=lambda name: '*' + name,
1275 formatvarkw=lambda name: '**' + name,
Georg Brandlc1c4bf82010-10-15 16:07:41 +00001276 formatvalue=lambda value: '=' + repr(value)):
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001277 """Format an argument spec from the 4 values returned by getargvalues.
1278
1279 The first four arguments are (args, varargs, varkw, locals). The
1280 next four arguments are the corresponding optional formatting functions
1281 that are called to turn names and values into strings. The ninth
1282 argument is an optional function to format the sequence of arguments."""
1283 def convert(name, locals=locals,
1284 formatarg=formatarg, formatvalue=formatvalue):
1285 return formatarg(name) + formatvalue(locals[name])
1286 specs = []
1287 for i in range(len(args)):
Georg Brandlc1c4bf82010-10-15 16:07:41 +00001288 specs.append(convert(args[i]))
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001289 if varargs:
1290 specs.append(formatvarargs(varargs) + formatvalue(locals[varargs]))
1291 if varkw:
1292 specs.append(formatvarkw(varkw) + formatvalue(locals[varkw]))
Neal Norwitz9d72bb42007-04-17 08:48:32 +00001293 return '(' + ', '.join(specs) + ')'
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001294
Benjamin Petersone109c702011-06-24 09:37:26 -05001295def _missing_arguments(f_name, argnames, pos, values):
1296 names = [repr(name) for name in argnames if name not in values]
1297 missing = len(names)
1298 if missing == 1:
1299 s = names[0]
1300 elif missing == 2:
1301 s = "{} and {}".format(*names)
1302 else:
Yury Selivanovdccfa132014-03-27 18:42:52 -04001303 tail = ", {} and {}".format(*names[-2:])
Benjamin Petersone109c702011-06-24 09:37:26 -05001304 del names[-2:]
1305 s = ", ".join(names) + tail
1306 raise TypeError("%s() missing %i required %s argument%s: %s" %
1307 (f_name, missing,
1308 "positional" if pos else "keyword-only",
1309 "" if missing == 1 else "s", s))
1310
1311def _too_many(f_name, args, kwonly, varargs, defcount, given, values):
Benjamin Petersonb204a422011-06-05 22:04:07 -05001312 atleast = len(args) - defcount
Benjamin Petersonb204a422011-06-05 22:04:07 -05001313 kwonly_given = len([arg for arg in kwonly if arg in values])
1314 if varargs:
1315 plural = atleast != 1
1316 sig = "at least %d" % (atleast,)
1317 elif defcount:
1318 plural = True
1319 sig = "from %d to %d" % (atleast, len(args))
1320 else:
1321 plural = len(args) != 1
1322 sig = str(len(args))
1323 kwonly_sig = ""
1324 if kwonly_given:
1325 msg = " positional argument%s (and %d keyword-only argument%s)"
1326 kwonly_sig = (msg % ("s" if given != 1 else "", kwonly_given,
1327 "s" if kwonly_given != 1 else ""))
1328 raise TypeError("%s() takes %s positional argument%s but %d%s %s given" %
1329 (f_name, sig, "s" if plural else "", given, kwonly_sig,
1330 "was" if given == 1 and not kwonly_given else "were"))
1331
Benjamin Peterson3e6ab172014-01-02 12:24:08 -06001332def getcallargs(*func_and_positional, **named):
Benjamin Peterson25cd7eb2010-03-30 18:42:32 +00001333 """Get the mapping of arguments to values.
1334
1335 A dict is returned, with keys the function argument names (including the
1336 names of the * and ** arguments, if any), and values the respective bound
1337 values from 'positional' and 'named'."""
Benjamin Peterson3e6ab172014-01-02 12:24:08 -06001338 func = func_and_positional[0]
1339 positional = func_and_positional[1:]
Benjamin Peterson25cd7eb2010-03-30 18:42:32 +00001340 spec = getfullargspec(func)
Pablo Galindod5d2b452019-04-30 02:01:14 +01001341 args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults, ann = spec
Benjamin Peterson25cd7eb2010-03-30 18:42:32 +00001342 f_name = func.__name__
1343 arg2value = {}
1344
Benjamin Petersonb204a422011-06-05 22:04:07 -05001345
Benjamin Peterson25cd7eb2010-03-30 18:42:32 +00001346 if ismethod(func) and func.__self__ is not None:
1347 # implicit 'self' (or 'cls' for classmethods) argument
1348 positional = (func.__self__,) + positional
1349 num_pos = len(positional)
Benjamin Peterson25cd7eb2010-03-30 18:42:32 +00001350 num_args = len(args)
1351 num_defaults = len(defaults) if defaults else 0
Benjamin Peterson25cd7eb2010-03-30 18:42:32 +00001352
Benjamin Petersonb204a422011-06-05 22:04:07 -05001353 n = min(num_pos, num_args)
1354 for i in range(n):
Pablo Galindod5d2b452019-04-30 02:01:14 +01001355 arg2value[args[i]] = positional[i]
Benjamin Petersonb204a422011-06-05 22:04:07 -05001356 if varargs:
1357 arg2value[varargs] = tuple(positional[n:])
1358 possible_kwargs = set(args + kwonlyargs)
Benjamin Peterson25cd7eb2010-03-30 18:42:32 +00001359 if varkw:
Benjamin Petersonb204a422011-06-05 22:04:07 -05001360 arg2value[varkw] = {}
1361 for kw, value in named.items():
1362 if kw not in possible_kwargs:
1363 if not varkw:
1364 raise TypeError("%s() got an unexpected keyword argument %r" %
1365 (f_name, kw))
1366 arg2value[varkw][kw] = value
1367 continue
1368 if kw in arg2value:
1369 raise TypeError("%s() got multiple values for argument %r" %
1370 (f_name, kw))
1371 arg2value[kw] = value
1372 if num_pos > num_args and not varargs:
Benjamin Petersone109c702011-06-24 09:37:26 -05001373 _too_many(f_name, args, kwonlyargs, varargs, num_defaults,
1374 num_pos, arg2value)
Benjamin Petersonb204a422011-06-05 22:04:07 -05001375 if num_pos < num_args:
Benjamin Petersone109c702011-06-24 09:37:26 -05001376 req = args[:num_args - num_defaults]
1377 for arg in req:
Benjamin Petersonb204a422011-06-05 22:04:07 -05001378 if arg not in arg2value:
Benjamin Petersone109c702011-06-24 09:37:26 -05001379 _missing_arguments(f_name, req, True, arg2value)
Benjamin Petersonb204a422011-06-05 22:04:07 -05001380 for i, arg in enumerate(args[num_args - num_defaults:]):
1381 if arg not in arg2value:
1382 arg2value[arg] = defaults[i]
Benjamin Petersone109c702011-06-24 09:37:26 -05001383 missing = 0
Benjamin Petersonb204a422011-06-05 22:04:07 -05001384 for kwarg in kwonlyargs:
1385 if kwarg not in arg2value:
Yury Selivanov875df202014-03-27 18:23:03 -04001386 if kwonlydefaults and kwarg in kwonlydefaults:
Benjamin Petersone109c702011-06-24 09:37:26 -05001387 arg2value[kwarg] = kwonlydefaults[kwarg]
1388 else:
1389 missing += 1
1390 if missing:
1391 _missing_arguments(f_name, kwonlyargs, False, arg2value)
Benjamin Peterson25cd7eb2010-03-30 18:42:32 +00001392 return arg2value
1393
Nick Coghlan2f92e542012-06-23 19:39:55 +10001394ClosureVars = namedtuple('ClosureVars', 'nonlocals globals builtins unbound')
1395
1396def getclosurevars(func):
1397 """
1398 Get the mapping of free variables to their current values.
1399
Meador Inge8fda3592012-07-19 21:33:21 -05001400 Returns a named tuple of dicts mapping the current nonlocal, global
Nick Coghlan2f92e542012-06-23 19:39:55 +10001401 and builtin references as seen by the body of the function. A final
1402 set of unbound names that could not be resolved is also provided.
1403 """
1404
1405 if ismethod(func):
1406 func = func.__func__
1407
1408 if not isfunction(func):
Serhiy Storchakaa4a30202017-11-28 22:54:42 +02001409 raise TypeError("{!r} is not a Python function".format(func))
Nick Coghlan2f92e542012-06-23 19:39:55 +10001410
1411 code = func.__code__
1412 # Nonlocal references are named in co_freevars and resolved
1413 # by looking them up in __closure__ by positional index
1414 if func.__closure__ is None:
1415 nonlocal_vars = {}
1416 else:
1417 nonlocal_vars = {
1418 var : cell.cell_contents
1419 for var, cell in zip(code.co_freevars, func.__closure__)
1420 }
1421
1422 # Global and builtin references are named in co_names and resolved
1423 # by looking them up in __globals__ or __builtins__
1424 global_ns = func.__globals__
1425 builtin_ns = global_ns.get("__builtins__", builtins.__dict__)
1426 if ismodule(builtin_ns):
1427 builtin_ns = builtin_ns.__dict__
1428 global_vars = {}
1429 builtin_vars = {}
1430 unbound_names = set()
1431 for name in code.co_names:
1432 if name in ("None", "True", "False"):
1433 # Because these used to be builtins instead of keywords, they
1434 # may still show up as name references. We ignore them.
1435 continue
1436 try:
1437 global_vars[name] = global_ns[name]
1438 except KeyError:
1439 try:
1440 builtin_vars[name] = builtin_ns[name]
1441 except KeyError:
1442 unbound_names.add(name)
1443
1444 return ClosureVars(nonlocal_vars, global_vars,
1445 builtin_vars, unbound_names)
1446
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001447# -------------------------------------------------- stack frame extraction
Christian Heimes25bb7832008-01-11 16:17:00 +00001448
1449Traceback = namedtuple('Traceback', 'filename lineno function code_context index')
1450
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001451def getframeinfo(frame, context=1):
1452 """Get information about a frame or traceback object.
1453
1454 A tuple of five things is returned: the filename, the line number of
1455 the current line, the function name, a list of lines of context from
1456 the source code, and the index of the current line within that list.
1457 The optional second argument specifies the number of lines of context
1458 to return, which are centered around the current line."""
1459 if istraceback(frame):
Andrew M. Kuchlingba8b6bc2004-06-05 14:11:59 +00001460 lineno = frame.tb_lineno
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001461 frame = frame.tb_frame
Andrew M. Kuchlingba8b6bc2004-06-05 14:11:59 +00001462 else:
1463 lineno = frame.f_lineno
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001464 if not isframe(frame):
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00001465 raise TypeError('{!r} is not a frame or traceback object'.format(frame))
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001466
Neil Schemenauerf06f8532002-03-23 23:51:04 +00001467 filename = getsourcefile(frame) or getfile(frame)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001468 if context > 0:
Guido van Rossum54e54c62001-09-04 19:14:14 +00001469 start = lineno - 1 - context//2
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001470 try:
1471 lines, lnum = findsource(frame)
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02001472 except OSError:
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +00001473 lines = index = None
1474 else:
Raymond Hettingera0501712004-06-15 11:22:53 +00001475 start = max(0, min(start, len(lines) - context))
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001476 lines = lines[start:start+context]
Ka-Ping Yee59ade082001-03-01 03:55:35 +00001477 index = lineno - 1 - start
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001478 else:
1479 lines = index = None
1480
Christian Heimes25bb7832008-01-11 16:17:00 +00001481 return Traceback(filename, lineno, frame.f_code.co_name, lines, index)
Ka-Ping Yee59ade082001-03-01 03:55:35 +00001482
1483def getlineno(frame):
1484 """Get the line number from a frame object, allowing for optimization."""
Michael W. Hudsondd32a912002-08-15 14:59:02 +00001485 # FrameType.f_lineno is now a descriptor that grovels co_lnotab
1486 return frame.f_lineno
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001487
Antoine Pitroucdcafb72014-08-24 10:50:28 -04001488FrameInfo = namedtuple('FrameInfo', ('frame',) + Traceback._fields)
1489
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001490def getouterframes(frame, context=1):
1491 """Get a list of records for a frame and all higher (calling) frames.
1492
1493 Each record contains a frame object, filename, line number, function
1494 name, a list of lines of context, and index within the context."""
1495 framelist = []
1496 while frame:
Antoine Pitroucdcafb72014-08-24 10:50:28 -04001497 frameinfo = (frame,) + getframeinfo(frame, context)
1498 framelist.append(FrameInfo(*frameinfo))
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001499 frame = frame.f_back
1500 return framelist
1501
1502def getinnerframes(tb, context=1):
1503 """Get a list of records for a traceback's frame and all lower frames.
1504
1505 Each record contains a frame object, filename, line number, function
1506 name, a list of lines of context, and index within the context."""
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001507 framelist = []
1508 while tb:
Antoine Pitroucdcafb72014-08-24 10:50:28 -04001509 frameinfo = (tb.tb_frame,) + getframeinfo(tb, context)
1510 framelist.append(FrameInfo(*frameinfo))
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001511 tb = tb.tb_next
1512 return framelist
1513
Benjamin Peterson42ac4752010-08-09 13:05:35 +00001514def currentframe():
Benjamin Petersona3a3fc62010-08-09 15:49:56 +00001515 """Return the frame of the caller or None if this is not possible."""
Benjamin Peterson42ac4752010-08-09 13:05:35 +00001516 return sys._getframe(1) if hasattr(sys, "_getframe") else None
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001517
1518def stack(context=1):
1519 """Return a list of records for the stack above the caller's frame."""
Jeremy Hyltonab919022003-06-27 18:41:20 +00001520 return getouterframes(sys._getframe(1), context)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001521
1522def trace(context=1):
Tim Peters85ba6732001-02-28 08:26:44 +00001523 """Return a list of records for the stack below the current exception."""
Fred Draked451ec12002-04-26 02:29:55 +00001524 return getinnerframes(sys.exc_info()[2], context)
Michael Foord95fc51d2010-11-20 15:07:30 +00001525
1526
1527# ------------------------------------------------ static version of getattr
1528
1529_sentinel = object()
1530
Michael Foorde5162652010-11-20 16:40:44 +00001531def _static_getmro(klass):
1532 return type.__dict__['__mro__'].__get__(klass)
1533
Michael Foord95fc51d2010-11-20 15:07:30 +00001534def _check_instance(obj, attr):
1535 instance_dict = {}
1536 try:
1537 instance_dict = object.__getattribute__(obj, "__dict__")
1538 except AttributeError:
1539 pass
Michael Foorddcebe0f2011-03-15 19:20:44 -04001540 return dict.get(instance_dict, attr, _sentinel)
Michael Foord95fc51d2010-11-20 15:07:30 +00001541
1542
1543def _check_class(klass, attr):
Michael Foorde5162652010-11-20 16:40:44 +00001544 for entry in _static_getmro(klass):
Michael Foorda51623b2011-12-18 22:01:40 +00001545 if _shadowed_dict(type(entry)) is _sentinel:
Michael Foorddcebe0f2011-03-15 19:20:44 -04001546 try:
1547 return entry.__dict__[attr]
1548 except KeyError:
1549 pass
Michael Foord95fc51d2010-11-20 15:07:30 +00001550 return _sentinel
1551
Michael Foord35184ed2010-11-20 16:58:30 +00001552def _is_type(obj):
1553 try:
1554 _static_getmro(obj)
1555 except TypeError:
1556 return False
1557 return True
1558
Michael Foorddcebe0f2011-03-15 19:20:44 -04001559def _shadowed_dict(klass):
1560 dict_attr = type.__dict__["__dict__"]
1561 for entry in _static_getmro(klass):
1562 try:
1563 class_dict = dict_attr.__get__(entry)["__dict__"]
1564 except KeyError:
1565 pass
1566 else:
Srinivas Reddy Thatiparthy (శ్రీనివాస్ రెడ్డి తాటిపర్తి)feaefc72018-02-09 15:29:19 +05301567 if not (isinstance(class_dict, types.GetSetDescriptorType) and
Michael Foorddcebe0f2011-03-15 19:20:44 -04001568 class_dict.__name__ == "__dict__" and
1569 class_dict.__objclass__ is entry):
Michael Foorda51623b2011-12-18 22:01:40 +00001570 return class_dict
1571 return _sentinel
Michael Foord95fc51d2010-11-20 15:07:30 +00001572
1573def getattr_static(obj, attr, default=_sentinel):
1574 """Retrieve attributes without triggering dynamic lookup via the
1575 descriptor protocol, __getattr__ or __getattribute__.
1576
1577 Note: this function may not be able to retrieve all attributes
1578 that getattr can fetch (like dynamically created attributes)
1579 and may find attributes that getattr can't (like descriptors
1580 that raise AttributeError). It can also return descriptor objects
1581 instead of instance members in some cases. See the
1582 documentation for details.
1583 """
1584 instance_result = _sentinel
Michael Foord35184ed2010-11-20 16:58:30 +00001585 if not _is_type(obj):
Michael Foordcc7ebb82010-11-20 16:20:16 +00001586 klass = type(obj)
Michael Foorda51623b2011-12-18 22:01:40 +00001587 dict_attr = _shadowed_dict(klass)
1588 if (dict_attr is _sentinel or
Srinivas Reddy Thatiparthy (శ్రీనివాస్ రెడ్డి తాటిపర్తి)feaefc72018-02-09 15:29:19 +05301589 isinstance(dict_attr, types.MemberDescriptorType)):
Michael Foorddcebe0f2011-03-15 19:20:44 -04001590 instance_result = _check_instance(obj, attr)
Michael Foord95fc51d2010-11-20 15:07:30 +00001591 else:
1592 klass = obj
1593
1594 klass_result = _check_class(klass, attr)
1595
1596 if instance_result is not _sentinel and klass_result is not _sentinel:
1597 if (_check_class(type(klass_result), '__get__') is not _sentinel and
1598 _check_class(type(klass_result), '__set__') is not _sentinel):
1599 return klass_result
1600
1601 if instance_result is not _sentinel:
1602 return instance_result
1603 if klass_result is not _sentinel:
1604 return klass_result
1605
1606 if obj is klass:
1607 # for types we check the metaclass too
Michael Foorde5162652010-11-20 16:40:44 +00001608 for entry in _static_getmro(type(klass)):
Michael Foord3ba95f82011-12-22 01:13:37 +00001609 if _shadowed_dict(type(entry)) is _sentinel:
1610 try:
1611 return entry.__dict__[attr]
1612 except KeyError:
1613 pass
Michael Foord95fc51d2010-11-20 15:07:30 +00001614 if default is not _sentinel:
1615 return default
1616 raise AttributeError(attr)
Nick Coghlane0f04652010-11-21 03:44:04 +00001617
1618
Nick Coghlan04e2e3f2012-06-23 19:52:05 +10001619# ------------------------------------------------ generator introspection
1620
Nick Coghlan7921b9f2010-11-30 06:36:04 +00001621GEN_CREATED = 'GEN_CREATED'
1622GEN_RUNNING = 'GEN_RUNNING'
1623GEN_SUSPENDED = 'GEN_SUSPENDED'
1624GEN_CLOSED = 'GEN_CLOSED'
Nick Coghlane0f04652010-11-21 03:44:04 +00001625
1626def getgeneratorstate(generator):
1627 """Get current state of a generator-iterator.
1628
1629 Possible states are:
1630 GEN_CREATED: Waiting to start execution.
1631 GEN_RUNNING: Currently being executed by the interpreter.
1632 GEN_SUSPENDED: Currently suspended at a yield expression.
1633 GEN_CLOSED: Execution has completed.
1634 """
1635 if generator.gi_running:
1636 return GEN_RUNNING
1637 if generator.gi_frame is None:
1638 return GEN_CLOSED
1639 if generator.gi_frame.f_lasti == -1:
1640 return GEN_CREATED
1641 return GEN_SUSPENDED
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07001642
1643
Nick Coghlan04e2e3f2012-06-23 19:52:05 +10001644def getgeneratorlocals(generator):
1645 """
1646 Get the mapping of generator local variables to their current values.
1647
1648 A dict is returned, with the keys the local variable names and values the
1649 bound values."""
1650
1651 if not isgenerator(generator):
Serhiy Storchakaa4a30202017-11-28 22:54:42 +02001652 raise TypeError("{!r} is not a Python generator".format(generator))
Nick Coghlan04e2e3f2012-06-23 19:52:05 +10001653
1654 frame = getattr(generator, "gi_frame", None)
1655 if frame is not None:
1656 return generator.gi_frame.f_locals
1657 else:
1658 return {}
1659
Yury Selivanov5376ba92015-06-22 12:19:30 -04001660
1661# ------------------------------------------------ coroutine introspection
1662
1663CORO_CREATED = 'CORO_CREATED'
1664CORO_RUNNING = 'CORO_RUNNING'
1665CORO_SUSPENDED = 'CORO_SUSPENDED'
1666CORO_CLOSED = 'CORO_CLOSED'
1667
1668def getcoroutinestate(coroutine):
1669 """Get current state of a coroutine object.
1670
1671 Possible states are:
1672 CORO_CREATED: Waiting to start execution.
1673 CORO_RUNNING: Currently being executed by the interpreter.
1674 CORO_SUSPENDED: Currently suspended at an await expression.
1675 CORO_CLOSED: Execution has completed.
1676 """
1677 if coroutine.cr_running:
1678 return CORO_RUNNING
1679 if coroutine.cr_frame is None:
1680 return CORO_CLOSED
1681 if coroutine.cr_frame.f_lasti == -1:
1682 return CORO_CREATED
1683 return CORO_SUSPENDED
1684
1685
1686def getcoroutinelocals(coroutine):
1687 """
1688 Get the mapping of coroutine local variables to their current values.
1689
1690 A dict is returned, with the keys the local variable names and values the
1691 bound values."""
1692 frame = getattr(coroutine, "cr_frame", None)
1693 if frame is not None:
1694 return frame.f_locals
1695 else:
1696 return {}
1697
1698
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07001699###############################################################################
1700### Function Signature Object (PEP 362)
1701###############################################################################
1702
1703
1704_WrapperDescriptor = type(type.__call__)
1705_MethodWrapper = type(all.__call__)
Larry Hastings5c661892014-01-24 06:17:25 -08001706_ClassMethodWrapper = type(int.__dict__['from_bytes'])
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07001707
1708_NonUserDefinedCallables = (_WrapperDescriptor,
1709 _MethodWrapper,
Larry Hastings5c661892014-01-24 06:17:25 -08001710 _ClassMethodWrapper,
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07001711 types.BuiltinFunctionType)
1712
1713
Yury Selivanov421f0c72014-01-29 12:05:40 -05001714def _signature_get_user_defined_method(cls, method_name):
Yury Selivanov5a23bd02014-03-29 13:47:11 -04001715 """Private helper. Checks if ``cls`` has an attribute
1716 named ``method_name`` and returns it only if it is a
1717 pure python function.
1718 """
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07001719 try:
1720 meth = getattr(cls, method_name)
1721 except AttributeError:
1722 return
1723 else:
1724 if not isinstance(meth, _NonUserDefinedCallables):
1725 # Once '__signature__' will be added to 'C'-level
1726 # callables, this check won't be necessary
1727 return meth
1728
1729
Yury Selivanov62560fb2014-01-28 12:26:24 -05001730def _signature_get_partial(wrapped_sig, partial, extra_args=()):
Yury Selivanov5a23bd02014-03-29 13:47:11 -04001731 """Private helper to calculate how 'wrapped_sig' signature will
1732 look like after applying a 'functools.partial' object (or alike)
1733 on it.
1734 """
Yury Selivanov62560fb2014-01-28 12:26:24 -05001735
Yury Selivanov3f73ca22014-04-08 11:30:45 -04001736 old_params = wrapped_sig.parameters
1737 new_params = OrderedDict(old_params.items())
Yury Selivanovda5fe4f2014-01-27 17:28:37 -05001738
1739 partial_args = partial.args or ()
1740 partial_keywords = partial.keywords or {}
1741
1742 if extra_args:
1743 partial_args = extra_args + partial_args
1744
1745 try:
1746 ba = wrapped_sig.bind_partial(*partial_args, **partial_keywords)
1747 except TypeError as ex:
1748 msg = 'partial object {!r} has incorrect arguments'.format(partial)
1749 raise ValueError(msg) from ex
1750
Yury Selivanovda5fe4f2014-01-27 17:28:37 -05001751
Yury Selivanov3f73ca22014-04-08 11:30:45 -04001752 transform_to_kwonly = False
1753 for param_name, param in old_params.items():
1754 try:
1755 arg_value = ba.arguments[param_name]
1756 except KeyError:
1757 pass
1758 else:
1759 if param.kind is _POSITIONAL_ONLY:
1760 # If positional-only parameter is bound by partial,
1761 # it effectively disappears from the signature
1762 new_params.pop(param_name)
1763 continue
1764
1765 if param.kind is _POSITIONAL_OR_KEYWORD:
1766 if param_name in partial_keywords:
1767 # This means that this parameter, and all parameters
1768 # after it should be keyword-only (and var-positional
1769 # should be removed). Here's why. Consider the following
1770 # function:
1771 # foo(a, b, *args, c):
1772 # pass
1773 #
1774 # "partial(foo, a='spam')" will have the following
1775 # signature: "(*, a='spam', b, c)". Because attempting
1776 # to call that partial with "(10, 20)" arguments will
1777 # raise a TypeError, saying that "a" argument received
1778 # multiple values.
1779 transform_to_kwonly = True
1780 # Set the new default value
1781 new_params[param_name] = param.replace(default=arg_value)
1782 else:
1783 # was passed as a positional argument
1784 new_params.pop(param.name)
1785 continue
1786
1787 if param.kind is _KEYWORD_ONLY:
1788 # Set the new default value
1789 new_params[param_name] = param.replace(default=arg_value)
1790
1791 if transform_to_kwonly:
1792 assert param.kind is not _POSITIONAL_ONLY
1793
1794 if param.kind is _POSITIONAL_OR_KEYWORD:
1795 new_param = new_params[param_name].replace(kind=_KEYWORD_ONLY)
1796 new_params[param_name] = new_param
1797 new_params.move_to_end(param_name)
1798 elif param.kind in (_KEYWORD_ONLY, _VAR_KEYWORD):
1799 new_params.move_to_end(param_name)
1800 elif param.kind is _VAR_POSITIONAL:
1801 new_params.pop(param.name)
Yury Selivanovda5fe4f2014-01-27 17:28:37 -05001802
1803 return wrapped_sig.replace(parameters=new_params.values())
1804
1805
Yury Selivanov62560fb2014-01-28 12:26:24 -05001806def _signature_bound_method(sig):
Yury Selivanov5a23bd02014-03-29 13:47:11 -04001807 """Private helper to transform signatures for unbound
1808 functions to bound methods.
1809 """
Yury Selivanov62560fb2014-01-28 12:26:24 -05001810
1811 params = tuple(sig.parameters.values())
1812
1813 if not params or params[0].kind in (_VAR_KEYWORD, _KEYWORD_ONLY):
1814 raise ValueError('invalid method signature')
1815
1816 kind = params[0].kind
1817 if kind in (_POSITIONAL_OR_KEYWORD, _POSITIONAL_ONLY):
1818 # Drop first parameter:
1819 # '(p1, p2[, ...])' -> '(p2[, ...])'
1820 params = params[1:]
1821 else:
1822 if kind is not _VAR_POSITIONAL:
1823 # Unless we add a new parameter type we never
1824 # get here
1825 raise ValueError('invalid argument type')
1826 # It's a var-positional parameter.
1827 # Do nothing. '(*args[, ...])' -> '(*args[, ...])'
1828
1829 return sig.replace(parameters=params)
1830
1831
Yury Selivanovb77511d2014-01-29 10:46:14 -05001832def _signature_is_builtin(obj):
Yury Selivanov5a23bd02014-03-29 13:47:11 -04001833 """Private helper to test if `obj` is a callable that might
1834 support Argument Clinic's __text_signature__ protocol.
1835 """
Yury Selivanov1d241832014-02-02 12:51:20 -05001836 return (isbuiltin(obj) or
Yury Selivanovb77511d2014-01-29 10:46:14 -05001837 ismethoddescriptor(obj) or
Yury Selivanov1d241832014-02-02 12:51:20 -05001838 isinstance(obj, _NonUserDefinedCallables) or
Yury Selivanovb77511d2014-01-29 10:46:14 -05001839 # Can't test 'isinstance(type)' here, as it would
1840 # also be True for regular python classes
1841 obj in (type, object))
1842
1843
Yury Selivanov63da7c72014-01-31 14:48:37 -05001844def _signature_is_functionlike(obj):
Yury Selivanov5a23bd02014-03-29 13:47:11 -04001845 """Private helper to test if `obj` is a duck type of FunctionType.
1846 A good example of such objects are functions compiled with
1847 Cython, which have all attributes that a pure Python function
1848 would have, but have their code statically compiled.
1849 """
Yury Selivanov63da7c72014-01-31 14:48:37 -05001850
1851 if not callable(obj) or isclass(obj):
1852 # All function-like objects are obviously callables,
1853 # and not classes.
1854 return False
1855
1856 name = getattr(obj, '__name__', None)
1857 code = getattr(obj, '__code__', None)
1858 defaults = getattr(obj, '__defaults__', _void) # Important to use _void ...
1859 kwdefaults = getattr(obj, '__kwdefaults__', _void) # ... and not None here
1860 annotations = getattr(obj, '__annotations__', None)
1861
1862 return (isinstance(code, types.CodeType) and
1863 isinstance(name, str) and
1864 (defaults is None or isinstance(defaults, tuple)) and
1865 (kwdefaults is None or isinstance(kwdefaults, dict)) and
1866 isinstance(annotations, dict))
1867
1868
Yury Selivanovd82eddc2014-01-29 11:24:39 -05001869def _signature_get_bound_param(spec):
Yury Selivanov5a23bd02014-03-29 13:47:11 -04001870 """ Private helper to get first parameter name from a
1871 __text_signature__ of a builtin method, which should
1872 be in the following format: '($param1, ...)'.
1873 Assumptions are that the first argument won't have
1874 a default value or an annotation.
1875 """
Yury Selivanovd82eddc2014-01-29 11:24:39 -05001876
1877 assert spec.startswith('($')
1878
1879 pos = spec.find(',')
1880 if pos == -1:
1881 pos = spec.find(')')
1882
1883 cpos = spec.find(':')
1884 assert cpos == -1 or cpos > pos
1885
1886 cpos = spec.find('=')
1887 assert cpos == -1 or cpos > pos
1888
1889 return spec[2:pos]
1890
1891
Larry Hastings2623c8c2014-02-08 22:15:29 -08001892def _signature_strip_non_python_syntax(signature):
1893 """
Yury Selivanov5a23bd02014-03-29 13:47:11 -04001894 Private helper function. Takes a signature in Argument Clinic's
1895 extended signature format.
1896
Larry Hastings2623c8c2014-02-08 22:15:29 -08001897 Returns a tuple of three things:
1898 * that signature re-rendered in standard Python syntax,
1899 * the index of the "self" parameter (generally 0), or None if
1900 the function does not have a "self" parameter, and
1901 * the index of the last "positional only" parameter,
1902 or None if the signature has no positional-only parameters.
1903 """
1904
1905 if not signature:
1906 return signature, None, None
1907
1908 self_parameter = None
1909 last_positional_only = None
1910
1911 lines = [l.encode('ascii') for l in signature.split('\n')]
1912 generator = iter(lines).__next__
1913 token_stream = tokenize.tokenize(generator)
1914
1915 delayed_comma = False
1916 skip_next_comma = False
1917 text = []
1918 add = text.append
1919
1920 current_parameter = 0
1921 OP = token.OP
1922 ERRORTOKEN = token.ERRORTOKEN
1923
1924 # token stream always starts with ENCODING token, skip it
1925 t = next(token_stream)
1926 assert t.type == tokenize.ENCODING
1927
1928 for t in token_stream:
1929 type, string = t.type, t.string
1930
1931 if type == OP:
1932 if string == ',':
1933 if skip_next_comma:
1934 skip_next_comma = False
1935 else:
1936 assert not delayed_comma
1937 delayed_comma = True
1938 current_parameter += 1
1939 continue
1940
1941 if string == '/':
1942 assert not skip_next_comma
1943 assert last_positional_only is None
1944 skip_next_comma = True
1945 last_positional_only = current_parameter - 1
1946 continue
1947
1948 if (type == ERRORTOKEN) and (string == '$'):
1949 assert self_parameter is None
1950 self_parameter = current_parameter
1951 continue
1952
1953 if delayed_comma:
1954 delayed_comma = False
1955 if not ((type == OP) and (string == ')')):
1956 add(', ')
1957 add(string)
1958 if (string == ','):
1959 add(' ')
1960 clean_signature = ''.join(text)
1961 return clean_signature, self_parameter, last_positional_only
1962
1963
Yury Selivanov57d240e2014-02-19 16:27:23 -05001964def _signature_fromstr(cls, obj, s, skip_bound_arg=True):
Yury Selivanov5a23bd02014-03-29 13:47:11 -04001965 """Private helper to parse content of '__text_signature__'
1966 and return a Signature based on it.
1967 """
INADA Naoki37420de2018-01-27 10:10:06 +09001968 # Lazy import ast because it's relatively heavy and
1969 # it's not used for other than this function.
1970 import ast
Yury Selivanov5a23bd02014-03-29 13:47:11 -04001971
Yury Selivanov7d2bfed2014-02-03 02:46:07 -05001972 Parameter = cls._parameter_cls
1973
Larry Hastings2623c8c2014-02-08 22:15:29 -08001974 clean_signature, self_parameter, last_positional_only = \
1975 _signature_strip_non_python_syntax(s)
Yury Selivanov7d2bfed2014-02-03 02:46:07 -05001976
Larry Hastings2623c8c2014-02-08 22:15:29 -08001977 program = "def foo" + clean_signature + ": pass"
Yury Selivanov7d2bfed2014-02-03 02:46:07 -05001978
1979 try:
Larry Hastings2623c8c2014-02-08 22:15:29 -08001980 module = ast.parse(program)
Yury Selivanov7d2bfed2014-02-03 02:46:07 -05001981 except SyntaxError:
1982 module = None
1983
1984 if not isinstance(module, ast.Module):
1985 raise ValueError("{!r} builtin has invalid signature".format(obj))
1986
1987 f = module.body[0]
1988
1989 parameters = []
1990 empty = Parameter.empty
1991 invalid = object()
1992
1993 module = None
1994 module_dict = {}
1995 module_name = getattr(obj, '__module__', None)
1996 if module_name:
1997 module = sys.modules.get(module_name, None)
1998 if module:
1999 module_dict = module.__dict__
INADA Naoki6f85b822018-10-05 01:47:09 +09002000 sys_module_dict = sys.modules.copy()
Yury Selivanov7d2bfed2014-02-03 02:46:07 -05002001
2002 def parse_name(node):
2003 assert isinstance(node, ast.arg)
Srinivas Reddy Thatiparthy (శ్రీనివాస్ రెడ్డి తాటిపర్తి)feaefc72018-02-09 15:29:19 +05302004 if node.annotation is not None:
Yury Selivanov7d2bfed2014-02-03 02:46:07 -05002005 raise ValueError("Annotations are not currently supported")
2006 return node.arg
2007
2008 def wrap_value(s):
2009 try:
2010 value = eval(s, module_dict)
2011 except NameError:
2012 try:
2013 value = eval(s, sys_module_dict)
2014 except NameError:
2015 raise RuntimeError()
2016
Serhiy Storchaka3f228112018-09-27 17:42:37 +03002017 if isinstance(value, (str, int, float, bytes, bool, type(None))):
2018 return ast.Constant(value)
Yury Selivanov7d2bfed2014-02-03 02:46:07 -05002019 raise RuntimeError()
2020
2021 class RewriteSymbolics(ast.NodeTransformer):
2022 def visit_Attribute(self, node):
2023 a = []
2024 n = node
2025 while isinstance(n, ast.Attribute):
2026 a.append(n.attr)
2027 n = n.value
2028 if not isinstance(n, ast.Name):
2029 raise RuntimeError()
2030 a.append(n.id)
2031 value = ".".join(reversed(a))
2032 return wrap_value(value)
2033
2034 def visit_Name(self, node):
2035 if not isinstance(node.ctx, ast.Load):
2036 raise ValueError()
2037 return wrap_value(node.id)
2038
2039 def p(name_node, default_node, default=empty):
2040 name = parse_name(name_node)
2041 if name is invalid:
2042 return None
2043 if default_node and default_node is not _empty:
2044 try:
2045 default_node = RewriteSymbolics().visit(default_node)
2046 o = ast.literal_eval(default_node)
2047 except ValueError:
2048 o = invalid
2049 if o is invalid:
2050 return None
2051 default = o if o is not invalid else default
2052 parameters.append(Parameter(name, kind, default=default, annotation=empty))
2053
2054 # non-keyword-only parameters
2055 args = reversed(f.args.args)
2056 defaults = reversed(f.args.defaults)
2057 iter = itertools.zip_longest(args, defaults, fillvalue=None)
Larry Hastings2623c8c2014-02-08 22:15:29 -08002058 if last_positional_only is not None:
2059 kind = Parameter.POSITIONAL_ONLY
2060 else:
2061 kind = Parameter.POSITIONAL_OR_KEYWORD
2062 for i, (name, default) in enumerate(reversed(list(iter))):
Yury Selivanov7d2bfed2014-02-03 02:46:07 -05002063 p(name, default)
Larry Hastings2623c8c2014-02-08 22:15:29 -08002064 if i == last_positional_only:
2065 kind = Parameter.POSITIONAL_OR_KEYWORD
Yury Selivanov7d2bfed2014-02-03 02:46:07 -05002066
2067 # *args
2068 if f.args.vararg:
2069 kind = Parameter.VAR_POSITIONAL
2070 p(f.args.vararg, empty)
2071
2072 # keyword-only arguments
2073 kind = Parameter.KEYWORD_ONLY
2074 for name, default in zip(f.args.kwonlyargs, f.args.kw_defaults):
2075 p(name, default)
2076
2077 # **kwargs
2078 if f.args.kwarg:
2079 kind = Parameter.VAR_KEYWORD
2080 p(f.args.kwarg, empty)
2081
Larry Hastings2623c8c2014-02-08 22:15:29 -08002082 if self_parameter is not None:
Yury Selivanov8c185ee2014-02-21 01:32:42 -05002083 # Possibly strip the bound argument:
2084 # - We *always* strip first bound argument if
2085 # it is a module.
2086 # - We don't strip first bound argument if
2087 # skip_bound_arg is False.
Yury Selivanov7d2bfed2014-02-03 02:46:07 -05002088 assert parameters
Yury Selivanov8c185ee2014-02-21 01:32:42 -05002089 _self = getattr(obj, '__self__', None)
2090 self_isbound = _self is not None
2091 self_ismodule = ismodule(_self)
2092 if self_isbound and (self_ismodule or skip_bound_arg):
Yury Selivanov7d2bfed2014-02-03 02:46:07 -05002093 parameters.pop(0)
2094 else:
2095 # for builtins, self parameter is always positional-only!
2096 p = parameters[0].replace(kind=Parameter.POSITIONAL_ONLY)
2097 parameters[0] = p
2098
2099 return cls(parameters, return_annotation=cls.empty)
2100
2101
Yury Selivanov57d240e2014-02-19 16:27:23 -05002102def _signature_from_builtin(cls, func, skip_bound_arg=True):
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002103 """Private helper function to get signature for
2104 builtin callables.
2105 """
2106
Yury Selivanov57d240e2014-02-19 16:27:23 -05002107 if not _signature_is_builtin(func):
2108 raise TypeError("{!r} is not a Python builtin "
2109 "function".format(func))
2110
2111 s = getattr(func, "__text_signature__", None)
2112 if not s:
2113 raise ValueError("no signature found for builtin {!r}".format(func))
2114
2115 return _signature_fromstr(cls, func, s, skip_bound_arg)
2116
2117
Serhiy Storchakad53cf992019-05-06 22:40:27 +03002118def _signature_from_function(cls, func, skip_bound_arg=True):
Yury Selivanovcf45f022015-05-20 14:38:50 -04002119 """Private helper: constructs Signature for the given python function."""
2120
2121 is_duck_function = False
2122 if not isfunction(func):
2123 if _signature_is_functionlike(func):
2124 is_duck_function = True
2125 else:
2126 # If it's not a pure Python function, and not a duck type
2127 # of pure function:
2128 raise TypeError('{!r} is not a Python function'.format(func))
2129
Serhiy Storchakad53cf992019-05-06 22:40:27 +03002130 s = getattr(func, "__text_signature__", None)
2131 if s:
2132 return _signature_fromstr(cls, func, s, skip_bound_arg)
2133
Yury Selivanovcf45f022015-05-20 14:38:50 -04002134 Parameter = cls._parameter_cls
2135
2136 # Parameter information.
2137 func_code = func.__code__
2138 pos_count = func_code.co_argcount
2139 arg_names = func_code.co_varnames
Pablo Galindo8c77b8c2019-04-29 13:36:57 +01002140 posonly_count = func_code.co_posonlyargcount
2141 positional_count = posonly_count + pos_count
2142 positional_only = tuple(arg_names[:posonly_count])
2143 positional = tuple(arg_names[posonly_count:positional_count])
Yury Selivanovcf45f022015-05-20 14:38:50 -04002144 keyword_only_count = func_code.co_kwonlyargcount
Pablo Galindo8c77b8c2019-04-29 13:36:57 +01002145 keyword_only = arg_names[positional_count:(positional_count + keyword_only_count)]
Yury Selivanovcf45f022015-05-20 14:38:50 -04002146 annotations = func.__annotations__
2147 defaults = func.__defaults__
2148 kwdefaults = func.__kwdefaults__
2149
2150 if defaults:
2151 pos_default_count = len(defaults)
2152 else:
2153 pos_default_count = 0
2154
2155 parameters = []
2156
Pablo Galindo8c77b8c2019-04-29 13:36:57 +01002157 non_default_count = positional_count - pos_default_count
2158 all_positional = positional_only + positional
2159
2160 posonly_left = posonly_count
2161
Yury Selivanovcf45f022015-05-20 14:38:50 -04002162 # Non-keyword-only parameters w/o defaults.
Pablo Galindo8c77b8c2019-04-29 13:36:57 +01002163 for name in all_positional[:non_default_count]:
2164 kind = _POSITIONAL_ONLY if posonly_left else _POSITIONAL_OR_KEYWORD
Yury Selivanovcf45f022015-05-20 14:38:50 -04002165 annotation = annotations.get(name, _empty)
2166 parameters.append(Parameter(name, annotation=annotation,
Pablo Galindo8c77b8c2019-04-29 13:36:57 +01002167 kind=kind))
2168 if posonly_left:
2169 posonly_left -= 1
Yury Selivanovcf45f022015-05-20 14:38:50 -04002170
2171 # ... w/ defaults.
Pablo Galindo8c77b8c2019-04-29 13:36:57 +01002172 for offset, name in enumerate(all_positional[non_default_count:]):
2173 kind = _POSITIONAL_ONLY if posonly_left else _POSITIONAL_OR_KEYWORD
Yury Selivanovcf45f022015-05-20 14:38:50 -04002174 annotation = annotations.get(name, _empty)
2175 parameters.append(Parameter(name, annotation=annotation,
Pablo Galindo8c77b8c2019-04-29 13:36:57 +01002176 kind=kind,
Yury Selivanovcf45f022015-05-20 14:38:50 -04002177 default=defaults[offset]))
Pablo Galindo8c77b8c2019-04-29 13:36:57 +01002178 if posonly_left:
2179 posonly_left -= 1
Yury Selivanovcf45f022015-05-20 14:38:50 -04002180
2181 # *args
2182 if func_code.co_flags & CO_VARARGS:
Pablo Galindo8c77b8c2019-04-29 13:36:57 +01002183 name = arg_names[positional_count + keyword_only_count]
Yury Selivanovcf45f022015-05-20 14:38:50 -04002184 annotation = annotations.get(name, _empty)
2185 parameters.append(Parameter(name, annotation=annotation,
2186 kind=_VAR_POSITIONAL))
2187
2188 # Keyword-only parameters.
2189 for name in keyword_only:
2190 default = _empty
2191 if kwdefaults is not None:
2192 default = kwdefaults.get(name, _empty)
2193
2194 annotation = annotations.get(name, _empty)
2195 parameters.append(Parameter(name, annotation=annotation,
2196 kind=_KEYWORD_ONLY,
2197 default=default))
2198 # **kwargs
2199 if func_code.co_flags & CO_VARKEYWORDS:
Pablo Galindo8c77b8c2019-04-29 13:36:57 +01002200 index = positional_count + keyword_only_count
Yury Selivanovcf45f022015-05-20 14:38:50 -04002201 if func_code.co_flags & CO_VARARGS:
2202 index += 1
2203
2204 name = arg_names[index]
2205 annotation = annotations.get(name, _empty)
2206 parameters.append(Parameter(name, annotation=annotation,
2207 kind=_VAR_KEYWORD))
2208
2209 # Is 'func' is a pure Python function - don't validate the
2210 # parameters list (for correct order and defaults), it should be OK.
2211 return cls(parameters,
2212 return_annotation=annotations.get('return', _empty),
2213 __validate_parameters__=is_duck_function)
2214
2215
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002216def _signature_from_callable(obj, *,
2217 follow_wrapper_chains=True,
2218 skip_bound_arg=True,
2219 sigcls):
2220
2221 """Private helper function to get signature for arbitrary
2222 callable objects.
2223 """
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002224
2225 if not callable(obj):
2226 raise TypeError('{!r} is not a callable object'.format(obj))
2227
2228 if isinstance(obj, types.MethodType):
2229 # In this case we skip the first parameter of the underlying
2230 # function (usually `self` or `cls`).
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002231 sig = _signature_from_callable(
Yury Selivanovda396452014-03-27 12:09:24 -04002232 obj.__func__,
2233 follow_wrapper_chains=follow_wrapper_chains,
2234 skip_bound_arg=skip_bound_arg,
2235 sigcls=sigcls)
2236
Yury Selivanov57d240e2014-02-19 16:27:23 -05002237 if skip_bound_arg:
2238 return _signature_bound_method(sig)
2239 else:
2240 return sig
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002241
Nick Coghlane8c45d62013-07-28 20:00:01 +10002242 # Was this function wrapped by a decorator?
Yury Selivanov57d240e2014-02-19 16:27:23 -05002243 if follow_wrapper_chains:
2244 obj = unwrap(obj, stop=(lambda f: hasattr(f, "__signature__")))
Yury Selivanov46c759d2015-05-27 21:56:53 -04002245 if isinstance(obj, types.MethodType):
2246 # If the unwrapped object is a *method*, we might want to
2247 # skip its first parameter (self).
2248 # See test_signature_wrapped_bound_method for details.
Yury Selivanov507cd3c2015-05-27 21:59:03 -04002249 return _signature_from_callable(
Yury Selivanov46c759d2015-05-27 21:56:53 -04002250 obj,
2251 follow_wrapper_chains=follow_wrapper_chains,
Yury Selivanov507cd3c2015-05-27 21:59:03 -04002252 skip_bound_arg=skip_bound_arg,
2253 sigcls=sigcls)
Nick Coghlane8c45d62013-07-28 20:00:01 +10002254
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002255 try:
2256 sig = obj.__signature__
2257 except AttributeError:
2258 pass
2259 else:
2260 if sig is not None:
Yury Selivanov42407ab2014-06-23 10:23:50 -07002261 if not isinstance(sig, Signature):
2262 raise TypeError(
2263 'unexpected object {!r} in __signature__ '
2264 'attribute'.format(sig))
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002265 return sig
2266
Yury Selivanovda5fe4f2014-01-27 17:28:37 -05002267 try:
2268 partialmethod = obj._partialmethod
2269 except AttributeError:
2270 pass
2271 else:
Yury Selivanov0486f812014-01-29 12:18:59 -05002272 if isinstance(partialmethod, functools.partialmethod):
2273 # Unbound partialmethod (see functools.partialmethod)
2274 # This means, that we need to calculate the signature
2275 # as if it's a regular partial object, but taking into
2276 # account that the first positional argument
2277 # (usually `self`, or `cls`) will not be passed
2278 # automatically (as for boundmethods)
Yury Selivanovda5fe4f2014-01-27 17:28:37 -05002279
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002280 wrapped_sig = _signature_from_callable(
Yury Selivanovda396452014-03-27 12:09:24 -04002281 partialmethod.func,
2282 follow_wrapper_chains=follow_wrapper_chains,
2283 skip_bound_arg=skip_bound_arg,
2284 sigcls=sigcls)
2285
Yury Selivanov0486f812014-01-29 12:18:59 -05002286 sig = _signature_get_partial(wrapped_sig, partialmethod, (None,))
Yury Selivanov0486f812014-01-29 12:18:59 -05002287 first_wrapped_param = tuple(wrapped_sig.parameters.values())[0]
Dong-hee Na378d7062017-05-18 04:00:51 +09002288 if first_wrapped_param.kind is Parameter.VAR_POSITIONAL:
2289 # First argument of the wrapped callable is `*args`, as in
2290 # `partialmethod(lambda *args)`.
2291 return sig
2292 else:
2293 sig_params = tuple(sig.parameters.values())
Yury Selivanov8a387212018-03-06 12:59:45 -05002294 assert (not sig_params or
2295 first_wrapped_param is not sig_params[0])
Dong-hee Na378d7062017-05-18 04:00:51 +09002296 new_params = (first_wrapped_param,) + sig_params
2297 return sig.replace(parameters=new_params)
Yury Selivanovda5fe4f2014-01-27 17:28:37 -05002298
Yury Selivanov63da7c72014-01-31 14:48:37 -05002299 if isfunction(obj) or _signature_is_functionlike(obj):
2300 # If it's a pure Python function, or an object that is duck type
2301 # of a Python function (Cython functions, for instance), then:
Serhiy Storchakad53cf992019-05-06 22:40:27 +03002302 return _signature_from_function(sigcls, obj,
2303 skip_bound_arg=skip_bound_arg)
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002304
Yury Selivanova773de02014-02-21 18:30:53 -05002305 if _signature_is_builtin(obj):
Yury Selivanovda396452014-03-27 12:09:24 -04002306 return _signature_from_builtin(sigcls, obj,
Yury Selivanova773de02014-02-21 18:30:53 -05002307 skip_bound_arg=skip_bound_arg)
2308
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002309 if isinstance(obj, functools.partial):
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002310 wrapped_sig = _signature_from_callable(
Yury Selivanovda396452014-03-27 12:09:24 -04002311 obj.func,
2312 follow_wrapper_chains=follow_wrapper_chains,
2313 skip_bound_arg=skip_bound_arg,
2314 sigcls=sigcls)
Yury Selivanov62560fb2014-01-28 12:26:24 -05002315 return _signature_get_partial(wrapped_sig, obj)
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002316
2317 sig = None
2318 if isinstance(obj, type):
2319 # obj is a class or a metaclass
2320
2321 # First, let's see if it has an overloaded __call__ defined
2322 # in its metaclass
Yury Selivanov421f0c72014-01-29 12:05:40 -05002323 call = _signature_get_user_defined_method(type(obj), '__call__')
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002324 if call is not None:
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002325 sig = _signature_from_callable(
Yury Selivanovda396452014-03-27 12:09:24 -04002326 call,
2327 follow_wrapper_chains=follow_wrapper_chains,
2328 skip_bound_arg=skip_bound_arg,
2329 sigcls=sigcls)
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002330 else:
2331 # Now we check if the 'obj' class has a '__new__' method
Yury Selivanov421f0c72014-01-29 12:05:40 -05002332 new = _signature_get_user_defined_method(obj, '__new__')
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002333 if new is not None:
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002334 sig = _signature_from_callable(
Yury Selivanovda396452014-03-27 12:09:24 -04002335 new,
2336 follow_wrapper_chains=follow_wrapper_chains,
2337 skip_bound_arg=skip_bound_arg,
2338 sigcls=sigcls)
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002339 else:
2340 # Finally, we should have at least __init__ implemented
Yury Selivanov421f0c72014-01-29 12:05:40 -05002341 init = _signature_get_user_defined_method(obj, '__init__')
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002342 if init is not None:
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002343 sig = _signature_from_callable(
Yury Selivanovda396452014-03-27 12:09:24 -04002344 init,
2345 follow_wrapper_chains=follow_wrapper_chains,
2346 skip_bound_arg=skip_bound_arg,
2347 sigcls=sigcls)
Yury Selivanove7dcc5e2014-01-27 19:29:45 -05002348
2349 if sig is None:
Yury Selivanov7d2bfed2014-02-03 02:46:07 -05002350 # At this point we know, that `obj` is a class, with no user-
2351 # defined '__init__', '__new__', or class-level '__call__'
2352
Larry Hastings2623c8c2014-02-08 22:15:29 -08002353 for base in obj.__mro__[:-1]:
Yury Selivanov7d2bfed2014-02-03 02:46:07 -05002354 # Since '__text_signature__' is implemented as a
2355 # descriptor that extracts text signature from the
2356 # class docstring, if 'obj' is derived from a builtin
2357 # class, its own '__text_signature__' may be 'None'.
Larry Hastings2623c8c2014-02-08 22:15:29 -08002358 # Therefore, we go through the MRO (except the last
2359 # class in there, which is 'object') to find the first
Yury Selivanov7d2bfed2014-02-03 02:46:07 -05002360 # class with non-empty text signature.
2361 try:
2362 text_sig = base.__text_signature__
2363 except AttributeError:
2364 pass
2365 else:
2366 if text_sig:
2367 # If 'obj' class has a __text_signature__ attribute:
2368 # return a signature based on it
Yury Selivanovda396452014-03-27 12:09:24 -04002369 return _signature_fromstr(sigcls, obj, text_sig)
Yury Selivanov7d2bfed2014-02-03 02:46:07 -05002370
2371 # No '__text_signature__' was found for the 'obj' class.
2372 # Last option is to check if its '__init__' is
2373 # object.__init__ or type.__init__.
Larry Hastings2623c8c2014-02-08 22:15:29 -08002374 if type not in obj.__mro__:
Yury Selivanove7dcc5e2014-01-27 19:29:45 -05002375 # We have a class (not metaclass), but no user-defined
2376 # __init__ or __new__ for it
Yury Selivanovbf304fc2015-05-30 17:08:36 -04002377 if (obj.__init__ is object.__init__ and
2378 obj.__new__ is object.__new__):
Yury Selivanov7d2bfed2014-02-03 02:46:07 -05002379 # Return a signature of 'object' builtin.
2380 return signature(object)
Yury Selivanovbf304fc2015-05-30 17:08:36 -04002381 else:
2382 raise ValueError(
2383 'no signature found for builtin type {!r}'.format(obj))
Yury Selivanove7dcc5e2014-01-27 19:29:45 -05002384
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002385 elif not isinstance(obj, _NonUserDefinedCallables):
2386 # An object with __call__
2387 # We also check that the 'obj' is not an instance of
2388 # _WrapperDescriptor or _MethodWrapper to avoid
2389 # infinite recursion (and even potential segfault)
Yury Selivanov421f0c72014-01-29 12:05:40 -05002390 call = _signature_get_user_defined_method(type(obj), '__call__')
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002391 if call is not None:
Larry Hastings2623c8c2014-02-08 22:15:29 -08002392 try:
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002393 sig = _signature_from_callable(
Yury Selivanovda396452014-03-27 12:09:24 -04002394 call,
2395 follow_wrapper_chains=follow_wrapper_chains,
2396 skip_bound_arg=skip_bound_arg,
2397 sigcls=sigcls)
Larry Hastings2623c8c2014-02-08 22:15:29 -08002398 except ValueError as ex:
2399 msg = 'no signature found for {!r}'.format(obj)
2400 raise ValueError(msg) from ex
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002401
2402 if sig is not None:
2403 # For classes and objects we skip the first parameter of their
2404 # __call__, __new__, or __init__ methods
Yury Selivanov57d240e2014-02-19 16:27:23 -05002405 if skip_bound_arg:
2406 return _signature_bound_method(sig)
2407 else:
2408 return sig
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002409
2410 if isinstance(obj, types.BuiltinFunctionType):
2411 # Raise a nicer error message for builtins
2412 msg = 'no signature found for builtin function {!r}'.format(obj)
2413 raise ValueError(msg)
2414
2415 raise ValueError('callable {!r} is not supported by signature'.format(obj))
2416
2417
2418class _void:
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002419 """A private marker - used in Parameter & Signature."""
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002420
2421
2422class _empty:
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002423 """Marker object for Signature.empty and Parameter.empty."""
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002424
2425
Yury Selivanov21e83a52014-03-27 11:23:13 -04002426class _ParameterKind(enum.IntEnum):
2427 POSITIONAL_ONLY = 0
2428 POSITIONAL_OR_KEYWORD = 1
2429 VAR_POSITIONAL = 2
2430 KEYWORD_ONLY = 3
2431 VAR_KEYWORD = 4
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002432
2433 def __str__(self):
Yury Selivanov21e83a52014-03-27 11:23:13 -04002434 return self._name_
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002435
Dong-hee Na4aa30062018-06-08 12:46:31 +09002436 @property
2437 def description(self):
2438 return _PARAM_NAME_MAPPING[self]
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002439
Yury Selivanov21e83a52014-03-27 11:23:13 -04002440_POSITIONAL_ONLY = _ParameterKind.POSITIONAL_ONLY
2441_POSITIONAL_OR_KEYWORD = _ParameterKind.POSITIONAL_OR_KEYWORD
2442_VAR_POSITIONAL = _ParameterKind.VAR_POSITIONAL
2443_KEYWORD_ONLY = _ParameterKind.KEYWORD_ONLY
2444_VAR_KEYWORD = _ParameterKind.VAR_KEYWORD
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002445
Dong-hee Naa9cab432018-05-30 00:04:08 +09002446_PARAM_NAME_MAPPING = {
2447 _POSITIONAL_ONLY: 'positional-only',
2448 _POSITIONAL_OR_KEYWORD: 'positional or keyword',
2449 _VAR_POSITIONAL: 'variadic positional',
2450 _KEYWORD_ONLY: 'keyword-only',
2451 _VAR_KEYWORD: 'variadic keyword'
2452}
2453
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002454
2455class Parameter:
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002456 """Represents a parameter in a function signature.
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002457
2458 Has the following public attributes:
2459
2460 * name : str
2461 The name of the parameter as a string.
2462 * default : object
2463 The default value for the parameter if specified. If the
Yury Selivanov8757ead2014-01-28 16:39:25 -05002464 parameter has no default value, this attribute is set to
2465 `Parameter.empty`.
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002466 * annotation
2467 The annotation for the parameter if specified. If the
Yury Selivanov8757ead2014-01-28 16:39:25 -05002468 parameter has no annotation, this attribute is set to
2469 `Parameter.empty`.
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002470 * kind : str
2471 Describes how argument values are bound to the parameter.
2472 Possible values: `Parameter.POSITIONAL_ONLY`,
2473 `Parameter.POSITIONAL_OR_KEYWORD`, `Parameter.VAR_POSITIONAL`,
2474 `Parameter.KEYWORD_ONLY`, `Parameter.VAR_KEYWORD`.
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002475 """
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002476
Yury Selivanov3f73ca22014-04-08 11:30:45 -04002477 __slots__ = ('_name', '_kind', '_default', '_annotation')
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002478
2479 POSITIONAL_ONLY = _POSITIONAL_ONLY
2480 POSITIONAL_OR_KEYWORD = _POSITIONAL_OR_KEYWORD
2481 VAR_POSITIONAL = _VAR_POSITIONAL
2482 KEYWORD_ONLY = _KEYWORD_ONLY
2483 VAR_KEYWORD = _VAR_KEYWORD
2484
2485 empty = _empty
2486
Yury Selivanov3f73ca22014-04-08 11:30:45 -04002487 def __init__(self, name, kind, *, default=_empty, annotation=_empty):
Dong-hee Naa9cab432018-05-30 00:04:08 +09002488 try:
2489 self._kind = _ParameterKind(kind)
2490 except ValueError:
2491 raise ValueError(f'value {kind!r} is not a valid Parameter.kind')
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002492 if default is not _empty:
Dong-hee Naa9cab432018-05-30 00:04:08 +09002493 if self._kind in (_VAR_POSITIONAL, _VAR_KEYWORD):
2494 msg = '{} parameters cannot have default values'
Dong-hee Na4aa30062018-06-08 12:46:31 +09002495 msg = msg.format(self._kind.description)
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002496 raise ValueError(msg)
2497 self._default = default
2498 self._annotation = annotation
2499
Yury Selivanov2393dca2014-01-27 15:07:58 -05002500 if name is _empty:
2501 raise ValueError('name is a required attribute for Parameter')
2502
2503 if not isinstance(name, str):
Dong-hee Naa9cab432018-05-30 00:04:08 +09002504 msg = 'name must be a str, not a {}'.format(type(name).__name__)
2505 raise TypeError(msg)
Yury Selivanov2393dca2014-01-27 15:07:58 -05002506
Nick Coghlanb4b966e2016-06-04 14:40:03 -07002507 if name[0] == '.' and name[1:].isdigit():
2508 # These are implicit arguments generated by comprehensions. In
2509 # order to provide a friendlier interface to users, we recast
2510 # their name as "implicitN" and treat them as positional-only.
2511 # See issue 19611.
Dong-hee Naa9cab432018-05-30 00:04:08 +09002512 if self._kind != _POSITIONAL_OR_KEYWORD:
2513 msg = (
2514 'implicit arguments must be passed as '
2515 'positional or keyword arguments, not {}'
Nick Coghlanb4b966e2016-06-04 14:40:03 -07002516 )
Dong-hee Na4aa30062018-06-08 12:46:31 +09002517 msg = msg.format(self._kind.description)
Dong-hee Naa9cab432018-05-30 00:04:08 +09002518 raise ValueError(msg)
Nick Coghlanb4b966e2016-06-04 14:40:03 -07002519 self._kind = _POSITIONAL_ONLY
2520 name = 'implicit{}'.format(name[1:])
2521
Yury Selivanov2393dca2014-01-27 15:07:58 -05002522 if not name.isidentifier():
2523 raise ValueError('{!r} is not a valid parameter name'.format(name))
2524
2525 self._name = name
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002526
Yury Selivanova5d63dd2014-03-27 11:31:43 -04002527 def __reduce__(self):
2528 return (type(self),
2529 (self._name, self._kind),
Yury Selivanov3f73ca22014-04-08 11:30:45 -04002530 {'_default': self._default,
Yury Selivanova5d63dd2014-03-27 11:31:43 -04002531 '_annotation': self._annotation})
2532
2533 def __setstate__(self, state):
Yury Selivanova5d63dd2014-03-27 11:31:43 -04002534 self._default = state['_default']
2535 self._annotation = state['_annotation']
2536
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002537 @property
2538 def name(self):
2539 return self._name
2540
2541 @property
2542 def default(self):
2543 return self._default
2544
2545 @property
2546 def annotation(self):
2547 return self._annotation
2548
2549 @property
2550 def kind(self):
2551 return self._kind
2552
Yury Selivanov3f73ca22014-04-08 11:30:45 -04002553 def replace(self, *, name=_void, kind=_void,
2554 annotation=_void, default=_void):
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002555 """Creates a customized copy of the Parameter."""
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002556
2557 if name is _void:
2558 name = self._name
2559
2560 if kind is _void:
2561 kind = self._kind
2562
2563 if annotation is _void:
2564 annotation = self._annotation
2565
2566 if default is _void:
2567 default = self._default
2568
Yury Selivanov3f73ca22014-04-08 11:30:45 -04002569 return type(self)(name, kind, default=default, annotation=annotation)
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002570
2571 def __str__(self):
2572 kind = self.kind
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002573 formatted = self._name
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002574
2575 # Add annotation and default value
2576 if self._annotation is not _empty:
Dong-hee Na762b9572017-11-16 03:30:59 +09002577 formatted = '{}: {}'.format(formatted,
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002578 formatannotation(self._annotation))
2579
2580 if self._default is not _empty:
Dong-hee Na762b9572017-11-16 03:30:59 +09002581 if self._annotation is not _empty:
2582 formatted = '{} = {}'.format(formatted, repr(self._default))
2583 else:
2584 formatted = '{}={}'.format(formatted, repr(self._default))
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002585
2586 if kind == _VAR_POSITIONAL:
2587 formatted = '*' + formatted
2588 elif kind == _VAR_KEYWORD:
2589 formatted = '**' + formatted
2590
2591 return formatted
2592
2593 def __repr__(self):
Yury Selivanovf229bc52015-05-15 12:53:56 -04002594 return '<{} "{}">'.format(self.__class__.__name__, self)
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002595
Yury Selivanov67ae50e2014-04-08 11:46:50 -04002596 def __hash__(self):
Yury Selivanov08d4a4f2014-09-12 15:48:02 -04002597 return hash((self.name, self.kind, self.annotation, self.default))
Yury Selivanov67ae50e2014-04-08 11:46:50 -04002598
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002599 def __eq__(self, other):
Serhiy Storchaka2489bd52015-07-18 23:20:50 +03002600 if self is other:
2601 return True
Serhiy Storchaka3018cc42015-07-18 23:19:05 +03002602 if not isinstance(other, Parameter):
2603 return NotImplemented
2604 return (self._name == other._name and
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002605 self._kind == other._kind and
2606 self._default == other._default and
2607 self._annotation == other._annotation)
2608
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002609
2610class BoundArguments:
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002611 """Result of `Signature.bind` call. Holds the mapping of arguments
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002612 to the function's parameters.
2613
2614 Has the following public attributes:
2615
2616 * arguments : OrderedDict
2617 An ordered mutable mapping of parameters' names to arguments' values.
2618 Does not contain arguments' default values.
2619 * signature : Signature
2620 The Signature object that created this instance.
2621 * args : tuple
2622 Tuple of positional arguments values.
2623 * kwargs : dict
2624 Dict of keyword arguments values.
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002625 """
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002626
Yury Selivanov6abe0322015-05-13 17:18:41 -04002627 __slots__ = ('arguments', '_signature', '__weakref__')
2628
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002629 def __init__(self, signature, arguments):
2630 self.arguments = arguments
2631 self._signature = signature
2632
2633 @property
2634 def signature(self):
2635 return self._signature
2636
2637 @property
2638 def args(self):
2639 args = []
2640 for param_name, param in self._signature.parameters.items():
Yury Selivanov3f73ca22014-04-08 11:30:45 -04002641 if param.kind in (_VAR_KEYWORD, _KEYWORD_ONLY):
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002642 break
2643
2644 try:
2645 arg = self.arguments[param_name]
2646 except KeyError:
2647 # We're done here. Other arguments
2648 # will be mapped in 'BoundArguments.kwargs'
2649 break
2650 else:
2651 if param.kind == _VAR_POSITIONAL:
2652 # *args
2653 args.extend(arg)
2654 else:
2655 # plain argument
2656 args.append(arg)
2657
2658 return tuple(args)
2659
2660 @property
2661 def kwargs(self):
2662 kwargs = {}
2663 kwargs_started = False
2664 for param_name, param in self._signature.parameters.items():
2665 if not kwargs_started:
Yury Selivanov3f73ca22014-04-08 11:30:45 -04002666 if param.kind in (_VAR_KEYWORD, _KEYWORD_ONLY):
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002667 kwargs_started = True
2668 else:
2669 if param_name not in self.arguments:
2670 kwargs_started = True
2671 continue
2672
2673 if not kwargs_started:
2674 continue
2675
2676 try:
2677 arg = self.arguments[param_name]
2678 except KeyError:
2679 pass
2680 else:
2681 if param.kind == _VAR_KEYWORD:
2682 # **kwargs
2683 kwargs.update(arg)
2684 else:
2685 # plain keyword argument
2686 kwargs[param_name] = arg
2687
2688 return kwargs
2689
Yury Selivanovb907a512015-05-16 13:45:09 -04002690 def apply_defaults(self):
2691 """Set default values for missing arguments.
2692
2693 For variable-positional arguments (*args) the default is an
2694 empty tuple.
2695
2696 For variable-keyword arguments (**kwargs) the default is an
2697 empty dict.
2698 """
2699 arguments = self.arguments
Yury Selivanovb907a512015-05-16 13:45:09 -04002700 new_arguments = []
2701 for name, param in self._signature.parameters.items():
2702 try:
2703 new_arguments.append((name, arguments[name]))
2704 except KeyError:
2705 if param.default is not _empty:
2706 val = param.default
2707 elif param.kind is _VAR_POSITIONAL:
2708 val = ()
2709 elif param.kind is _VAR_KEYWORD:
2710 val = {}
2711 else:
2712 # This BoundArguments was likely produced by
2713 # Signature.bind_partial().
2714 continue
2715 new_arguments.append((name, val))
2716 self.arguments = OrderedDict(new_arguments)
2717
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002718 def __eq__(self, other):
Serhiy Storchaka2489bd52015-07-18 23:20:50 +03002719 if self is other:
2720 return True
Serhiy Storchaka3018cc42015-07-18 23:19:05 +03002721 if not isinstance(other, BoundArguments):
2722 return NotImplemented
2723 return (self.signature == other.signature and
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002724 self.arguments == other.arguments)
2725
Yury Selivanov6abe0322015-05-13 17:18:41 -04002726 def __setstate__(self, state):
2727 self._signature = state['_signature']
2728 self.arguments = state['arguments']
2729
2730 def __getstate__(self):
2731 return {'_signature': self._signature, 'arguments': self.arguments}
2732
Yury Selivanov3f6538f2015-05-14 18:47:17 -04002733 def __repr__(self):
2734 args = []
2735 for arg, value in self.arguments.items():
2736 args.append('{}={!r}'.format(arg, value))
Yury Selivanovf229bc52015-05-15 12:53:56 -04002737 return '<{} ({})>'.format(self.__class__.__name__, ', '.join(args))
Yury Selivanov3f6538f2015-05-14 18:47:17 -04002738
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002739
2740class Signature:
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002741 """A Signature object represents the overall signature of a function.
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002742 It stores a Parameter object for each parameter accepted by the
2743 function, as well as information specific to the function itself.
2744
2745 A Signature object has the following public attributes and methods:
2746
2747 * parameters : OrderedDict
2748 An ordered mapping of parameters' names to the corresponding
2749 Parameter objects (keyword-only arguments are in the same order
2750 as listed in `code.co_varnames`).
2751 * return_annotation : object
2752 The annotation for the return type of the function if specified.
2753 If the function has no annotation for its return type, this
Yury Selivanov8757ead2014-01-28 16:39:25 -05002754 attribute is set to `Signature.empty`.
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002755 * bind(*args, **kwargs) -> BoundArguments
2756 Creates a mapping from positional and keyword arguments to
2757 parameters.
2758 * bind_partial(*args, **kwargs) -> BoundArguments
2759 Creates a partial mapping from positional and keyword arguments
2760 to parameters (simulating 'functools.partial' behavior.)
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002761 """
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002762
2763 __slots__ = ('_return_annotation', '_parameters')
2764
2765 _parameter_cls = Parameter
2766 _bound_arguments_cls = BoundArguments
2767
2768 empty = _empty
2769
2770 def __init__(self, parameters=None, *, return_annotation=_empty,
2771 __validate_parameters__=True):
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002772 """Constructs Signature from the given list of Parameter
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002773 objects and 'return_annotation'. All arguments are optional.
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002774 """
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002775
2776 if parameters is None:
2777 params = OrderedDict()
2778 else:
2779 if __validate_parameters__:
2780 params = OrderedDict()
2781 top_kind = _POSITIONAL_ONLY
Yury Selivanov07a9e452014-01-29 10:58:16 -05002782 kind_defaults = False
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002783
2784 for idx, param in enumerate(parameters):
2785 kind = param.kind
Yury Selivanov2393dca2014-01-27 15:07:58 -05002786 name = param.name
2787
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002788 if kind < top_kind:
Dong-hee Naa9cab432018-05-30 00:04:08 +09002789 msg = (
2790 'wrong parameter order: {} parameter before {} '
2791 'parameter'
2792 )
Dong-hee Na4aa30062018-06-08 12:46:31 +09002793 msg = msg.format(top_kind.description,
2794 kind.description)
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002795 raise ValueError(msg)
Yury Selivanov07a9e452014-01-29 10:58:16 -05002796 elif kind > top_kind:
2797 kind_defaults = False
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002798 top_kind = kind
2799
Yury Selivanov3f73ca22014-04-08 11:30:45 -04002800 if kind in (_POSITIONAL_ONLY, _POSITIONAL_OR_KEYWORD):
Yury Selivanov07a9e452014-01-29 10:58:16 -05002801 if param.default is _empty:
2802 if kind_defaults:
2803 # No default for this parameter, but the
2804 # previous parameter of the same kind had
2805 # a default
2806 msg = 'non-default argument follows default ' \
2807 'argument'
2808 raise ValueError(msg)
2809 else:
2810 # There is a default for this parameter.
2811 kind_defaults = True
2812
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002813 if name in params:
2814 msg = 'duplicate parameter name: {!r}'.format(name)
2815 raise ValueError(msg)
Yury Selivanov2393dca2014-01-27 15:07:58 -05002816
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002817 params[name] = param
2818 else:
2819 params = OrderedDict(((param.name, param)
2820 for param in parameters))
2821
2822 self._parameters = types.MappingProxyType(params)
2823 self._return_annotation = return_annotation
2824
2825 @classmethod
2826 def from_function(cls, func):
Matthias Bussonnierded87d82018-10-19 16:40:45 -07002827 """Constructs Signature for the given python function.
Yury Selivanov57c74fc2015-05-20 23:07:02 -04002828
Matthias Bussonnierded87d82018-10-19 16:40:45 -07002829 Deprecated since Python 3.5, use `Signature.from_callable()`.
2830 """
2831
2832 warnings.warn("inspect.Signature.from_function() is deprecated since "
2833 "Python 3.5, use Signature.from_callable()",
Berker Peksagb5601582015-05-21 23:40:54 +03002834 DeprecationWarning, stacklevel=2)
Yury Selivanovcf45f022015-05-20 14:38:50 -04002835 return _signature_from_function(cls, func)
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002836
Larry Hastings44e2eaa2013-11-23 15:37:55 -08002837 @classmethod
2838 def from_builtin(cls, func):
Matthias Bussonnierded87d82018-10-19 16:40:45 -07002839 """Constructs Signature for the given builtin function.
Yury Selivanov57c74fc2015-05-20 23:07:02 -04002840
Matthias Bussonnierded87d82018-10-19 16:40:45 -07002841 Deprecated since Python 3.5, use `Signature.from_callable()`.
2842 """
2843
2844 warnings.warn("inspect.Signature.from_builtin() is deprecated since "
2845 "Python 3.5, use Signature.from_callable()",
Berker Peksagb5601582015-05-21 23:40:54 +03002846 DeprecationWarning, stacklevel=2)
Yury Selivanov57d240e2014-02-19 16:27:23 -05002847 return _signature_from_builtin(cls, func)
Larry Hastings44e2eaa2013-11-23 15:37:55 -08002848
Yury Selivanovda396452014-03-27 12:09:24 -04002849 @classmethod
Yury Selivanovbcd4fc12015-05-20 14:30:08 -04002850 def from_callable(cls, obj, *, follow_wrapped=True):
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002851 """Constructs Signature for the given callable object."""
Yury Selivanovbcd4fc12015-05-20 14:30:08 -04002852 return _signature_from_callable(obj, sigcls=cls,
2853 follow_wrapper_chains=follow_wrapped)
Yury Selivanovda396452014-03-27 12:09:24 -04002854
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002855 @property
2856 def parameters(self):
2857 return self._parameters
2858
2859 @property
2860 def return_annotation(self):
2861 return self._return_annotation
2862
2863 def replace(self, *, parameters=_void, return_annotation=_void):
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002864 """Creates a customized copy of the Signature.
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002865 Pass 'parameters' and/or 'return_annotation' arguments
2866 to override them in the new copy.
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002867 """
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002868
2869 if parameters is _void:
2870 parameters = self.parameters.values()
2871
2872 if return_annotation is _void:
2873 return_annotation = self._return_annotation
2874
2875 return type(self)(parameters,
2876 return_annotation=return_annotation)
2877
Yury Selivanov08d4a4f2014-09-12 15:48:02 -04002878 def _hash_basis(self):
2879 params = tuple(param for param in self.parameters.values()
2880 if param.kind != _KEYWORD_ONLY)
2881
2882 kwo_params = {param.name: param for param in self.parameters.values()
2883 if param.kind == _KEYWORD_ONLY}
2884
2885 return params, kwo_params, self.return_annotation
2886
Yury Selivanov67ae50e2014-04-08 11:46:50 -04002887 def __hash__(self):
Yury Selivanov08d4a4f2014-09-12 15:48:02 -04002888 params, kwo_params, return_annotation = self._hash_basis()
2889 kwo_params = frozenset(kwo_params.values())
2890 return hash((params, kwo_params, return_annotation))
Yury Selivanov67ae50e2014-04-08 11:46:50 -04002891
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002892 def __eq__(self, other):
Serhiy Storchaka2489bd52015-07-18 23:20:50 +03002893 if self is other:
2894 return True
Serhiy Storchaka3018cc42015-07-18 23:19:05 +03002895 if not isinstance(other, Signature):
2896 return NotImplemented
Serhiy Storchaka2489bd52015-07-18 23:20:50 +03002897 return self._hash_basis() == other._hash_basis()
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002898
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002899 def _bind(self, args, kwargs, *, partial=False):
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002900 """Private method. Don't use directly."""
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002901
2902 arguments = OrderedDict()
2903
2904 parameters = iter(self.parameters.values())
2905 parameters_ex = ()
2906 arg_vals = iter(args)
2907
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002908 while True:
2909 # Let's iterate through the positional arguments and corresponding
2910 # parameters
2911 try:
2912 arg_val = next(arg_vals)
2913 except StopIteration:
2914 # No more positional arguments
2915 try:
2916 param = next(parameters)
2917 except StopIteration:
2918 # No more parameters. That's it. Just need to check that
2919 # we have no `kwargs` after this while loop
2920 break
2921 else:
2922 if param.kind == _VAR_POSITIONAL:
2923 # That's OK, just empty *args. Let's start parsing
2924 # kwargs
2925 break
2926 elif param.name in kwargs:
2927 if param.kind == _POSITIONAL_ONLY:
2928 msg = '{arg!r} parameter is positional only, ' \
2929 'but was passed as a keyword'
2930 msg = msg.format(arg=param.name)
2931 raise TypeError(msg) from None
2932 parameters_ex = (param,)
2933 break
2934 elif (param.kind == _VAR_KEYWORD or
2935 param.default is not _empty):
2936 # That's fine too - we have a default value for this
2937 # parameter. So, lets start parsing `kwargs`, starting
2938 # with the current parameter
2939 parameters_ex = (param,)
2940 break
2941 else:
Yury Selivanov38b0d5a2014-01-28 17:27:39 -05002942 # No default, not VAR_KEYWORD, not VAR_POSITIONAL,
2943 # not in `kwargs`
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002944 if partial:
2945 parameters_ex = (param,)
2946 break
2947 else:
Yury Selivanov86872752015-05-19 00:27:49 -04002948 msg = 'missing a required argument: {arg!r}'
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002949 msg = msg.format(arg=param.name)
2950 raise TypeError(msg) from None
2951 else:
2952 # We have a positional argument to process
2953 try:
2954 param = next(parameters)
2955 except StopIteration:
2956 raise TypeError('too many positional arguments') from None
2957 else:
2958 if param.kind in (_VAR_KEYWORD, _KEYWORD_ONLY):
2959 # Looks like we have no parameter for this positional
2960 # argument
Yury Selivanov86872752015-05-19 00:27:49 -04002961 raise TypeError(
2962 'too many positional arguments') from None
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002963
2964 if param.kind == _VAR_POSITIONAL:
2965 # We have an '*args'-like argument, let's fill it with
2966 # all positional arguments we have left and move on to
2967 # the next phase
2968 values = [arg_val]
2969 values.extend(arg_vals)
2970 arguments[param.name] = tuple(values)
2971 break
2972
2973 if param.name in kwargs:
Yury Selivanov86872752015-05-19 00:27:49 -04002974 raise TypeError(
2975 'multiple values for argument {arg!r}'.format(
2976 arg=param.name)) from None
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002977
2978 arguments[param.name] = arg_val
2979
2980 # Now, we iterate through the remaining parameters to process
2981 # keyword arguments
2982 kwargs_param = None
2983 for param in itertools.chain(parameters_ex, parameters):
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002984 if param.kind == _VAR_KEYWORD:
2985 # Memorize that we have a '**kwargs'-like parameter
2986 kwargs_param = param
2987 continue
2988
Yury Selivanov38b0d5a2014-01-28 17:27:39 -05002989 if param.kind == _VAR_POSITIONAL:
2990 # Named arguments don't refer to '*args'-like parameters.
2991 # We only arrive here if the positional arguments ended
2992 # before reaching the last parameter before *args.
2993 continue
2994
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002995 param_name = param.name
2996 try:
2997 arg_val = kwargs.pop(param_name)
2998 except KeyError:
2999 # We have no value for this parameter. It's fine though,
3000 # if it has a default value, or it is an '*args'-like
3001 # parameter, left alone by the processing of positional
3002 # arguments.
3003 if (not partial and param.kind != _VAR_POSITIONAL and
3004 param.default is _empty):
Yury Selivanov86872752015-05-19 00:27:49 -04003005 raise TypeError('missing a required argument: {arg!r}'. \
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07003006 format(arg=param_name)) from None
3007
3008 else:
Yury Selivanov9b9ac952014-01-28 20:54:28 -05003009 if param.kind == _POSITIONAL_ONLY:
3010 # This should never happen in case of a properly built
3011 # Signature object (but let's have this check here
3012 # to ensure correct behaviour just in case)
3013 raise TypeError('{arg!r} parameter is positional only, '
3014 'but was passed as a keyword'. \
3015 format(arg=param.name))
3016
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07003017 arguments[param_name] = arg_val
3018
3019 if kwargs:
3020 if kwargs_param is not None:
3021 # Process our '**kwargs'-like parameter
3022 arguments[kwargs_param.name] = kwargs
3023 else:
Yury Selivanov86872752015-05-19 00:27:49 -04003024 raise TypeError(
3025 'got an unexpected keyword argument {arg!r}'.format(
3026 arg=next(iter(kwargs))))
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07003027
3028 return self._bound_arguments_cls(self, arguments)
3029
Yury Selivanovc45873e2014-01-29 12:10:27 -05003030 def bind(*args, **kwargs):
Yury Selivanov5a23bd02014-03-29 13:47:11 -04003031 """Get a BoundArguments object, that maps the passed `args`
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07003032 and `kwargs` to the function's signature. Raises `TypeError`
3033 if the passed arguments can not be bound.
Yury Selivanov5a23bd02014-03-29 13:47:11 -04003034 """
Yury Selivanovc45873e2014-01-29 12:10:27 -05003035 return args[0]._bind(args[1:], kwargs)
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07003036
Yury Selivanovc45873e2014-01-29 12:10:27 -05003037 def bind_partial(*args, **kwargs):
Yury Selivanov5a23bd02014-03-29 13:47:11 -04003038 """Get a BoundArguments object, that partially maps the
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07003039 passed `args` and `kwargs` to the function's signature.
3040 Raises `TypeError` if the passed arguments can not be bound.
Yury Selivanov5a23bd02014-03-29 13:47:11 -04003041 """
Yury Selivanovc45873e2014-01-29 12:10:27 -05003042 return args[0]._bind(args[1:], kwargs, partial=True)
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07003043
Yury Selivanova5d63dd2014-03-27 11:31:43 -04003044 def __reduce__(self):
3045 return (type(self),
3046 (tuple(self._parameters.values()),),
3047 {'_return_annotation': self._return_annotation})
3048
3049 def __setstate__(self, state):
3050 self._return_annotation = state['_return_annotation']
3051
Yury Selivanov374375d2014-03-27 12:41:53 -04003052 def __repr__(self):
Yury Selivanovf229bc52015-05-15 12:53:56 -04003053 return '<{} {}>'.format(self.__class__.__name__, self)
Yury Selivanov374375d2014-03-27 12:41:53 -04003054
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07003055 def __str__(self):
3056 result = []
Yury Selivanov2393dca2014-01-27 15:07:58 -05003057 render_pos_only_separator = False
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07003058 render_kw_only_separator = True
Yury Selivanov2393dca2014-01-27 15:07:58 -05003059 for param in self.parameters.values():
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07003060 formatted = str(param)
3061
3062 kind = param.kind
Yury Selivanov2393dca2014-01-27 15:07:58 -05003063
3064 if kind == _POSITIONAL_ONLY:
3065 render_pos_only_separator = True
3066 elif render_pos_only_separator:
3067 # It's not a positional-only parameter, and the flag
3068 # is set to 'True' (there were pos-only params before.)
3069 result.append('/')
3070 render_pos_only_separator = False
3071
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07003072 if kind == _VAR_POSITIONAL:
3073 # OK, we have an '*args'-like parameter, so we won't need
3074 # a '*' to separate keyword-only arguments
3075 render_kw_only_separator = False
3076 elif kind == _KEYWORD_ONLY and render_kw_only_separator:
3077 # We have a keyword-only parameter to render and we haven't
3078 # rendered an '*args'-like parameter before, so add a '*'
3079 # separator to the parameters list ("foo(arg1, *, arg2)" case)
3080 result.append('*')
3081 # This condition should be only triggered once, so
3082 # reset the flag
3083 render_kw_only_separator = False
3084
3085 result.append(formatted)
3086
Yury Selivanov2393dca2014-01-27 15:07:58 -05003087 if render_pos_only_separator:
3088 # There were only positional-only parameters, hence the
3089 # flag was not reset to 'False'
3090 result.append('/')
3091
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07003092 rendered = '({})'.format(', '.join(result))
3093
3094 if self.return_annotation is not _empty:
3095 anno = formatannotation(self.return_annotation)
3096 rendered += ' -> {}'.format(anno)
3097
3098 return rendered
Nick Coghlanf94a16b2013-09-22 22:46:49 +10003099
Yury Selivanovda396452014-03-27 12:09:24 -04003100
Yury Selivanovbcd4fc12015-05-20 14:30:08 -04003101def signature(obj, *, follow_wrapped=True):
Yury Selivanov5a23bd02014-03-29 13:47:11 -04003102 """Get a signature object for the passed callable."""
Yury Selivanovbcd4fc12015-05-20 14:30:08 -04003103 return Signature.from_callable(obj, follow_wrapped=follow_wrapped)
Yury Selivanovda396452014-03-27 12:09:24 -04003104
3105
Nick Coghlanf94a16b2013-09-22 22:46:49 +10003106def _main():
3107 """ Logic for inspecting an object given at command line """
3108 import argparse
3109 import importlib
3110
3111 parser = argparse.ArgumentParser()
3112 parser.add_argument(
3113 'object',
3114 help="The object to be analysed. "
3115 "It supports the 'module:qualname' syntax")
3116 parser.add_argument(
3117 '-d', '--details', action='store_true',
3118 help='Display info about the module rather than its source code')
3119
3120 args = parser.parse_args()
3121
3122 target = args.object
3123 mod_name, has_attrs, attrs = target.partition(":")
3124 try:
3125 obj = module = importlib.import_module(mod_name)
3126 except Exception as exc:
3127 msg = "Failed to import {} ({}: {})".format(mod_name,
3128 type(exc).__name__,
3129 exc)
3130 print(msg, file=sys.stderr)
3131 exit(2)
3132
3133 if has_attrs:
3134 parts = attrs.split(".")
3135 obj = module
3136 for part in parts:
3137 obj = getattr(obj, part)
3138
3139 if module.__name__ in sys.builtin_module_names:
3140 print("Can't get info for builtin modules.", file=sys.stderr)
3141 exit(1)
3142
3143 if args.details:
3144 print('Target: {}'.format(target))
3145 print('Origin: {}'.format(getsourcefile(module)))
3146 print('Cached: {}'.format(module.__cached__))
3147 if obj is module:
3148 print('Loader: {}'.format(repr(module.__loader__)))
3149 if hasattr(module, '__path__'):
3150 print('Submodule search path: {}'.format(module.__path__))
3151 else:
3152 try:
3153 __, lineno = findsource(obj)
3154 except Exception:
3155 pass
3156 else:
3157 print('Line: {}'.format(lineno))
3158
3159 print('\n')
3160 else:
3161 print(getsource(obj))
3162
3163
3164if __name__ == "__main__":
3165 _main()