blob: d8475c63f9017f15a5782077bdbb79a72782e2d3 [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
275 co_kwonlyargcount number of keyword only arguments (not including ** arg)
276 co_lnotab encoded mapping of line numbers to bytecode indices
277 co_name name with which this code object was defined
278 co_names tuple of names of local variables
279 co_nlocals number of local variables
280 co_stacksize virtual machine stack space required
281 co_varnames tuple of names of arguments and local variables"""
Tim Peters28bc59f2001-09-16 08:40:16 +0000282 return isinstance(object, types.CodeType)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000283
284def isbuiltin(object):
285 """Return true if the object is a built-in function or method.
286
287 Built-in functions and methods provide these attributes:
288 __doc__ documentation string
289 __name__ original name of this function or method
290 __self__ instance to which a method is bound, or None"""
Tim Peters28bc59f2001-09-16 08:40:16 +0000291 return isinstance(object, types.BuiltinFunctionType)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000292
293def isroutine(object):
294 """Return true if the object is any kind of function or method."""
Tim Peters536d2262001-09-20 05:13:38 +0000295 return (isbuiltin(object)
296 or isfunction(object)
297 or ismethod(object)
298 or ismethoddescriptor(object))
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000299
Christian Heimesbe5b30b2008-03-03 19:18:51 +0000300def isabstract(object):
301 """Return true if the object is an abstract base class (ABC)."""
Natefcfe80e2017-04-24 10:06:15 -0700302 if not isinstance(object, type):
303 return False
304 if object.__flags__ & TPFLAGS_IS_ABSTRACT:
305 return True
306 if not issubclass(type(object), abc.ABCMeta):
307 return False
308 if hasattr(object, '__abstractmethods__'):
309 # It looks like ABCMeta.__new__ has finished running;
310 # TPFLAGS_IS_ABSTRACT should have been accurate.
311 return False
312 # It looks like ABCMeta.__new__ has not finished running yet; we're
313 # probably in __init_subclass__. We'll look for abstractmethods manually.
314 for name, value in object.__dict__.items():
315 if getattr(value, "__isabstractmethod__", False):
316 return True
317 for base in object.__bases__:
318 for name in getattr(base, "__abstractmethods__", ()):
319 value = getattr(object, name, None)
320 if getattr(value, "__isabstractmethod__", False):
321 return True
322 return False
Christian Heimesbe5b30b2008-03-03 19:18:51 +0000323
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000324def getmembers(object, predicate=None):
325 """Return all members of an object as (name, value) pairs sorted by name.
326 Optionally, only return members that satisfy a given predicate."""
Antoine Pitrou86a8a9a2011-12-21 09:57:40 +0100327 if isclass(object):
328 mro = (object,) + getmro(object)
329 else:
330 mro = ()
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000331 results = []
Ethan Furmane03ea372013-09-25 07:14:41 -0700332 processed = set()
333 names = dir(object)
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700334 # :dd any DynamicClassAttributes to the list of names if object is a class;
Ethan Furmane03ea372013-09-25 07:14:41 -0700335 # this may result in duplicate entries if, for example, a virtual
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700336 # attribute with the same name as a DynamicClassAttribute exists
Ethan Furmane03ea372013-09-25 07:14:41 -0700337 try:
338 for base in object.__bases__:
339 for k, v in base.__dict__.items():
340 if isinstance(v, types.DynamicClassAttribute):
341 names.append(k)
342 except AttributeError:
343 pass
344 for key in names:
Ethan Furman63c141c2013-10-18 00:27:39 -0700345 # First try to get the value via getattr. Some descriptors don't
346 # like calling their __get__ (see bug #1785), so fall back to
347 # looking in the __dict__.
348 try:
349 value = getattr(object, key)
350 # handle the duplicate key
351 if key in processed:
352 raise AttributeError
353 except AttributeError:
354 for base in mro:
355 if key in base.__dict__:
356 value = base.__dict__[key]
357 break
358 else:
359 # could be a (currently) missing slot member, or a buggy
360 # __dir__; discard and move on
Antoine Pitrou86a8a9a2011-12-21 09:57:40 +0100361 continue
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000362 if not predicate or predicate(value):
363 results.append((key, value))
Ethan Furmane03ea372013-09-25 07:14:41 -0700364 processed.add(key)
365 results.sort(key=lambda pair: pair[0])
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000366 return results
367
Christian Heimes25bb7832008-01-11 16:17:00 +0000368Attribute = namedtuple('Attribute', 'name kind defining_class object')
369
Tim Peters13b49d32001-09-23 02:00:29 +0000370def classify_class_attrs(cls):
371 """Return list of attribute-descriptor tuples.
372
373 For each name in dir(cls), the return list contains a 4-tuple
374 with these elements:
375
376 0. The name (a string).
377
378 1. The kind of attribute this is, one of these strings:
379 'class method' created via classmethod()
380 'static method' created via staticmethod()
381 'property' created via property()
Ethan Furmane03ea372013-09-25 07:14:41 -0700382 'method' any other flavor of method or descriptor
Tim Peters13b49d32001-09-23 02:00:29 +0000383 'data' not a method
384
385 2. The class which defined this attribute (a class).
386
Ethan Furmane03ea372013-09-25 07:14:41 -0700387 3. The object as obtained by calling getattr; if this fails, or if the
388 resulting object does not live anywhere in the class' mro (including
389 metaclasses) then the object is looked up in the defining class's
390 dict (found by walking the mro).
Ethan Furman668dede2013-09-14 18:53:26 -0700391
392 If one of the items in dir(cls) is stored in the metaclass it will now
393 be discovered and not have None be listed as the class in which it was
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700394 defined. Any items whose home class cannot be discovered are skipped.
Tim Peters13b49d32001-09-23 02:00:29 +0000395 """
396
397 mro = getmro(cls)
Ethan Furman668dede2013-09-14 18:53:26 -0700398 metamro = getmro(type(cls)) # for attributes stored in the metaclass
Jon Dufresne39726282017-05-18 07:35:54 -0700399 metamro = tuple(cls for cls in metamro if cls not in (type, object))
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700400 class_bases = (cls,) + mro
401 all_bases = class_bases + metamro
Tim Peters13b49d32001-09-23 02:00:29 +0000402 names = dir(cls)
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700403 # :dd any DynamicClassAttributes to the list of names;
Ethan Furmane03ea372013-09-25 07:14:41 -0700404 # this may result in duplicate entries if, for example, a virtual
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700405 # attribute with the same name as a DynamicClassAttribute exists.
Ethan Furman63c141c2013-10-18 00:27:39 -0700406 for base in mro:
Ethan Furmane03ea372013-09-25 07:14:41 -0700407 for k, v in base.__dict__.items():
408 if isinstance(v, types.DynamicClassAttribute):
409 names.append(k)
Tim Peters13b49d32001-09-23 02:00:29 +0000410 result = []
Ethan Furmane03ea372013-09-25 07:14:41 -0700411 processed = set()
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700412
Tim Peters13b49d32001-09-23 02:00:29 +0000413 for name in names:
Antoine Pitrou86a8a9a2011-12-21 09:57:40 +0100414 # Get the object associated with the name, and where it was defined.
Ethan Furmane03ea372013-09-25 07:14:41 -0700415 # Normal objects will be looked up with both getattr and directly in
416 # its class' dict (in case getattr fails [bug #1785], and also to look
417 # for a docstring).
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700418 # For DynamicClassAttributes on the second pass we only look in the
Ethan Furmane03ea372013-09-25 07:14:41 -0700419 # class's dict.
420 #
Tim Peters13b49d32001-09-23 02:00:29 +0000421 # Getting an obj from the __dict__ sometimes reveals more than
422 # using getattr. Static and class methods are dramatic examples.
Antoine Pitrou86a8a9a2011-12-21 09:57:40 +0100423 homecls = None
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700424 get_obj = None
425 dict_obj = None
Ethan Furmane03ea372013-09-25 07:14:41 -0700426 if name not in processed:
427 try:
Ethan Furmana8b07072013-10-18 01:22:08 -0700428 if name == '__dict__':
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700429 raise Exception("__dict__ is special, don't want the proxy")
Ethan Furmane03ea372013-09-25 07:14:41 -0700430 get_obj = getattr(cls, name)
431 except Exception as exc:
432 pass
433 else:
Ethan Furmane03ea372013-09-25 07:14:41 -0700434 homecls = getattr(get_obj, "__objclass__", homecls)
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700435 if homecls not in class_bases:
Ethan Furmane03ea372013-09-25 07:14:41 -0700436 # if the resulting object does not live somewhere in the
Ethan Furman63c141c2013-10-18 00:27:39 -0700437 # mro, drop it and search the mro manually
Ethan Furmane03ea372013-09-25 07:14:41 -0700438 homecls = None
Ethan Furman63c141c2013-10-18 00:27:39 -0700439 last_cls = None
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700440 # first look in the classes
441 for srch_cls in class_bases:
Ethan Furman63c141c2013-10-18 00:27:39 -0700442 srch_obj = getattr(srch_cls, name, None)
Yury Selivanovbf341fb2015-05-21 15:41:57 -0400443 if srch_obj is get_obj:
Ethan Furman63c141c2013-10-18 00:27:39 -0700444 last_cls = srch_cls
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700445 # then check the metaclasses
446 for srch_cls in metamro:
447 try:
448 srch_obj = srch_cls.__getattr__(cls, name)
449 except AttributeError:
450 continue
Yury Selivanovbf341fb2015-05-21 15:41:57 -0400451 if srch_obj is get_obj:
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700452 last_cls = srch_cls
Ethan Furman63c141c2013-10-18 00:27:39 -0700453 if last_cls is not None:
454 homecls = last_cls
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700455 for base in all_bases:
Ethan Furmane03ea372013-09-25 07:14:41 -0700456 if name in base.__dict__:
457 dict_obj = base.__dict__[name]
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700458 if homecls not in metamro:
459 homecls = base
Ethan Furmane03ea372013-09-25 07:14:41 -0700460 break
Ethan Furman63c141c2013-10-18 00:27:39 -0700461 if homecls is None:
462 # unable to locate the attribute anywhere, most likely due to
463 # buggy custom __dir__; discard and move on
464 continue
Yury Selivanovbf341fb2015-05-21 15:41:57 -0400465 obj = get_obj if get_obj is not None else dict_obj
Ethan Furmane03ea372013-09-25 07:14:41 -0700466 # Classify the object or its descriptor.
Serhiy Storchaka3327a2d2017-12-15 14:13:41 +0200467 if isinstance(dict_obj, (staticmethod, types.BuiltinMethodType)):
Tim Peters13b49d32001-09-23 02:00:29 +0000468 kind = "static method"
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700469 obj = dict_obj
Serhiy Storchaka3327a2d2017-12-15 14:13:41 +0200470 elif isinstance(dict_obj, (classmethod, types.ClassMethodDescriptorType)):
Tim Peters13b49d32001-09-23 02:00:29 +0000471 kind = "class method"
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700472 obj = dict_obj
473 elif isinstance(dict_obj, property):
Tim Peters13b49d32001-09-23 02:00:29 +0000474 kind = "property"
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700475 obj = dict_obj
Yury Selivanov0860a0b2014-01-31 14:28:44 -0500476 elif isroutine(obj):
Tim Peters13b49d32001-09-23 02:00:29 +0000477 kind = "method"
Antoine Pitrou86a8a9a2011-12-21 09:57:40 +0100478 else:
Ethan Furmane03ea372013-09-25 07:14:41 -0700479 kind = "data"
Christian Heimes25bb7832008-01-11 16:17:00 +0000480 result.append(Attribute(name, kind, homecls, obj))
Ethan Furmane03ea372013-09-25 07:14:41 -0700481 processed.add(name)
Tim Peters13b49d32001-09-23 02:00:29 +0000482 return result
483
Tim Peterse0b2d7a2001-09-22 06:10:55 +0000484# ----------------------------------------------------------- class helpers
Tim Peterse0b2d7a2001-09-22 06:10:55 +0000485
486def getmro(cls):
487 "Return tuple of base classes (including cls) in method resolution order."
Benjamin Petersonb82c8e52010-11-04 00:38:49 +0000488 return cls.__mro__
Tim Peterse0b2d7a2001-09-22 06:10:55 +0000489
Nick Coghlane8c45d62013-07-28 20:00:01 +1000490# -------------------------------------------------------- function helpers
491
492def unwrap(func, *, stop=None):
493 """Get the object wrapped by *func*.
494
495 Follows the chain of :attr:`__wrapped__` attributes returning the last
496 object in the chain.
497
498 *stop* is an optional callback accepting an object in the wrapper chain
499 as its sole argument that allows the unwrapping to be terminated early if
500 the callback returns a true value. If the callback never returns a true
501 value, the last object in the chain is returned as usual. For example,
502 :func:`signature` uses this to stop unwrapping if any object in the
503 chain has a ``__signature__`` attribute defined.
504
505 :exc:`ValueError` is raised if a cycle is encountered.
506
507 """
508 if stop is None:
509 def _is_wrapper(f):
510 return hasattr(f, '__wrapped__')
511 else:
512 def _is_wrapper(f):
513 return hasattr(f, '__wrapped__') and not stop(f)
514 f = func # remember the original func for error reporting
Thomas Kluyverf9169ce2017-05-23 04:27:52 +0100515 # Memoise by id to tolerate non-hashable objects, but store objects to
516 # ensure they aren't destroyed, which would allow their IDs to be reused.
517 memo = {id(f): f}
518 recursion_limit = sys.getrecursionlimit()
Nick Coghlane8c45d62013-07-28 20:00:01 +1000519 while _is_wrapper(func):
520 func = func.__wrapped__
521 id_func = id(func)
Thomas Kluyverf9169ce2017-05-23 04:27:52 +0100522 if (id_func in memo) or (len(memo) >= recursion_limit):
Nick Coghlane8c45d62013-07-28 20:00:01 +1000523 raise ValueError('wrapper loop when unwrapping {!r}'.format(f))
Thomas Kluyverf9169ce2017-05-23 04:27:52 +0100524 memo[id_func] = func
Nick Coghlane8c45d62013-07-28 20:00:01 +1000525 return func
526
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000527# -------------------------------------------------- source code extraction
528def indentsize(line):
529 """Return the indent size, in spaces, at the start of a line of text."""
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000530 expline = line.expandtabs()
531 return len(expline) - len(expline.lstrip())
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000532
Serhiy Storchaka5cf2b7252015-04-03 22:38:53 +0300533def _findclass(func):
534 cls = sys.modules.get(func.__module__)
535 if cls is None:
536 return None
537 for name in func.__qualname__.split('.')[:-1]:
538 cls = getattr(cls, name)
539 if not isclass(cls):
540 return None
541 return cls
542
543def _finddoc(obj):
544 if isclass(obj):
545 for base in obj.__mro__:
546 if base is not object:
547 try:
548 doc = base.__doc__
549 except AttributeError:
550 continue
551 if doc is not None:
552 return doc
553 return None
554
555 if ismethod(obj):
556 name = obj.__func__.__name__
557 self = obj.__self__
558 if (isclass(self) and
559 getattr(getattr(self, name, None), '__func__') is obj.__func__):
560 # classmethod
561 cls = self
562 else:
563 cls = self.__class__
564 elif isfunction(obj):
565 name = obj.__name__
566 cls = _findclass(obj)
567 if cls is None or getattr(cls, name) is not obj:
568 return None
569 elif isbuiltin(obj):
570 name = obj.__name__
571 self = obj.__self__
572 if (isclass(self) and
573 self.__qualname__ + '.' + name == obj.__qualname__):
574 # classmethod
575 cls = self
576 else:
577 cls = self.__class__
Serhiy Storchakaac4bdcc2015-10-29 08:15:50 +0200578 # Should be tested before isdatadescriptor().
579 elif isinstance(obj, property):
580 func = obj.fget
581 name = func.__name__
582 cls = _findclass(func)
583 if cls is None or getattr(cls, name) is not obj:
584 return None
Serhiy Storchaka5cf2b7252015-04-03 22:38:53 +0300585 elif ismethoddescriptor(obj) or isdatadescriptor(obj):
586 name = obj.__name__
587 cls = obj.__objclass__
588 if getattr(cls, name) is not obj:
589 return None
Raymond Hettingerd1e768a2019-03-25 13:01:13 -0700590 if ismemberdescriptor(obj):
591 slots = getattr(cls, '__slots__', None)
592 if isinstance(slots, dict) and name in slots:
593 return slots[name]
Serhiy Storchaka5cf2b7252015-04-03 22:38:53 +0300594 else:
595 return None
Serhiy Storchaka5cf2b7252015-04-03 22:38:53 +0300596 for base in cls.__mro__:
597 try:
598 doc = getattr(base, name).__doc__
599 except AttributeError:
600 continue
601 if doc is not None:
602 return doc
603 return None
604
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000605def getdoc(object):
606 """Get the documentation string for an object.
607
608 All tabs are expanded to spaces. To clean up docstrings that are
609 indented to line up with blocks of code, any whitespace than can be
610 uniformly removed from the second line onwards is removed."""
Tim Peters24008312002-03-17 18:56:20 +0000611 try:
612 doc = object.__doc__
613 except AttributeError:
614 return None
Serhiy Storchaka5cf2b7252015-04-03 22:38:53 +0300615 if doc is None:
616 try:
617 doc = _finddoc(object)
618 except (AttributeError, TypeError):
619 return None
Guido van Rossum3172c5d2007-10-16 18:12:55 +0000620 if not isinstance(doc, str):
Tim Peters24008312002-03-17 18:56:20 +0000621 return None
Georg Brandl0c77a822008-06-10 16:37:50 +0000622 return cleandoc(doc)
623
624def cleandoc(doc):
625 """Clean up indentation from docstrings.
626
627 Any whitespace that can be uniformly removed from the second line
628 onwards is removed."""
Tim Peters24008312002-03-17 18:56:20 +0000629 try:
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000630 lines = doc.expandtabs().split('\n')
Tim Peters24008312002-03-17 18:56:20 +0000631 except UnicodeError:
632 return None
633 else:
Ka-Ping Yeea59ef7b2002-11-30 03:53:15 +0000634 # Find minimum indentation of any non-blank lines after first line.
Christian Heimesa37d4c62007-12-04 23:02:19 +0000635 margin = sys.maxsize
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000636 for line in lines[1:]:
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000637 content = len(line.lstrip())
Ka-Ping Yeea59ef7b2002-11-30 03:53:15 +0000638 if content:
639 indent = len(line) - content
640 margin = min(margin, indent)
641 # Remove indentation.
642 if lines:
643 lines[0] = lines[0].lstrip()
Christian Heimesa37d4c62007-12-04 23:02:19 +0000644 if margin < sys.maxsize:
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000645 for i in range(1, len(lines)): lines[i] = lines[i][margin:]
Ka-Ping Yeea59ef7b2002-11-30 03:53:15 +0000646 # Remove any trailing or leading blank lines.
647 while lines and not lines[-1]:
648 lines.pop()
649 while lines and not lines[0]:
650 lines.pop(0)
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000651 return '\n'.join(lines)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000652
653def getfile(object):
Ka-Ping Yeec113c242001-03-02 02:08:53 +0000654 """Work out which source or compiled file an object was defined in."""
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000655 if ismodule(object):
Jason R. Coombsb9650a02018-03-05 18:29:08 -0500656 if getattr(object, '__file__', None):
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000657 return object.__file__
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +0000658 raise TypeError('{!r} is a built-in module'.format(object))
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000659 if isclass(object):
Yury Selivanov2eed8b72014-01-27 13:24:56 -0500660 if hasattr(object, '__module__'):
661 object = sys.modules.get(object.__module__)
Jason R. Coombsb9650a02018-03-05 18:29:08 -0500662 if getattr(object, '__file__', None):
Yury Selivanov2eed8b72014-01-27 13:24:56 -0500663 return object.__file__
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +0000664 raise TypeError('{!r} is a built-in class'.format(object))
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000665 if ismethod(object):
Christian Heimesff737952007-11-27 10:40:20 +0000666 object = object.__func__
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000667 if isfunction(object):
Neal Norwitz221085d2007-02-25 20:55:47 +0000668 object = object.__code__
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000669 if istraceback(object):
670 object = object.tb_frame
671 if isframe(object):
672 object = object.f_code
673 if iscode(object):
674 return object.co_filename
Thomas Kluyvere968bc732017-10-24 13:42:36 +0100675 raise TypeError('module, class, method, function, traceback, frame, or '
676 'code object was expected, got {}'.format(
677 type(object).__name__))
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000678
Ka-Ping Yee4d6fc7f2001-04-10 11:43:00 +0000679def getmodulename(path):
680 """Return the module name for a given file, or None."""
Nick Coghlan76e07702012-07-18 23:14:57 +1000681 fname = os.path.basename(path)
682 # Check for paths that look like an actual module file
683 suffixes = [(-len(suffix), suffix)
684 for suffix in importlib.machinery.all_suffixes()]
685 suffixes.sort() # try longest suffixes first, in case they overlap
686 for neglen, suffix in suffixes:
687 if fname.endswith(suffix):
688 return fname[:neglen]
689 return None
Ka-Ping Yee4d6fc7f2001-04-10 11:43:00 +0000690
Ka-Ping Yeec113c242001-03-02 02:08:53 +0000691def getsourcefile(object):
R. David Murraya1b37402010-06-17 02:04:29 +0000692 """Return the filename that can be used to locate an object's source.
693 Return None if no way can be identified to get the source.
694 """
Ka-Ping Yeec113c242001-03-02 02:08:53 +0000695 filename = getfile(object)
Brett Cannoncb66eb02012-05-11 12:58:42 -0400696 all_bytecode_suffixes = importlib.machinery.DEBUG_BYTECODE_SUFFIXES[:]
697 all_bytecode_suffixes += importlib.machinery.OPTIMIZED_BYTECODE_SUFFIXES[:]
698 if any(filename.endswith(s) for s in all_bytecode_suffixes):
699 filename = (os.path.splitext(filename)[0] +
700 importlib.machinery.SOURCE_SUFFIXES[0])
701 elif any(filename.endswith(s) for s in
702 importlib.machinery.EXTENSION_SUFFIXES):
703 return None
Thomas Wouters477c8d52006-05-27 19:21:47 +0000704 if os.path.exists(filename):
705 return filename
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000706 # only return a non-existent filename if the module has a PEP 302 loader
Brett Cannon4c14b5d2013-05-04 13:56:58 -0400707 if getattr(getmodule(object, filename), '__loader__', None) is not None:
Ka-Ping Yeec113c242001-03-02 02:08:53 +0000708 return filename
R. David Murraya1b37402010-06-17 02:04:29 +0000709 # or it is in the linecache
710 if filename in linecache.cache:
711 return filename
Ka-Ping Yeec113c242001-03-02 02:08:53 +0000712
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000713def getabsfile(object, _filename=None):
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000714 """Return an absolute path to the source or compiled file for an object.
Ka-Ping Yeec113c242001-03-02 02:08:53 +0000715
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000716 The idea is for each object to have a unique origin, so this routine
717 normalizes the result as much as possible."""
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000718 if _filename is None:
719 _filename = getsourcefile(object) or getfile(object)
720 return os.path.normcase(os.path.abspath(_filename))
Ka-Ping Yeec113c242001-03-02 02:08:53 +0000721
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000722modulesbyfile = {}
Thomas Wouters89f507f2006-12-13 04:49:30 +0000723_filesbymodname = {}
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000724
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000725def getmodule(object, _filename=None):
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000726 """Return the module an object was defined in, or None if not found."""
Ka-Ping Yee202c99b2001-04-13 09:15:08 +0000727 if ismodule(object):
728 return object
Johannes Gijsbers93245262004-09-11 15:53:22 +0000729 if hasattr(object, '__module__'):
Ka-Ping Yee8b58b842001-03-01 13:56:16 +0000730 return sys.modules.get(object.__module__)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000731 # Try the filename to modulename cache
732 if _filename is not None and _filename in modulesbyfile:
733 return sys.modules.get(modulesbyfile[_filename])
734 # Try the cache again with the absolute file name
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000735 try:
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000736 file = getabsfile(object, _filename)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000737 except TypeError:
738 return None
Raymond Hettinger54f02222002-06-01 14:18:47 +0000739 if file in modulesbyfile:
Ka-Ping Yeeb38bbbd2003-03-28 16:29:50 +0000740 return sys.modules.get(modulesbyfile[file])
Thomas Wouters89f507f2006-12-13 04:49:30 +0000741 # Update the filename to module name cache and check yet again
742 # Copy sys.modules in order to cope with changes while iterating
Éric Araujoa74f8ef2011-11-29 16:58:53 +0100743 for modname, module in list(sys.modules.items()):
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000744 if ismodule(module) and hasattr(module, '__file__'):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000745 f = module.__file__
746 if f == _filesbymodname.get(modname, None):
747 # Have already mapped this module, so skip it
748 continue
749 _filesbymodname[modname] = f
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000750 f = getabsfile(module)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000751 # Always map to the name the module knows itself by
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000752 modulesbyfile[f] = modulesbyfile[
753 os.path.realpath(f)] = module.__name__
Raymond Hettinger54f02222002-06-01 14:18:47 +0000754 if file in modulesbyfile:
Ka-Ping Yeeb38bbbd2003-03-28 16:29:50 +0000755 return sys.modules.get(modulesbyfile[file])
Thomas Wouters89f507f2006-12-13 04:49:30 +0000756 # Check the main module
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000757 main = sys.modules['__main__']
Brett Cannon4a671fe2003-06-15 22:33:28 +0000758 if not hasattr(object, '__name__'):
759 return None
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000760 if hasattr(main, object.__name__):
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000761 mainobject = getattr(main, object.__name__)
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000762 if mainobject is object:
763 return main
Thomas Wouters89f507f2006-12-13 04:49:30 +0000764 # Check builtins
Georg Brandl1a3284e2007-12-02 09:40:06 +0000765 builtin = sys.modules['builtins']
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000766 if hasattr(builtin, object.__name__):
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000767 builtinobject = getattr(builtin, object.__name__)
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000768 if builtinobject is object:
769 return builtin
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000770
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000771def findsource(object):
772 """Return the entire source file and starting line number for an object.
773
774 The argument may be a module, class, method, function, traceback, frame,
775 or code object. The source code is returned as a list of all the lines
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200776 in the file and the line number indexes a line in that list. An OSError
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000777 is raised if the source code cannot be retrieved."""
Benjamin Peterson9620cc02011-06-11 15:53:11 -0500778
Yury Selivanovef1e7502014-12-08 16:05:34 -0500779 file = getsourcefile(object)
780 if file:
781 # Invalidate cache if needed.
782 linecache.checkcache(file)
783 else:
784 file = getfile(object)
785 # Allow filenames in form of "<something>" to pass through.
786 # `doctest` monkeypatches `linecache` module to enable
787 # inspection, so let `linecache.getlines` to be called.
788 if not (file.startswith('<') and file.endswith('>')):
789 raise OSError('source code not available')
Benjamin Peterson9620cc02011-06-11 15:53:11 -0500790
Thomas Wouters89f507f2006-12-13 04:49:30 +0000791 module = getmodule(object, file)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000792 if module:
793 lines = linecache.getlines(file, module.__dict__)
794 else:
795 lines = linecache.getlines(file)
Neil Schemenauerf06f8532002-03-23 23:51:04 +0000796 if not lines:
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200797 raise OSError('could not get source code')
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000798
799 if ismodule(object):
800 return lines, 0
801
802 if isclass(object):
803 name = object.__name__
Thomas Wouters89f507f2006-12-13 04:49:30 +0000804 pat = re.compile(r'^(\s*)class\s*' + name + r'\b')
805 # make some effort to find the best matching class definition:
806 # use the one with the least indentation, which is the one
807 # that's most probably not inside a function definition.
808 candidates = []
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000809 for i in range(len(lines)):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000810 match = pat.match(lines[i])
811 if match:
812 # if it's at toplevel, it's already the best one
813 if lines[i][0] == 'c':
814 return lines, i
815 # else add whitespace to candidate list
816 candidates.append((match.group(1), i))
817 if candidates:
818 # this will sort by whitespace, and by line number,
819 # less whitespace first
820 candidates.sort()
821 return lines, candidates[0][1]
Jeremy Hyltonab919022003-06-27 18:41:20 +0000822 else:
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200823 raise OSError('could not find class definition')
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000824
825 if ismethod(object):
Christian Heimesff737952007-11-27 10:40:20 +0000826 object = object.__func__
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000827 if isfunction(object):
Neal Norwitz221085d2007-02-25 20:55:47 +0000828 object = object.__code__
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000829 if istraceback(object):
830 object = object.tb_frame
831 if isframe(object):
832 object = object.f_code
833 if iscode(object):
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000834 if not hasattr(object, 'co_firstlineno'):
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200835 raise OSError('could not find function definition')
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000836 lnum = object.co_firstlineno - 1
Yury Selivanove4e811d2015-07-21 19:01:52 +0300837 pat = re.compile(r'^(\s*def\s)|(\s*async\s+def\s)|(.*(?<!\w)lambda(:|\s))|^(\s*@)')
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000838 while lnum > 0:
Ka-Ping Yeea6e59712001-03-10 09:31:55 +0000839 if pat.match(lines[lnum]): break
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000840 lnum = lnum - 1
841 return lines, lnum
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200842 raise OSError('could not find code object')
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000843
844def getcomments(object):
Jeremy Hyltonb4c17c82002-03-28 23:01:56 +0000845 """Get lines of comments immediately preceding an object's source code.
846
847 Returns None when source can't be found.
848 """
849 try:
850 lines, lnum = findsource(object)
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200851 except (OSError, TypeError):
Jeremy Hyltonb4c17c82002-03-28 23:01:56 +0000852 return None
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000853
854 if ismodule(object):
855 # Look for a comment block at the top of the file.
856 start = 0
Ka-Ping Yeeb910efe2001-04-12 13:17:17 +0000857 if lines and lines[0][:2] == '#!': start = 1
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000858 while start < len(lines) and lines[start].strip() in ('', '#'):
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000859 start = start + 1
Ka-Ping Yeeb910efe2001-04-12 13:17:17 +0000860 if start < len(lines) and lines[start][:1] == '#':
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000861 comments = []
862 end = start
863 while end < len(lines) and lines[end][:1] == '#':
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000864 comments.append(lines[end].expandtabs())
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000865 end = end + 1
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000866 return ''.join(comments)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000867
868 # Look for a preceding block of comments at the same indentation.
869 elif lnum > 0:
870 indent = indentsize(lines[lnum])
871 end = lnum - 1
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000872 if end >= 0 and lines[end].lstrip()[:1] == '#' and \
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000873 indentsize(lines[end]) == indent:
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000874 comments = [lines[end].expandtabs().lstrip()]
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000875 if end > 0:
876 end = end - 1
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000877 comment = lines[end].expandtabs().lstrip()
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000878 while comment[:1] == '#' and indentsize(lines[end]) == indent:
879 comments[:0] = [comment]
880 end = end - 1
881 if end < 0: break
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000882 comment = lines[end].expandtabs().lstrip()
883 while comments and comments[0].strip() == '#':
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000884 comments[:1] = []
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000885 while comments and comments[-1].strip() == '#':
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000886 comments[-1:] = []
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000887 return ''.join(comments)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000888
Tim Peters4efb6e92001-06-29 23:51:08 +0000889class EndOfBlock(Exception): pass
890
891class BlockFinder:
892 """Provide a tokeneater() method to detect the end of a code block."""
893 def __init__(self):
894 self.indent = 0
Johannes Gijsbersa5855d52005-03-12 16:37:11 +0000895 self.islambda = False
Johannes Gijsbers1542f342004-12-12 16:46:28 +0000896 self.started = False
897 self.passline = False
Meador Inge5b718d72015-07-23 22:49:37 -0500898 self.indecorator = False
899 self.decoratorhasargs = False
Armin Rigodd5c0232005-09-25 11:45:45 +0000900 self.last = 1
Tim Peters4efb6e92001-06-29 23:51:08 +0000901
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000902 def tokeneater(self, type, token, srowcol, erowcol, line):
Meador Inge5b718d72015-07-23 22:49:37 -0500903 if not self.started and not self.indecorator:
904 # skip any decorators
905 if token == "@":
906 self.indecorator = True
Armin Rigodd5c0232005-09-25 11:45:45 +0000907 # look for the first "def", "class" or "lambda"
Meador Inge5b718d72015-07-23 22:49:37 -0500908 elif token in ("def", "class", "lambda"):
Johannes Gijsbersa5855d52005-03-12 16:37:11 +0000909 if token == "lambda":
910 self.islambda = True
Johannes Gijsbers1542f342004-12-12 16:46:28 +0000911 self.started = True
Armin Rigodd5c0232005-09-25 11:45:45 +0000912 self.passline = True # skip to the end of the line
Meador Inge5b718d72015-07-23 22:49:37 -0500913 elif token == "(":
914 if self.indecorator:
915 self.decoratorhasargs = True
916 elif token == ")":
917 if self.indecorator:
918 self.indecorator = False
919 self.decoratorhasargs = False
Tim Peters4efb6e92001-06-29 23:51:08 +0000920 elif type == tokenize.NEWLINE:
Armin Rigodd5c0232005-09-25 11:45:45 +0000921 self.passline = False # stop skipping when a NEWLINE is seen
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000922 self.last = srowcol[0]
Armin Rigodd5c0232005-09-25 11:45:45 +0000923 if self.islambda: # lambdas always end at the first NEWLINE
924 raise EndOfBlock
Meador Inge5b718d72015-07-23 22:49:37 -0500925 # hitting a NEWLINE when in a decorator without args
926 # ends the decorator
927 if self.indecorator and not self.decoratorhasargs:
928 self.indecorator = False
Johannes Gijsbers1542f342004-12-12 16:46:28 +0000929 elif self.passline:
930 pass
Tim Peters4efb6e92001-06-29 23:51:08 +0000931 elif type == tokenize.INDENT:
932 self.indent = self.indent + 1
Johannes Gijsbers1542f342004-12-12 16:46:28 +0000933 self.passline = True
Tim Peters4efb6e92001-06-29 23:51:08 +0000934 elif type == tokenize.DEDENT:
935 self.indent = self.indent - 1
Armin Rigodd5c0232005-09-25 11:45:45 +0000936 # the end of matching indent/dedent pairs end a block
937 # (note that this only works for "def"/"class" blocks,
938 # not e.g. for "if: else:" or "try: finally:" blocks)
939 if self.indent <= 0:
940 raise EndOfBlock
941 elif self.indent == 0 and type not in (tokenize.COMMENT, tokenize.NL):
942 # any other token on the same indentation level end the previous
943 # block as well, except the pseudo-tokens COMMENT and NL.
944 raise EndOfBlock
Tim Peters4efb6e92001-06-29 23:51:08 +0000945
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000946def getblock(lines):
947 """Extract the block of code at the top of the given list of lines."""
Armin Rigodd5c0232005-09-25 11:45:45 +0000948 blockfinder = BlockFinder()
Tim Peters4efb6e92001-06-29 23:51:08 +0000949 try:
Trent Nelson428de652008-03-18 22:41:35 +0000950 tokens = tokenize.generate_tokens(iter(lines).__next__)
951 for _token in tokens:
952 blockfinder.tokeneater(*_token)
Armin Rigodd5c0232005-09-25 11:45:45 +0000953 except (EndOfBlock, IndentationError):
954 pass
955 return lines[:blockfinder.last]
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000956
957def getsourcelines(object):
958 """Return a list of source lines and starting line number for an object.
959
960 The argument may be a module, class, method, function, traceback, frame,
961 or code object. The source code is returned as a list of the lines
962 corresponding to the object and the line number indicates where in the
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200963 original source file the first line of code was found. An OSError is
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000964 raised if the source code cannot be retrieved."""
Yury Selivanov081bbf62014-09-26 17:34:54 -0400965 object = unwrap(object)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000966 lines, lnum = findsource(object)
967
Vladimir Matveev91cb2982018-08-24 07:18:00 -0700968 if istraceback(object):
969 object = object.tb_frame
970
971 # for module or frame that corresponds to module, return all source lines
972 if (ismodule(object) or
973 (isframe(object) and object.f_code.co_name == "<module>")):
Meador Inge5b718d72015-07-23 22:49:37 -0500974 return lines, 0
975 else:
976 return getblock(lines[lnum:]), lnum + 1
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000977
978def getsource(object):
979 """Return the text of the source code for an object.
980
981 The argument may be a module, class, method, function, traceback, frame,
982 or code object. The source code is returned as a single string. An
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200983 OSError is raised if the source code cannot be retrieved."""
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000984 lines, lnum = getsourcelines(object)
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000985 return ''.join(lines)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000986
987# --------------------------------------------------- class tree extraction
988def walktree(classes, children, parent):
989 """Recursive helper function for getclasstree()."""
990 results = []
Raymond Hettingera1a992c2005-03-11 06:46:45 +0000991 classes.sort(key=attrgetter('__module__', '__name__'))
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000992 for c in classes:
993 results.append((c, c.__bases__))
Raymond Hettinger54f02222002-06-01 14:18:47 +0000994 if c in children:
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000995 results.append(walktree(children[c], children, c))
996 return results
997
Georg Brandl5ce83a02009-06-01 17:23:51 +0000998def getclasstree(classes, unique=False):
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000999 """Arrange the given list of classes into a hierarchy of nested lists.
1000
1001 Where a nested list appears, it contains classes derived from the class
1002 whose entry immediately precedes the list. Each entry is a 2-tuple
1003 containing a class and a tuple of its base classes. If the 'unique'
1004 argument is true, exactly one entry appears in the returned structure
1005 for each class in the given list. Otherwise, classes using multiple
1006 inheritance and their descendants will appear multiple times."""
1007 children = {}
1008 roots = []
1009 for c in classes:
1010 if c.__bases__:
1011 for parent in c.__bases__:
Srinivas Reddy Thatiparthy (శ్రీనివాస్ రెడ్డి తాటిపర్తి)feaefc72018-02-09 15:29:19 +05301012 if parent not in children:
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001013 children[parent] = []
Serhiy Storchaka362c1b52013-09-05 17:14:32 +03001014 if c not in children[parent]:
1015 children[parent].append(c)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001016 if unique and parent in classes: break
1017 elif c not in roots:
1018 roots.append(c)
Raymond Hettingere0d49722002-06-02 18:55:56 +00001019 for parent in children:
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001020 if parent not in classes:
1021 roots.append(parent)
1022 return walktree(roots, children, None)
1023
1024# ------------------------------------------------ argument list extraction
Christian Heimes25bb7832008-01-11 16:17:00 +00001025Arguments = namedtuple('Arguments', 'args, varargs, varkw')
1026
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001027def getargs(co):
1028 """Get information about the arguments accepted by a code object.
1029
Guido van Rossum2e65f892007-02-28 22:03:49 +00001030 Three things are returned: (args, varargs, varkw), where
Georg Brandlc1c4bf82010-10-15 16:07:41 +00001031 'args' is the list of argument names. Keyword-only arguments are
1032 appended. 'varargs' and 'varkw' are the names of the * and **
1033 arguments or None."""
Guido van Rossum2e65f892007-02-28 22:03:49 +00001034 args, varargs, kwonlyargs, varkw = _getfullargs(co)
Christian Heimes25bb7832008-01-11 16:17:00 +00001035 return Arguments(args + kwonlyargs, varargs, varkw)
Guido van Rossum2e65f892007-02-28 22:03:49 +00001036
1037def _getfullargs(co):
1038 """Get information about the arguments accepted by a code object.
1039
1040 Four things are returned: (args, varargs, kwonlyargs, varkw), where
Georg Brandlc1c4bf82010-10-15 16:07:41 +00001041 'args' and 'kwonlyargs' are lists of argument names, and 'varargs'
1042 and 'varkw' are the names of the * and ** arguments or None."""
Jeremy Hylton64967882003-06-27 18:14:39 +00001043
1044 if not iscode(co):
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00001045 raise TypeError('{!r} is not a code object'.format(co))
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001046
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001047 nargs = co.co_argcount
1048 names = co.co_varnames
Guido van Rossum2e65f892007-02-28 22:03:49 +00001049 nkwargs = co.co_kwonlyargcount
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001050 args = list(names[:nargs])
Guido van Rossum2e65f892007-02-28 22:03:49 +00001051 kwonlyargs = list(names[nargs:nargs+nkwargs])
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001052 step = 0
1053
Guido van Rossum2e65f892007-02-28 22:03:49 +00001054 nargs += nkwargs
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001055 varargs = None
1056 if co.co_flags & CO_VARARGS:
1057 varargs = co.co_varnames[nargs]
1058 nargs = nargs + 1
1059 varkw = None
1060 if co.co_flags & CO_VARKEYWORDS:
1061 varkw = co.co_varnames[nargs]
Guido van Rossum2e65f892007-02-28 22:03:49 +00001062 return args, varargs, kwonlyargs, varkw
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001063
Yury Selivanov37dc2b22016-01-11 15:15:01 -05001064
1065ArgSpec = namedtuple('ArgSpec', 'args varargs keywords defaults')
1066
1067def getargspec(func):
Nick Coghlan3c35fdb2016-12-02 20:29:57 +10001068 """Get the names and default values of a function's parameters.
Yury Selivanov37dc2b22016-01-11 15:15:01 -05001069
1070 A tuple of four things is returned: (args, varargs, keywords, defaults).
1071 'args' is a list of the argument names, including keyword-only argument names.
Nick Coghlan3c35fdb2016-12-02 20:29:57 +10001072 'varargs' and 'keywords' are the names of the * and ** parameters or None.
1073 'defaults' is an n-tuple of the default values of the last n parameters.
Yury Selivanov37dc2b22016-01-11 15:15:01 -05001074
Nick Coghlan3c35fdb2016-12-02 20:29:57 +10001075 This function is deprecated, as it does not support annotations or
1076 keyword-only parameters and will raise ValueError if either is present
1077 on the supplied callable.
1078
1079 For a more structured introspection API, use inspect.signature() instead.
1080
1081 Alternatively, use getfullargspec() for an API with a similar namedtuple
1082 based interface, but full support for annotations and keyword-only
1083 parameters.
Matthias Bussonnierded87d82018-10-19 16:40:45 -07001084
1085 Deprecated since Python 3.5, use `inspect.getfullargspec()`.
Yury Selivanov37dc2b22016-01-11 15:15:01 -05001086 """
Matthias Bussonnierded87d82018-10-19 16:40:45 -07001087 warnings.warn("inspect.getargspec() is deprecated since Python 3.0, "
Nick Coghlan3c35fdb2016-12-02 20:29:57 +10001088 "use inspect.signature() or inspect.getfullargspec()",
1089 DeprecationWarning, stacklevel=2)
Yury Selivanov37dc2b22016-01-11 15:15:01 -05001090 args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults, ann = \
1091 getfullargspec(func)
1092 if kwonlyargs or ann:
Nick Coghlan3c35fdb2016-12-02 20:29:57 +10001093 raise ValueError("Function has keyword-only parameters or annotations"
Yury Selivanov37dc2b22016-01-11 15:15:01 -05001094 ", use getfullargspec() API which can support them")
1095 return ArgSpec(args, varargs, varkw, defaults)
1096
Christian Heimes25bb7832008-01-11 16:17:00 +00001097FullArgSpec = namedtuple('FullArgSpec',
Benjamin Peterson3d4ca742008-11-12 21:39:01 +00001098 'args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults, annotations')
Guido van Rossum2e65f892007-02-28 22:03:49 +00001099
1100def getfullargspec(func):
Nick Coghlan3c35fdb2016-12-02 20:29:57 +10001101 """Get the names and default values of a callable object's parameters.
Guido van Rossum2e65f892007-02-28 22:03:49 +00001102
Brett Cannon504d8852007-09-07 02:12:14 +00001103 A tuple of seven things is returned:
Nick Coghlan3c35fdb2016-12-02 20:29:57 +10001104 (args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults, annotations).
1105 'args' is a list of the parameter names.
1106 'varargs' and 'varkw' are the names of the * and ** parameters or None.
1107 'defaults' is an n-tuple of the default values of the last n parameters.
1108 'kwonlyargs' is a list of keyword-only parameter names.
Guido van Rossum2e65f892007-02-28 22:03:49 +00001109 'kwonlydefaults' is a dictionary mapping names from kwonlyargs to defaults.
Nick Coghlan3c35fdb2016-12-02 20:29:57 +10001110 'annotations' is a dictionary mapping parameter names to annotations.
Guido van Rossuma8add0e2007-05-14 22:03:55 +00001111
Nick Coghlan3c35fdb2016-12-02 20:29:57 +10001112 Notable differences from inspect.signature():
1113 - the "self" parameter is always reported, even for bound methods
1114 - wrapper chains defined by __wrapped__ *not* unwrapped automatically
Jeremy Hylton64967882003-06-27 18:14:39 +00001115 """
1116
Yury Selivanov57d240e2014-02-19 16:27:23 -05001117 try:
1118 # Re: `skip_bound_arg=False`
1119 #
Yury Selivanovd82eddc2014-01-29 11:24:39 -05001120 # There is a notable difference in behaviour between getfullargspec
1121 # and Signature: the former always returns 'self' parameter for bound
1122 # methods, whereas the Signature always shows the actual calling
1123 # signature of the passed object.
1124 #
1125 # To simulate this behaviour, we "unbind" bound methods, to trick
1126 # inspect.signature to always return their first parameter ("self",
1127 # usually)
Yury Selivanovd82eddc2014-01-29 11:24:39 -05001128
Yury Selivanov57d240e2014-02-19 16:27:23 -05001129 # Re: `follow_wrapper_chains=False`
1130 #
1131 # getfullargspec() historically ignored __wrapped__ attributes,
1132 # so we ensure that remains the case in 3.3+
Yury Selivanovd82eddc2014-01-29 11:24:39 -05001133
Yury Selivanov5a23bd02014-03-29 13:47:11 -04001134 sig = _signature_from_callable(func,
1135 follow_wrapper_chains=False,
1136 skip_bound_arg=False,
1137 sigcls=Signature)
Yury Selivanovd82eddc2014-01-29 11:24:39 -05001138 except Exception as ex:
1139 # Most of the times 'signature' will raise ValueError.
1140 # But, it can also raise AttributeError, and, maybe something
1141 # else. So to be fully backwards compatible, we catch all
1142 # possible exceptions here, and reraise a TypeError.
1143 raise TypeError('unsupported callable') from ex
1144
1145 args = []
1146 varargs = None
1147 varkw = None
1148 kwonlyargs = []
1149 defaults = ()
1150 annotations = {}
1151 defaults = ()
1152 kwdefaults = {}
1153
1154 if sig.return_annotation is not sig.empty:
1155 annotations['return'] = sig.return_annotation
1156
1157 for param in sig.parameters.values():
1158 kind = param.kind
1159 name = param.name
1160
1161 if kind is _POSITIONAL_ONLY:
1162 args.append(name)
1163 elif kind is _POSITIONAL_OR_KEYWORD:
1164 args.append(name)
1165 if param.default is not param.empty:
1166 defaults += (param.default,)
1167 elif kind is _VAR_POSITIONAL:
1168 varargs = name
1169 elif kind is _KEYWORD_ONLY:
1170 kwonlyargs.append(name)
1171 if param.default is not param.empty:
1172 kwdefaults[name] = param.default
1173 elif kind is _VAR_KEYWORD:
1174 varkw = name
1175
1176 if param.annotation is not param.empty:
1177 annotations[name] = param.annotation
1178
1179 if not kwdefaults:
1180 # compatibility with 'func.__kwdefaults__'
1181 kwdefaults = None
1182
1183 if not defaults:
1184 # compatibility with 'func.__defaults__'
1185 defaults = None
1186
Yury Selivanovd82eddc2014-01-29 11:24:39 -05001187 return FullArgSpec(args, varargs, varkw, defaults,
1188 kwonlyargs, kwdefaults, annotations)
1189
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001190
Christian Heimes25bb7832008-01-11 16:17:00 +00001191ArgInfo = namedtuple('ArgInfo', 'args varargs keywords locals')
1192
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001193def getargvalues(frame):
1194 """Get information about arguments passed into a particular frame.
1195
1196 A tuple of four things is returned: (args, varargs, varkw, locals).
Georg Brandlc1c4bf82010-10-15 16:07:41 +00001197 'args' is a list of the argument names.
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001198 'varargs' and 'varkw' are the names of the * and ** arguments or None.
1199 'locals' is the locals dictionary of the given frame."""
1200 args, varargs, varkw = getargs(frame.f_code)
Benjamin Peterson1a6e0d02008-10-25 15:49:17 +00001201 return ArgInfo(args, varargs, varkw, frame.f_locals)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001202
Guido van Rossum2e65f892007-02-28 22:03:49 +00001203def formatannotation(annotation, base_module=None):
Guido van Rossum52e50042016-10-22 07:55:18 -07001204 if getattr(annotation, '__module__', None) == 'typing':
1205 return repr(annotation).replace('typing.', '')
Guido van Rossum2e65f892007-02-28 22:03:49 +00001206 if isinstance(annotation, type):
Georg Brandl1a3284e2007-12-02 09:40:06 +00001207 if annotation.__module__ in ('builtins', base_module):
Serhiy Storchaka521e5862014-07-22 15:00:37 +03001208 return annotation.__qualname__
1209 return annotation.__module__+'.'+annotation.__qualname__
Guido van Rossum2e65f892007-02-28 22:03:49 +00001210 return repr(annotation)
Guido van Rossuma8add0e2007-05-14 22:03:55 +00001211
Guido van Rossum2e65f892007-02-28 22:03:49 +00001212def formatannotationrelativeto(object):
Guido van Rossuma8add0e2007-05-14 22:03:55 +00001213 module = getattr(object, '__module__', None)
1214 def _formatannotation(annotation):
1215 return formatannotation(annotation, module)
1216 return _formatannotation
Guido van Rossum2e65f892007-02-28 22:03:49 +00001217
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001218def formatargspec(args, varargs=None, varkw=None, defaults=None,
Guido van Rossum2e65f892007-02-28 22:03:49 +00001219 kwonlyargs=(), kwonlydefaults={}, annotations={},
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001220 formatarg=str,
1221 formatvarargs=lambda name: '*' + name,
1222 formatvarkw=lambda name: '**' + name,
1223 formatvalue=lambda value: '=' + repr(value),
Guido van Rossum2e65f892007-02-28 22:03:49 +00001224 formatreturns=lambda text: ' -> ' + text,
Georg Brandlc1c4bf82010-10-15 16:07:41 +00001225 formatannotation=formatannotation):
Berker Peksagfa3922c2015-07-31 04:11:29 +03001226 """Format an argument spec from the values returned by getfullargspec.
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001227
Guido van Rossum2e65f892007-02-28 22:03:49 +00001228 The first seven arguments are (args, varargs, varkw, defaults,
1229 kwonlyargs, kwonlydefaults, annotations). The other five arguments
1230 are the corresponding optional formatting functions that are called to
1231 turn names and values into strings. The last argument is an optional
Matthias Bussonnier46c5cd02018-06-11 22:08:16 +02001232 function to format the sequence of arguments.
1233
1234 Deprecated since Python 3.5: use the `signature` function and `Signature`
1235 objects.
1236 """
1237
1238 from warnings import warn
1239
1240 warn("`formatargspec` is deprecated since Python 3.5. Use `signature` and "
Zackery Spytz41254eb2018-06-11 21:16:18 -06001241 "the `Signature` object directly",
Matthias Bussonnier46c5cd02018-06-11 22:08:16 +02001242 DeprecationWarning,
1243 stacklevel=2)
1244
Guido van Rossum2e65f892007-02-28 22:03:49 +00001245 def formatargandannotation(arg):
1246 result = formatarg(arg)
1247 if arg in annotations:
1248 result += ': ' + formatannotation(annotations[arg])
1249 return result
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001250 specs = []
1251 if defaults:
1252 firstdefault = len(args) - len(defaults)
Benjamin Petersonb58dda72009-01-18 22:27:04 +00001253 for i, arg in enumerate(args):
Georg Brandlc1c4bf82010-10-15 16:07:41 +00001254 spec = formatargandannotation(arg)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001255 if defaults and i >= firstdefault:
1256 spec = spec + formatvalue(defaults[i - firstdefault])
1257 specs.append(spec)
Raymond Hettinger936654b2002-06-01 03:06:31 +00001258 if varargs is not None:
Guido van Rossum2e65f892007-02-28 22:03:49 +00001259 specs.append(formatvarargs(formatargandannotation(varargs)))
1260 else:
1261 if kwonlyargs:
1262 specs.append('*')
1263 if kwonlyargs:
1264 for kwonlyarg in kwonlyargs:
1265 spec = formatargandannotation(kwonlyarg)
Benjamin Peterson9953a8d2009-01-17 04:15:01 +00001266 if kwonlydefaults and kwonlyarg in kwonlydefaults:
Guido van Rossum2e65f892007-02-28 22:03:49 +00001267 spec += formatvalue(kwonlydefaults[kwonlyarg])
1268 specs.append(spec)
Raymond Hettinger936654b2002-06-01 03:06:31 +00001269 if varkw is not None:
Guido van Rossum2e65f892007-02-28 22:03:49 +00001270 specs.append(formatvarkw(formatargandannotation(varkw)))
Neal Norwitz9d72bb42007-04-17 08:48:32 +00001271 result = '(' + ', '.join(specs) + ')'
Guido van Rossum2e65f892007-02-28 22:03:49 +00001272 if 'return' in annotations:
1273 result += formatreturns(formatannotation(annotations['return']))
1274 return result
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001275
1276def formatargvalues(args, varargs, varkw, locals,
1277 formatarg=str,
1278 formatvarargs=lambda name: '*' + name,
1279 formatvarkw=lambda name: '**' + name,
Georg Brandlc1c4bf82010-10-15 16:07:41 +00001280 formatvalue=lambda value: '=' + repr(value)):
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001281 """Format an argument spec from the 4 values returned by getargvalues.
1282
1283 The first four arguments are (args, varargs, varkw, locals). The
1284 next four arguments are the corresponding optional formatting functions
1285 that are called to turn names and values into strings. The ninth
1286 argument is an optional function to format the sequence of arguments."""
1287 def convert(name, locals=locals,
1288 formatarg=formatarg, formatvalue=formatvalue):
1289 return formatarg(name) + formatvalue(locals[name])
1290 specs = []
1291 for i in range(len(args)):
Georg Brandlc1c4bf82010-10-15 16:07:41 +00001292 specs.append(convert(args[i]))
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001293 if varargs:
1294 specs.append(formatvarargs(varargs) + formatvalue(locals[varargs]))
1295 if varkw:
1296 specs.append(formatvarkw(varkw) + formatvalue(locals[varkw]))
Neal Norwitz9d72bb42007-04-17 08:48:32 +00001297 return '(' + ', '.join(specs) + ')'
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001298
Benjamin Petersone109c702011-06-24 09:37:26 -05001299def _missing_arguments(f_name, argnames, pos, values):
1300 names = [repr(name) for name in argnames if name not in values]
1301 missing = len(names)
1302 if missing == 1:
1303 s = names[0]
1304 elif missing == 2:
1305 s = "{} and {}".format(*names)
1306 else:
Yury Selivanovdccfa132014-03-27 18:42:52 -04001307 tail = ", {} and {}".format(*names[-2:])
Benjamin Petersone109c702011-06-24 09:37:26 -05001308 del names[-2:]
1309 s = ", ".join(names) + tail
1310 raise TypeError("%s() missing %i required %s argument%s: %s" %
1311 (f_name, missing,
1312 "positional" if pos else "keyword-only",
1313 "" if missing == 1 else "s", s))
1314
1315def _too_many(f_name, args, kwonly, varargs, defcount, given, values):
Benjamin Petersonb204a422011-06-05 22:04:07 -05001316 atleast = len(args) - defcount
Benjamin Petersonb204a422011-06-05 22:04:07 -05001317 kwonly_given = len([arg for arg in kwonly if arg in values])
1318 if varargs:
1319 plural = atleast != 1
1320 sig = "at least %d" % (atleast,)
1321 elif defcount:
1322 plural = True
1323 sig = "from %d to %d" % (atleast, len(args))
1324 else:
1325 plural = len(args) != 1
1326 sig = str(len(args))
1327 kwonly_sig = ""
1328 if kwonly_given:
1329 msg = " positional argument%s (and %d keyword-only argument%s)"
1330 kwonly_sig = (msg % ("s" if given != 1 else "", kwonly_given,
1331 "s" if kwonly_given != 1 else ""))
1332 raise TypeError("%s() takes %s positional argument%s but %d%s %s given" %
1333 (f_name, sig, "s" if plural else "", given, kwonly_sig,
1334 "was" if given == 1 and not kwonly_given else "were"))
1335
Benjamin Peterson3e6ab172014-01-02 12:24:08 -06001336def getcallargs(*func_and_positional, **named):
Benjamin Peterson25cd7eb2010-03-30 18:42:32 +00001337 """Get the mapping of arguments to values.
1338
1339 A dict is returned, with keys the function argument names (including the
1340 names of the * and ** arguments, if any), and values the respective bound
1341 values from 'positional' and 'named'."""
Benjamin Peterson3e6ab172014-01-02 12:24:08 -06001342 func = func_and_positional[0]
1343 positional = func_and_positional[1:]
Benjamin Peterson25cd7eb2010-03-30 18:42:32 +00001344 spec = getfullargspec(func)
1345 args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults, ann = spec
1346 f_name = func.__name__
1347 arg2value = {}
1348
Benjamin Petersonb204a422011-06-05 22:04:07 -05001349
Benjamin Peterson25cd7eb2010-03-30 18:42:32 +00001350 if ismethod(func) and func.__self__ is not None:
1351 # implicit 'self' (or 'cls' for classmethods) argument
1352 positional = (func.__self__,) + positional
1353 num_pos = len(positional)
Benjamin Peterson25cd7eb2010-03-30 18:42:32 +00001354 num_args = len(args)
1355 num_defaults = len(defaults) if defaults else 0
Benjamin Peterson25cd7eb2010-03-30 18:42:32 +00001356
Benjamin Petersonb204a422011-06-05 22:04:07 -05001357 n = min(num_pos, num_args)
1358 for i in range(n):
1359 arg2value[args[i]] = positional[i]
1360 if varargs:
1361 arg2value[varargs] = tuple(positional[n:])
1362 possible_kwargs = set(args + kwonlyargs)
Benjamin Peterson25cd7eb2010-03-30 18:42:32 +00001363 if varkw:
Benjamin Petersonb204a422011-06-05 22:04:07 -05001364 arg2value[varkw] = {}
1365 for kw, value in named.items():
1366 if kw not in possible_kwargs:
1367 if not varkw:
1368 raise TypeError("%s() got an unexpected keyword argument %r" %
1369 (f_name, kw))
1370 arg2value[varkw][kw] = value
1371 continue
1372 if kw in arg2value:
1373 raise TypeError("%s() got multiple values for argument %r" %
1374 (f_name, kw))
1375 arg2value[kw] = value
1376 if num_pos > num_args and not varargs:
Benjamin Petersone109c702011-06-24 09:37:26 -05001377 _too_many(f_name, args, kwonlyargs, varargs, num_defaults,
1378 num_pos, arg2value)
Benjamin Petersonb204a422011-06-05 22:04:07 -05001379 if num_pos < num_args:
Benjamin Petersone109c702011-06-24 09:37:26 -05001380 req = args[:num_args - num_defaults]
1381 for arg in req:
Benjamin Petersonb204a422011-06-05 22:04:07 -05001382 if arg not in arg2value:
Benjamin Petersone109c702011-06-24 09:37:26 -05001383 _missing_arguments(f_name, req, True, arg2value)
Benjamin Petersonb204a422011-06-05 22:04:07 -05001384 for i, arg in enumerate(args[num_args - num_defaults:]):
1385 if arg not in arg2value:
1386 arg2value[arg] = defaults[i]
Benjamin Petersone109c702011-06-24 09:37:26 -05001387 missing = 0
Benjamin Petersonb204a422011-06-05 22:04:07 -05001388 for kwarg in kwonlyargs:
1389 if kwarg not in arg2value:
Yury Selivanov875df202014-03-27 18:23:03 -04001390 if kwonlydefaults and kwarg in kwonlydefaults:
Benjamin Petersone109c702011-06-24 09:37:26 -05001391 arg2value[kwarg] = kwonlydefaults[kwarg]
1392 else:
1393 missing += 1
1394 if missing:
1395 _missing_arguments(f_name, kwonlyargs, False, arg2value)
Benjamin Peterson25cd7eb2010-03-30 18:42:32 +00001396 return arg2value
1397
Nick Coghlan2f92e542012-06-23 19:39:55 +10001398ClosureVars = namedtuple('ClosureVars', 'nonlocals globals builtins unbound')
1399
1400def getclosurevars(func):
1401 """
1402 Get the mapping of free variables to their current values.
1403
Meador Inge8fda3592012-07-19 21:33:21 -05001404 Returns a named tuple of dicts mapping the current nonlocal, global
Nick Coghlan2f92e542012-06-23 19:39:55 +10001405 and builtin references as seen by the body of the function. A final
1406 set of unbound names that could not be resolved is also provided.
1407 """
1408
1409 if ismethod(func):
1410 func = func.__func__
1411
1412 if not isfunction(func):
Serhiy Storchakaa4a30202017-11-28 22:54:42 +02001413 raise TypeError("{!r} is not a Python function".format(func))
Nick Coghlan2f92e542012-06-23 19:39:55 +10001414
1415 code = func.__code__
1416 # Nonlocal references are named in co_freevars and resolved
1417 # by looking them up in __closure__ by positional index
1418 if func.__closure__ is None:
1419 nonlocal_vars = {}
1420 else:
1421 nonlocal_vars = {
1422 var : cell.cell_contents
1423 for var, cell in zip(code.co_freevars, func.__closure__)
1424 }
1425
1426 # Global and builtin references are named in co_names and resolved
1427 # by looking them up in __globals__ or __builtins__
1428 global_ns = func.__globals__
1429 builtin_ns = global_ns.get("__builtins__", builtins.__dict__)
1430 if ismodule(builtin_ns):
1431 builtin_ns = builtin_ns.__dict__
1432 global_vars = {}
1433 builtin_vars = {}
1434 unbound_names = set()
1435 for name in code.co_names:
1436 if name in ("None", "True", "False"):
1437 # Because these used to be builtins instead of keywords, they
1438 # may still show up as name references. We ignore them.
1439 continue
1440 try:
1441 global_vars[name] = global_ns[name]
1442 except KeyError:
1443 try:
1444 builtin_vars[name] = builtin_ns[name]
1445 except KeyError:
1446 unbound_names.add(name)
1447
1448 return ClosureVars(nonlocal_vars, global_vars,
1449 builtin_vars, unbound_names)
1450
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001451# -------------------------------------------------- stack frame extraction
Christian Heimes25bb7832008-01-11 16:17:00 +00001452
1453Traceback = namedtuple('Traceback', 'filename lineno function code_context index')
1454
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001455def getframeinfo(frame, context=1):
1456 """Get information about a frame or traceback object.
1457
1458 A tuple of five things is returned: the filename, the line number of
1459 the current line, the function name, a list of lines of context from
1460 the source code, and the index of the current line within that list.
1461 The optional second argument specifies the number of lines of context
1462 to return, which are centered around the current line."""
1463 if istraceback(frame):
Andrew M. Kuchlingba8b6bc2004-06-05 14:11:59 +00001464 lineno = frame.tb_lineno
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001465 frame = frame.tb_frame
Andrew M. Kuchlingba8b6bc2004-06-05 14:11:59 +00001466 else:
1467 lineno = frame.f_lineno
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001468 if not isframe(frame):
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00001469 raise TypeError('{!r} is not a frame or traceback object'.format(frame))
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001470
Neil Schemenauerf06f8532002-03-23 23:51:04 +00001471 filename = getsourcefile(frame) or getfile(frame)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001472 if context > 0:
Guido van Rossum54e54c62001-09-04 19:14:14 +00001473 start = lineno - 1 - context//2
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001474 try:
1475 lines, lnum = findsource(frame)
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02001476 except OSError:
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +00001477 lines = index = None
1478 else:
Raymond Hettingera0501712004-06-15 11:22:53 +00001479 start = max(0, min(start, len(lines) - context))
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001480 lines = lines[start:start+context]
Ka-Ping Yee59ade082001-03-01 03:55:35 +00001481 index = lineno - 1 - start
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001482 else:
1483 lines = index = None
1484
Christian Heimes25bb7832008-01-11 16:17:00 +00001485 return Traceback(filename, lineno, frame.f_code.co_name, lines, index)
Ka-Ping Yee59ade082001-03-01 03:55:35 +00001486
1487def getlineno(frame):
1488 """Get the line number from a frame object, allowing for optimization."""
Michael W. Hudsondd32a912002-08-15 14:59:02 +00001489 # FrameType.f_lineno is now a descriptor that grovels co_lnotab
1490 return frame.f_lineno
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001491
Antoine Pitroucdcafb72014-08-24 10:50:28 -04001492FrameInfo = namedtuple('FrameInfo', ('frame',) + Traceback._fields)
1493
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001494def getouterframes(frame, context=1):
1495 """Get a list of records for a frame and all higher (calling) frames.
1496
1497 Each record contains a frame object, filename, line number, function
1498 name, a list of lines of context, and index within the context."""
1499 framelist = []
1500 while frame:
Antoine Pitroucdcafb72014-08-24 10:50:28 -04001501 frameinfo = (frame,) + getframeinfo(frame, context)
1502 framelist.append(FrameInfo(*frameinfo))
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001503 frame = frame.f_back
1504 return framelist
1505
1506def getinnerframes(tb, context=1):
1507 """Get a list of records for a traceback's frame and all lower frames.
1508
1509 Each record contains a frame object, filename, line number, function
1510 name, a list of lines of context, and index within the context."""
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001511 framelist = []
1512 while tb:
Antoine Pitroucdcafb72014-08-24 10:50:28 -04001513 frameinfo = (tb.tb_frame,) + getframeinfo(tb, context)
1514 framelist.append(FrameInfo(*frameinfo))
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001515 tb = tb.tb_next
1516 return framelist
1517
Benjamin Peterson42ac4752010-08-09 13:05:35 +00001518def currentframe():
Benjamin Petersona3a3fc62010-08-09 15:49:56 +00001519 """Return the frame of the caller or None if this is not possible."""
Benjamin Peterson42ac4752010-08-09 13:05:35 +00001520 return sys._getframe(1) if hasattr(sys, "_getframe") else None
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001521
1522def stack(context=1):
1523 """Return a list of records for the stack above the caller's frame."""
Jeremy Hyltonab919022003-06-27 18:41:20 +00001524 return getouterframes(sys._getframe(1), context)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001525
1526def trace(context=1):
Tim Peters85ba6732001-02-28 08:26:44 +00001527 """Return a list of records for the stack below the current exception."""
Fred Draked451ec12002-04-26 02:29:55 +00001528 return getinnerframes(sys.exc_info()[2], context)
Michael Foord95fc51d2010-11-20 15:07:30 +00001529
1530
1531# ------------------------------------------------ static version of getattr
1532
1533_sentinel = object()
1534
Michael Foorde5162652010-11-20 16:40:44 +00001535def _static_getmro(klass):
1536 return type.__dict__['__mro__'].__get__(klass)
1537
Michael Foord95fc51d2010-11-20 15:07:30 +00001538def _check_instance(obj, attr):
1539 instance_dict = {}
1540 try:
1541 instance_dict = object.__getattribute__(obj, "__dict__")
1542 except AttributeError:
1543 pass
Michael Foorddcebe0f2011-03-15 19:20:44 -04001544 return dict.get(instance_dict, attr, _sentinel)
Michael Foord95fc51d2010-11-20 15:07:30 +00001545
1546
1547def _check_class(klass, attr):
Michael Foorde5162652010-11-20 16:40:44 +00001548 for entry in _static_getmro(klass):
Michael Foorda51623b2011-12-18 22:01:40 +00001549 if _shadowed_dict(type(entry)) is _sentinel:
Michael Foorddcebe0f2011-03-15 19:20:44 -04001550 try:
1551 return entry.__dict__[attr]
1552 except KeyError:
1553 pass
Michael Foord95fc51d2010-11-20 15:07:30 +00001554 return _sentinel
1555
Michael Foord35184ed2010-11-20 16:58:30 +00001556def _is_type(obj):
1557 try:
1558 _static_getmro(obj)
1559 except TypeError:
1560 return False
1561 return True
1562
Michael Foorddcebe0f2011-03-15 19:20:44 -04001563def _shadowed_dict(klass):
1564 dict_attr = type.__dict__["__dict__"]
1565 for entry in _static_getmro(klass):
1566 try:
1567 class_dict = dict_attr.__get__(entry)["__dict__"]
1568 except KeyError:
1569 pass
1570 else:
Srinivas Reddy Thatiparthy (శ్రీనివాస్ రెడ్డి తాటిపర్తి)feaefc72018-02-09 15:29:19 +05301571 if not (isinstance(class_dict, types.GetSetDescriptorType) and
Michael Foorddcebe0f2011-03-15 19:20:44 -04001572 class_dict.__name__ == "__dict__" and
1573 class_dict.__objclass__ is entry):
Michael Foorda51623b2011-12-18 22:01:40 +00001574 return class_dict
1575 return _sentinel
Michael Foord95fc51d2010-11-20 15:07:30 +00001576
1577def getattr_static(obj, attr, default=_sentinel):
1578 """Retrieve attributes without triggering dynamic lookup via the
1579 descriptor protocol, __getattr__ or __getattribute__.
1580
1581 Note: this function may not be able to retrieve all attributes
1582 that getattr can fetch (like dynamically created attributes)
1583 and may find attributes that getattr can't (like descriptors
1584 that raise AttributeError). It can also return descriptor objects
1585 instead of instance members in some cases. See the
1586 documentation for details.
1587 """
1588 instance_result = _sentinel
Michael Foord35184ed2010-11-20 16:58:30 +00001589 if not _is_type(obj):
Michael Foordcc7ebb82010-11-20 16:20:16 +00001590 klass = type(obj)
Michael Foorda51623b2011-12-18 22:01:40 +00001591 dict_attr = _shadowed_dict(klass)
1592 if (dict_attr is _sentinel or
Srinivas Reddy Thatiparthy (శ్రీనివాస్ రెడ్డి తాటిపర్తి)feaefc72018-02-09 15:29:19 +05301593 isinstance(dict_attr, types.MemberDescriptorType)):
Michael Foorddcebe0f2011-03-15 19:20:44 -04001594 instance_result = _check_instance(obj, attr)
Michael Foord95fc51d2010-11-20 15:07:30 +00001595 else:
1596 klass = obj
1597
1598 klass_result = _check_class(klass, attr)
1599
1600 if instance_result is not _sentinel and klass_result is not _sentinel:
1601 if (_check_class(type(klass_result), '__get__') is not _sentinel and
1602 _check_class(type(klass_result), '__set__') is not _sentinel):
1603 return klass_result
1604
1605 if instance_result is not _sentinel:
1606 return instance_result
1607 if klass_result is not _sentinel:
1608 return klass_result
1609
1610 if obj is klass:
1611 # for types we check the metaclass too
Michael Foorde5162652010-11-20 16:40:44 +00001612 for entry in _static_getmro(type(klass)):
Michael Foord3ba95f82011-12-22 01:13:37 +00001613 if _shadowed_dict(type(entry)) is _sentinel:
1614 try:
1615 return entry.__dict__[attr]
1616 except KeyError:
1617 pass
Michael Foord95fc51d2010-11-20 15:07:30 +00001618 if default is not _sentinel:
1619 return default
1620 raise AttributeError(attr)
Nick Coghlane0f04652010-11-21 03:44:04 +00001621
1622
Nick Coghlan04e2e3f2012-06-23 19:52:05 +10001623# ------------------------------------------------ generator introspection
1624
Nick Coghlan7921b9f2010-11-30 06:36:04 +00001625GEN_CREATED = 'GEN_CREATED'
1626GEN_RUNNING = 'GEN_RUNNING'
1627GEN_SUSPENDED = 'GEN_SUSPENDED'
1628GEN_CLOSED = 'GEN_CLOSED'
Nick Coghlane0f04652010-11-21 03:44:04 +00001629
1630def getgeneratorstate(generator):
1631 """Get current state of a generator-iterator.
1632
1633 Possible states are:
1634 GEN_CREATED: Waiting to start execution.
1635 GEN_RUNNING: Currently being executed by the interpreter.
1636 GEN_SUSPENDED: Currently suspended at a yield expression.
1637 GEN_CLOSED: Execution has completed.
1638 """
1639 if generator.gi_running:
1640 return GEN_RUNNING
1641 if generator.gi_frame is None:
1642 return GEN_CLOSED
1643 if generator.gi_frame.f_lasti == -1:
1644 return GEN_CREATED
1645 return GEN_SUSPENDED
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07001646
1647
Nick Coghlan04e2e3f2012-06-23 19:52:05 +10001648def getgeneratorlocals(generator):
1649 """
1650 Get the mapping of generator local variables to their current values.
1651
1652 A dict is returned, with the keys the local variable names and values the
1653 bound values."""
1654
1655 if not isgenerator(generator):
Serhiy Storchakaa4a30202017-11-28 22:54:42 +02001656 raise TypeError("{!r} is not a Python generator".format(generator))
Nick Coghlan04e2e3f2012-06-23 19:52:05 +10001657
1658 frame = getattr(generator, "gi_frame", None)
1659 if frame is not None:
1660 return generator.gi_frame.f_locals
1661 else:
1662 return {}
1663
Yury Selivanov5376ba92015-06-22 12:19:30 -04001664
1665# ------------------------------------------------ coroutine introspection
1666
1667CORO_CREATED = 'CORO_CREATED'
1668CORO_RUNNING = 'CORO_RUNNING'
1669CORO_SUSPENDED = 'CORO_SUSPENDED'
1670CORO_CLOSED = 'CORO_CLOSED'
1671
1672def getcoroutinestate(coroutine):
1673 """Get current state of a coroutine object.
1674
1675 Possible states are:
1676 CORO_CREATED: Waiting to start execution.
1677 CORO_RUNNING: Currently being executed by the interpreter.
1678 CORO_SUSPENDED: Currently suspended at an await expression.
1679 CORO_CLOSED: Execution has completed.
1680 """
1681 if coroutine.cr_running:
1682 return CORO_RUNNING
1683 if coroutine.cr_frame is None:
1684 return CORO_CLOSED
1685 if coroutine.cr_frame.f_lasti == -1:
1686 return CORO_CREATED
1687 return CORO_SUSPENDED
1688
1689
1690def getcoroutinelocals(coroutine):
1691 """
1692 Get the mapping of coroutine local variables to their current values.
1693
1694 A dict is returned, with the keys the local variable names and values the
1695 bound values."""
1696 frame = getattr(coroutine, "cr_frame", None)
1697 if frame is not None:
1698 return frame.f_locals
1699 else:
1700 return {}
1701
1702
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07001703###############################################################################
1704### Function Signature Object (PEP 362)
1705###############################################################################
1706
1707
1708_WrapperDescriptor = type(type.__call__)
1709_MethodWrapper = type(all.__call__)
Larry Hastings5c661892014-01-24 06:17:25 -08001710_ClassMethodWrapper = type(int.__dict__['from_bytes'])
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07001711
1712_NonUserDefinedCallables = (_WrapperDescriptor,
1713 _MethodWrapper,
Larry Hastings5c661892014-01-24 06:17:25 -08001714 _ClassMethodWrapper,
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07001715 types.BuiltinFunctionType)
1716
1717
Yury Selivanov421f0c72014-01-29 12:05:40 -05001718def _signature_get_user_defined_method(cls, method_name):
Yury Selivanov5a23bd02014-03-29 13:47:11 -04001719 """Private helper. Checks if ``cls`` has an attribute
1720 named ``method_name`` and returns it only if it is a
1721 pure python function.
1722 """
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07001723 try:
1724 meth = getattr(cls, method_name)
1725 except AttributeError:
1726 return
1727 else:
1728 if not isinstance(meth, _NonUserDefinedCallables):
1729 # Once '__signature__' will be added to 'C'-level
1730 # callables, this check won't be necessary
1731 return meth
1732
1733
Yury Selivanov62560fb2014-01-28 12:26:24 -05001734def _signature_get_partial(wrapped_sig, partial, extra_args=()):
Yury Selivanov5a23bd02014-03-29 13:47:11 -04001735 """Private helper to calculate how 'wrapped_sig' signature will
1736 look like after applying a 'functools.partial' object (or alike)
1737 on it.
1738 """
Yury Selivanov62560fb2014-01-28 12:26:24 -05001739
Yury Selivanov3f73ca22014-04-08 11:30:45 -04001740 old_params = wrapped_sig.parameters
1741 new_params = OrderedDict(old_params.items())
Yury Selivanovda5fe4f2014-01-27 17:28:37 -05001742
1743 partial_args = partial.args or ()
1744 partial_keywords = partial.keywords or {}
1745
1746 if extra_args:
1747 partial_args = extra_args + partial_args
1748
1749 try:
1750 ba = wrapped_sig.bind_partial(*partial_args, **partial_keywords)
1751 except TypeError as ex:
1752 msg = 'partial object {!r} has incorrect arguments'.format(partial)
1753 raise ValueError(msg) from ex
1754
Yury Selivanovda5fe4f2014-01-27 17:28:37 -05001755
Yury Selivanov3f73ca22014-04-08 11:30:45 -04001756 transform_to_kwonly = False
1757 for param_name, param in old_params.items():
1758 try:
1759 arg_value = ba.arguments[param_name]
1760 except KeyError:
1761 pass
1762 else:
1763 if param.kind is _POSITIONAL_ONLY:
1764 # If positional-only parameter is bound by partial,
1765 # it effectively disappears from the signature
1766 new_params.pop(param_name)
1767 continue
1768
1769 if param.kind is _POSITIONAL_OR_KEYWORD:
1770 if param_name in partial_keywords:
1771 # This means that this parameter, and all parameters
1772 # after it should be keyword-only (and var-positional
1773 # should be removed). Here's why. Consider the following
1774 # function:
1775 # foo(a, b, *args, c):
1776 # pass
1777 #
1778 # "partial(foo, a='spam')" will have the following
1779 # signature: "(*, a='spam', b, c)". Because attempting
1780 # to call that partial with "(10, 20)" arguments will
1781 # raise a TypeError, saying that "a" argument received
1782 # multiple values.
1783 transform_to_kwonly = True
1784 # Set the new default value
1785 new_params[param_name] = param.replace(default=arg_value)
1786 else:
1787 # was passed as a positional argument
1788 new_params.pop(param.name)
1789 continue
1790
1791 if param.kind is _KEYWORD_ONLY:
1792 # Set the new default value
1793 new_params[param_name] = param.replace(default=arg_value)
1794
1795 if transform_to_kwonly:
1796 assert param.kind is not _POSITIONAL_ONLY
1797
1798 if param.kind is _POSITIONAL_OR_KEYWORD:
1799 new_param = new_params[param_name].replace(kind=_KEYWORD_ONLY)
1800 new_params[param_name] = new_param
1801 new_params.move_to_end(param_name)
1802 elif param.kind in (_KEYWORD_ONLY, _VAR_KEYWORD):
1803 new_params.move_to_end(param_name)
1804 elif param.kind is _VAR_POSITIONAL:
1805 new_params.pop(param.name)
Yury Selivanovda5fe4f2014-01-27 17:28:37 -05001806
1807 return wrapped_sig.replace(parameters=new_params.values())
1808
1809
Yury Selivanov62560fb2014-01-28 12:26:24 -05001810def _signature_bound_method(sig):
Yury Selivanov5a23bd02014-03-29 13:47:11 -04001811 """Private helper to transform signatures for unbound
1812 functions to bound methods.
1813 """
Yury Selivanov62560fb2014-01-28 12:26:24 -05001814
1815 params = tuple(sig.parameters.values())
1816
1817 if not params or params[0].kind in (_VAR_KEYWORD, _KEYWORD_ONLY):
1818 raise ValueError('invalid method signature')
1819
1820 kind = params[0].kind
1821 if kind in (_POSITIONAL_OR_KEYWORD, _POSITIONAL_ONLY):
1822 # Drop first parameter:
1823 # '(p1, p2[, ...])' -> '(p2[, ...])'
1824 params = params[1:]
1825 else:
1826 if kind is not _VAR_POSITIONAL:
1827 # Unless we add a new parameter type we never
1828 # get here
1829 raise ValueError('invalid argument type')
1830 # It's a var-positional parameter.
1831 # Do nothing. '(*args[, ...])' -> '(*args[, ...])'
1832
1833 return sig.replace(parameters=params)
1834
1835
Yury Selivanovb77511d2014-01-29 10:46:14 -05001836def _signature_is_builtin(obj):
Yury Selivanov5a23bd02014-03-29 13:47:11 -04001837 """Private helper to test if `obj` is a callable that might
1838 support Argument Clinic's __text_signature__ protocol.
1839 """
Yury Selivanov1d241832014-02-02 12:51:20 -05001840 return (isbuiltin(obj) or
Yury Selivanovb77511d2014-01-29 10:46:14 -05001841 ismethoddescriptor(obj) or
Yury Selivanov1d241832014-02-02 12:51:20 -05001842 isinstance(obj, _NonUserDefinedCallables) or
Yury Selivanovb77511d2014-01-29 10:46:14 -05001843 # Can't test 'isinstance(type)' here, as it would
1844 # also be True for regular python classes
1845 obj in (type, object))
1846
1847
Yury Selivanov63da7c72014-01-31 14:48:37 -05001848def _signature_is_functionlike(obj):
Yury Selivanov5a23bd02014-03-29 13:47:11 -04001849 """Private helper to test if `obj` is a duck type of FunctionType.
1850 A good example of such objects are functions compiled with
1851 Cython, which have all attributes that a pure Python function
1852 would have, but have their code statically compiled.
1853 """
Yury Selivanov63da7c72014-01-31 14:48:37 -05001854
1855 if not callable(obj) or isclass(obj):
1856 # All function-like objects are obviously callables,
1857 # and not classes.
1858 return False
1859
1860 name = getattr(obj, '__name__', None)
1861 code = getattr(obj, '__code__', None)
1862 defaults = getattr(obj, '__defaults__', _void) # Important to use _void ...
1863 kwdefaults = getattr(obj, '__kwdefaults__', _void) # ... and not None here
1864 annotations = getattr(obj, '__annotations__', None)
1865
1866 return (isinstance(code, types.CodeType) and
1867 isinstance(name, str) and
1868 (defaults is None or isinstance(defaults, tuple)) and
1869 (kwdefaults is None or isinstance(kwdefaults, dict)) and
1870 isinstance(annotations, dict))
1871
1872
Yury Selivanovd82eddc2014-01-29 11:24:39 -05001873def _signature_get_bound_param(spec):
Yury Selivanov5a23bd02014-03-29 13:47:11 -04001874 """ Private helper to get first parameter name from a
1875 __text_signature__ of a builtin method, which should
1876 be in the following format: '($param1, ...)'.
1877 Assumptions are that the first argument won't have
1878 a default value or an annotation.
1879 """
Yury Selivanovd82eddc2014-01-29 11:24:39 -05001880
1881 assert spec.startswith('($')
1882
1883 pos = spec.find(',')
1884 if pos == -1:
1885 pos = spec.find(')')
1886
1887 cpos = spec.find(':')
1888 assert cpos == -1 or cpos > pos
1889
1890 cpos = spec.find('=')
1891 assert cpos == -1 or cpos > pos
1892
1893 return spec[2:pos]
1894
1895
Larry Hastings2623c8c2014-02-08 22:15:29 -08001896def _signature_strip_non_python_syntax(signature):
1897 """
Yury Selivanov5a23bd02014-03-29 13:47:11 -04001898 Private helper function. Takes a signature in Argument Clinic's
1899 extended signature format.
1900
Larry Hastings2623c8c2014-02-08 22:15:29 -08001901 Returns a tuple of three things:
1902 * that signature re-rendered in standard Python syntax,
1903 * the index of the "self" parameter (generally 0), or None if
1904 the function does not have a "self" parameter, and
1905 * the index of the last "positional only" parameter,
1906 or None if the signature has no positional-only parameters.
1907 """
1908
1909 if not signature:
1910 return signature, None, None
1911
1912 self_parameter = None
1913 last_positional_only = None
1914
1915 lines = [l.encode('ascii') for l in signature.split('\n')]
1916 generator = iter(lines).__next__
1917 token_stream = tokenize.tokenize(generator)
1918
1919 delayed_comma = False
1920 skip_next_comma = False
1921 text = []
1922 add = text.append
1923
1924 current_parameter = 0
1925 OP = token.OP
1926 ERRORTOKEN = token.ERRORTOKEN
1927
1928 # token stream always starts with ENCODING token, skip it
1929 t = next(token_stream)
1930 assert t.type == tokenize.ENCODING
1931
1932 for t in token_stream:
1933 type, string = t.type, t.string
1934
1935 if type == OP:
1936 if string == ',':
1937 if skip_next_comma:
1938 skip_next_comma = False
1939 else:
1940 assert not delayed_comma
1941 delayed_comma = True
1942 current_parameter += 1
1943 continue
1944
1945 if string == '/':
1946 assert not skip_next_comma
1947 assert last_positional_only is None
1948 skip_next_comma = True
1949 last_positional_only = current_parameter - 1
1950 continue
1951
1952 if (type == ERRORTOKEN) and (string == '$'):
1953 assert self_parameter is None
1954 self_parameter = current_parameter
1955 continue
1956
1957 if delayed_comma:
1958 delayed_comma = False
1959 if not ((type == OP) and (string == ')')):
1960 add(', ')
1961 add(string)
1962 if (string == ','):
1963 add(' ')
1964 clean_signature = ''.join(text)
1965 return clean_signature, self_parameter, last_positional_only
1966
1967
Yury Selivanov57d240e2014-02-19 16:27:23 -05001968def _signature_fromstr(cls, obj, s, skip_bound_arg=True):
Yury Selivanov5a23bd02014-03-29 13:47:11 -04001969 """Private helper to parse content of '__text_signature__'
1970 and return a Signature based on it.
1971 """
INADA Naoki37420de2018-01-27 10:10:06 +09001972 # Lazy import ast because it's relatively heavy and
1973 # it's not used for other than this function.
1974 import ast
Yury Selivanov5a23bd02014-03-29 13:47:11 -04001975
Yury Selivanov7d2bfed2014-02-03 02:46:07 -05001976 Parameter = cls._parameter_cls
1977
Larry Hastings2623c8c2014-02-08 22:15:29 -08001978 clean_signature, self_parameter, last_positional_only = \
1979 _signature_strip_non_python_syntax(s)
Yury Selivanov7d2bfed2014-02-03 02:46:07 -05001980
Larry Hastings2623c8c2014-02-08 22:15:29 -08001981 program = "def foo" + clean_signature + ": pass"
Yury Selivanov7d2bfed2014-02-03 02:46:07 -05001982
1983 try:
Larry Hastings2623c8c2014-02-08 22:15:29 -08001984 module = ast.parse(program)
Yury Selivanov7d2bfed2014-02-03 02:46:07 -05001985 except SyntaxError:
1986 module = None
1987
1988 if not isinstance(module, ast.Module):
1989 raise ValueError("{!r} builtin has invalid signature".format(obj))
1990
1991 f = module.body[0]
1992
1993 parameters = []
1994 empty = Parameter.empty
1995 invalid = object()
1996
1997 module = None
1998 module_dict = {}
1999 module_name = getattr(obj, '__module__', None)
2000 if module_name:
2001 module = sys.modules.get(module_name, None)
2002 if module:
2003 module_dict = module.__dict__
INADA Naoki6f85b822018-10-05 01:47:09 +09002004 sys_module_dict = sys.modules.copy()
Yury Selivanov7d2bfed2014-02-03 02:46:07 -05002005
2006 def parse_name(node):
2007 assert isinstance(node, ast.arg)
Srinivas Reddy Thatiparthy (శ్రీనివాస్ రెడ్డి తాటిపర్తి)feaefc72018-02-09 15:29:19 +05302008 if node.annotation is not None:
Yury Selivanov7d2bfed2014-02-03 02:46:07 -05002009 raise ValueError("Annotations are not currently supported")
2010 return node.arg
2011
2012 def wrap_value(s):
2013 try:
2014 value = eval(s, module_dict)
2015 except NameError:
2016 try:
2017 value = eval(s, sys_module_dict)
2018 except NameError:
2019 raise RuntimeError()
2020
Serhiy Storchaka3f228112018-09-27 17:42:37 +03002021 if isinstance(value, (str, int, float, bytes, bool, type(None))):
2022 return ast.Constant(value)
Yury Selivanov7d2bfed2014-02-03 02:46:07 -05002023 raise RuntimeError()
2024
2025 class RewriteSymbolics(ast.NodeTransformer):
2026 def visit_Attribute(self, node):
2027 a = []
2028 n = node
2029 while isinstance(n, ast.Attribute):
2030 a.append(n.attr)
2031 n = n.value
2032 if not isinstance(n, ast.Name):
2033 raise RuntimeError()
2034 a.append(n.id)
2035 value = ".".join(reversed(a))
2036 return wrap_value(value)
2037
2038 def visit_Name(self, node):
2039 if not isinstance(node.ctx, ast.Load):
2040 raise ValueError()
2041 return wrap_value(node.id)
2042
2043 def p(name_node, default_node, default=empty):
2044 name = parse_name(name_node)
2045 if name is invalid:
2046 return None
2047 if default_node and default_node is not _empty:
2048 try:
2049 default_node = RewriteSymbolics().visit(default_node)
2050 o = ast.literal_eval(default_node)
2051 except ValueError:
2052 o = invalid
2053 if o is invalid:
2054 return None
2055 default = o if o is not invalid else default
2056 parameters.append(Parameter(name, kind, default=default, annotation=empty))
2057
2058 # non-keyword-only parameters
2059 args = reversed(f.args.args)
2060 defaults = reversed(f.args.defaults)
2061 iter = itertools.zip_longest(args, defaults, fillvalue=None)
Larry Hastings2623c8c2014-02-08 22:15:29 -08002062 if last_positional_only is not None:
2063 kind = Parameter.POSITIONAL_ONLY
2064 else:
2065 kind = Parameter.POSITIONAL_OR_KEYWORD
2066 for i, (name, default) in enumerate(reversed(list(iter))):
Yury Selivanov7d2bfed2014-02-03 02:46:07 -05002067 p(name, default)
Larry Hastings2623c8c2014-02-08 22:15:29 -08002068 if i == last_positional_only:
2069 kind = Parameter.POSITIONAL_OR_KEYWORD
Yury Selivanov7d2bfed2014-02-03 02:46:07 -05002070
2071 # *args
2072 if f.args.vararg:
2073 kind = Parameter.VAR_POSITIONAL
2074 p(f.args.vararg, empty)
2075
2076 # keyword-only arguments
2077 kind = Parameter.KEYWORD_ONLY
2078 for name, default in zip(f.args.kwonlyargs, f.args.kw_defaults):
2079 p(name, default)
2080
2081 # **kwargs
2082 if f.args.kwarg:
2083 kind = Parameter.VAR_KEYWORD
2084 p(f.args.kwarg, empty)
2085
Larry Hastings2623c8c2014-02-08 22:15:29 -08002086 if self_parameter is not None:
Yury Selivanov8c185ee2014-02-21 01:32:42 -05002087 # Possibly strip the bound argument:
2088 # - We *always* strip first bound argument if
2089 # it is a module.
2090 # - We don't strip first bound argument if
2091 # skip_bound_arg is False.
Yury Selivanov7d2bfed2014-02-03 02:46:07 -05002092 assert parameters
Yury Selivanov8c185ee2014-02-21 01:32:42 -05002093 _self = getattr(obj, '__self__', None)
2094 self_isbound = _self is not None
2095 self_ismodule = ismodule(_self)
2096 if self_isbound and (self_ismodule or skip_bound_arg):
Yury Selivanov7d2bfed2014-02-03 02:46:07 -05002097 parameters.pop(0)
2098 else:
2099 # for builtins, self parameter is always positional-only!
2100 p = parameters[0].replace(kind=Parameter.POSITIONAL_ONLY)
2101 parameters[0] = p
2102
2103 return cls(parameters, return_annotation=cls.empty)
2104
2105
Yury Selivanov57d240e2014-02-19 16:27:23 -05002106def _signature_from_builtin(cls, func, skip_bound_arg=True):
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002107 """Private helper function to get signature for
2108 builtin callables.
2109 """
2110
Yury Selivanov57d240e2014-02-19 16:27:23 -05002111 if not _signature_is_builtin(func):
2112 raise TypeError("{!r} is not a Python builtin "
2113 "function".format(func))
2114
2115 s = getattr(func, "__text_signature__", None)
2116 if not s:
2117 raise ValueError("no signature found for builtin {!r}".format(func))
2118
2119 return _signature_fromstr(cls, func, s, skip_bound_arg)
2120
2121
Yury Selivanovcf45f022015-05-20 14:38:50 -04002122def _signature_from_function(cls, func):
2123 """Private helper: constructs Signature for the given python function."""
2124
2125 is_duck_function = False
2126 if not isfunction(func):
2127 if _signature_is_functionlike(func):
2128 is_duck_function = True
2129 else:
2130 # If it's not a pure Python function, and not a duck type
2131 # of pure function:
2132 raise TypeError('{!r} is not a Python function'.format(func))
2133
2134 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
2140 positional = tuple(arg_names[:pos_count])
2141 keyword_only_count = func_code.co_kwonlyargcount
2142 keyword_only = arg_names[pos_count:(pos_count + keyword_only_count)]
2143 annotations = func.__annotations__
2144 defaults = func.__defaults__
2145 kwdefaults = func.__kwdefaults__
2146
2147 if defaults:
2148 pos_default_count = len(defaults)
2149 else:
2150 pos_default_count = 0
2151
2152 parameters = []
2153
2154 # Non-keyword-only parameters w/o defaults.
2155 non_default_count = pos_count - pos_default_count
2156 for name in positional[:non_default_count]:
2157 annotation = annotations.get(name, _empty)
2158 parameters.append(Parameter(name, annotation=annotation,
2159 kind=_POSITIONAL_OR_KEYWORD))
2160
2161 # ... w/ defaults.
2162 for offset, name in enumerate(positional[non_default_count:]):
2163 annotation = annotations.get(name, _empty)
2164 parameters.append(Parameter(name, annotation=annotation,
2165 kind=_POSITIONAL_OR_KEYWORD,
2166 default=defaults[offset]))
2167
2168 # *args
2169 if func_code.co_flags & CO_VARARGS:
2170 name = arg_names[pos_count + keyword_only_count]
2171 annotation = annotations.get(name, _empty)
2172 parameters.append(Parameter(name, annotation=annotation,
2173 kind=_VAR_POSITIONAL))
2174
2175 # Keyword-only parameters.
2176 for name in keyword_only:
2177 default = _empty
2178 if kwdefaults is not None:
2179 default = kwdefaults.get(name, _empty)
2180
2181 annotation = annotations.get(name, _empty)
2182 parameters.append(Parameter(name, annotation=annotation,
2183 kind=_KEYWORD_ONLY,
2184 default=default))
2185 # **kwargs
2186 if func_code.co_flags & CO_VARKEYWORDS:
2187 index = pos_count + keyword_only_count
2188 if func_code.co_flags & CO_VARARGS:
2189 index += 1
2190
2191 name = arg_names[index]
2192 annotation = annotations.get(name, _empty)
2193 parameters.append(Parameter(name, annotation=annotation,
2194 kind=_VAR_KEYWORD))
2195
2196 # Is 'func' is a pure Python function - don't validate the
2197 # parameters list (for correct order and defaults), it should be OK.
2198 return cls(parameters,
2199 return_annotation=annotations.get('return', _empty),
2200 __validate_parameters__=is_duck_function)
2201
2202
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002203def _signature_from_callable(obj, *,
2204 follow_wrapper_chains=True,
2205 skip_bound_arg=True,
2206 sigcls):
2207
2208 """Private helper function to get signature for arbitrary
2209 callable objects.
2210 """
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002211
2212 if not callable(obj):
2213 raise TypeError('{!r} is not a callable object'.format(obj))
2214
2215 if isinstance(obj, types.MethodType):
2216 # In this case we skip the first parameter of the underlying
2217 # function (usually `self` or `cls`).
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002218 sig = _signature_from_callable(
Yury Selivanovda396452014-03-27 12:09:24 -04002219 obj.__func__,
2220 follow_wrapper_chains=follow_wrapper_chains,
2221 skip_bound_arg=skip_bound_arg,
2222 sigcls=sigcls)
2223
Yury Selivanov57d240e2014-02-19 16:27:23 -05002224 if skip_bound_arg:
2225 return _signature_bound_method(sig)
2226 else:
2227 return sig
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002228
Nick Coghlane8c45d62013-07-28 20:00:01 +10002229 # Was this function wrapped by a decorator?
Yury Selivanov57d240e2014-02-19 16:27:23 -05002230 if follow_wrapper_chains:
2231 obj = unwrap(obj, stop=(lambda f: hasattr(f, "__signature__")))
Yury Selivanov46c759d2015-05-27 21:56:53 -04002232 if isinstance(obj, types.MethodType):
2233 # If the unwrapped object is a *method*, we might want to
2234 # skip its first parameter (self).
2235 # See test_signature_wrapped_bound_method for details.
Yury Selivanov507cd3c2015-05-27 21:59:03 -04002236 return _signature_from_callable(
Yury Selivanov46c759d2015-05-27 21:56:53 -04002237 obj,
2238 follow_wrapper_chains=follow_wrapper_chains,
Yury Selivanov507cd3c2015-05-27 21:59:03 -04002239 skip_bound_arg=skip_bound_arg,
2240 sigcls=sigcls)
Nick Coghlane8c45d62013-07-28 20:00:01 +10002241
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002242 try:
2243 sig = obj.__signature__
2244 except AttributeError:
2245 pass
2246 else:
2247 if sig is not None:
Yury Selivanov42407ab2014-06-23 10:23:50 -07002248 if not isinstance(sig, Signature):
2249 raise TypeError(
2250 'unexpected object {!r} in __signature__ '
2251 'attribute'.format(sig))
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002252 return sig
2253
Yury Selivanovda5fe4f2014-01-27 17:28:37 -05002254 try:
2255 partialmethod = obj._partialmethod
2256 except AttributeError:
2257 pass
2258 else:
Yury Selivanov0486f812014-01-29 12:18:59 -05002259 if isinstance(partialmethod, functools.partialmethod):
2260 # Unbound partialmethod (see functools.partialmethod)
2261 # This means, that we need to calculate the signature
2262 # as if it's a regular partial object, but taking into
2263 # account that the first positional argument
2264 # (usually `self`, or `cls`) will not be passed
2265 # automatically (as for boundmethods)
Yury Selivanovda5fe4f2014-01-27 17:28:37 -05002266
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002267 wrapped_sig = _signature_from_callable(
Yury Selivanovda396452014-03-27 12:09:24 -04002268 partialmethod.func,
2269 follow_wrapper_chains=follow_wrapper_chains,
2270 skip_bound_arg=skip_bound_arg,
2271 sigcls=sigcls)
2272
Yury Selivanov0486f812014-01-29 12:18:59 -05002273 sig = _signature_get_partial(wrapped_sig, partialmethod, (None,))
Yury Selivanov0486f812014-01-29 12:18:59 -05002274 first_wrapped_param = tuple(wrapped_sig.parameters.values())[0]
Dong-hee Na378d7062017-05-18 04:00:51 +09002275 if first_wrapped_param.kind is Parameter.VAR_POSITIONAL:
2276 # First argument of the wrapped callable is `*args`, as in
2277 # `partialmethod(lambda *args)`.
2278 return sig
2279 else:
2280 sig_params = tuple(sig.parameters.values())
Yury Selivanov8a387212018-03-06 12:59:45 -05002281 assert (not sig_params or
2282 first_wrapped_param is not sig_params[0])
Dong-hee Na378d7062017-05-18 04:00:51 +09002283 new_params = (first_wrapped_param,) + sig_params
2284 return sig.replace(parameters=new_params)
Yury Selivanovda5fe4f2014-01-27 17:28:37 -05002285
Yury Selivanov63da7c72014-01-31 14:48:37 -05002286 if isfunction(obj) or _signature_is_functionlike(obj):
2287 # If it's a pure Python function, or an object that is duck type
2288 # of a Python function (Cython functions, for instance), then:
Yury Selivanovcf45f022015-05-20 14:38:50 -04002289 return _signature_from_function(sigcls, obj)
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002290
Yury Selivanova773de02014-02-21 18:30:53 -05002291 if _signature_is_builtin(obj):
Yury Selivanovda396452014-03-27 12:09:24 -04002292 return _signature_from_builtin(sigcls, obj,
Yury Selivanova773de02014-02-21 18:30:53 -05002293 skip_bound_arg=skip_bound_arg)
2294
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002295 if isinstance(obj, functools.partial):
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002296 wrapped_sig = _signature_from_callable(
Yury Selivanovda396452014-03-27 12:09:24 -04002297 obj.func,
2298 follow_wrapper_chains=follow_wrapper_chains,
2299 skip_bound_arg=skip_bound_arg,
2300 sigcls=sigcls)
Yury Selivanov62560fb2014-01-28 12:26:24 -05002301 return _signature_get_partial(wrapped_sig, obj)
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002302
2303 sig = None
2304 if isinstance(obj, type):
2305 # obj is a class or a metaclass
2306
2307 # First, let's see if it has an overloaded __call__ defined
2308 # in its metaclass
Yury Selivanov421f0c72014-01-29 12:05:40 -05002309 call = _signature_get_user_defined_method(type(obj), '__call__')
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002310 if call is not None:
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002311 sig = _signature_from_callable(
Yury Selivanovda396452014-03-27 12:09:24 -04002312 call,
2313 follow_wrapper_chains=follow_wrapper_chains,
2314 skip_bound_arg=skip_bound_arg,
2315 sigcls=sigcls)
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002316 else:
2317 # Now we check if the 'obj' class has a '__new__' method
Yury Selivanov421f0c72014-01-29 12:05:40 -05002318 new = _signature_get_user_defined_method(obj, '__new__')
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002319 if new is not None:
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002320 sig = _signature_from_callable(
Yury Selivanovda396452014-03-27 12:09:24 -04002321 new,
2322 follow_wrapper_chains=follow_wrapper_chains,
2323 skip_bound_arg=skip_bound_arg,
2324 sigcls=sigcls)
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002325 else:
2326 # Finally, we should have at least __init__ implemented
Yury Selivanov421f0c72014-01-29 12:05:40 -05002327 init = _signature_get_user_defined_method(obj, '__init__')
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002328 if init is not None:
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002329 sig = _signature_from_callable(
Yury Selivanovda396452014-03-27 12:09:24 -04002330 init,
2331 follow_wrapper_chains=follow_wrapper_chains,
2332 skip_bound_arg=skip_bound_arg,
2333 sigcls=sigcls)
Yury Selivanove7dcc5e2014-01-27 19:29:45 -05002334
2335 if sig is None:
Yury Selivanov7d2bfed2014-02-03 02:46:07 -05002336 # At this point we know, that `obj` is a class, with no user-
2337 # defined '__init__', '__new__', or class-level '__call__'
2338
Larry Hastings2623c8c2014-02-08 22:15:29 -08002339 for base in obj.__mro__[:-1]:
Yury Selivanov7d2bfed2014-02-03 02:46:07 -05002340 # Since '__text_signature__' is implemented as a
2341 # descriptor that extracts text signature from the
2342 # class docstring, if 'obj' is derived from a builtin
2343 # class, its own '__text_signature__' may be 'None'.
Larry Hastings2623c8c2014-02-08 22:15:29 -08002344 # Therefore, we go through the MRO (except the last
2345 # class in there, which is 'object') to find the first
Yury Selivanov7d2bfed2014-02-03 02:46:07 -05002346 # class with non-empty text signature.
2347 try:
2348 text_sig = base.__text_signature__
2349 except AttributeError:
2350 pass
2351 else:
2352 if text_sig:
2353 # If 'obj' class has a __text_signature__ attribute:
2354 # return a signature based on it
Yury Selivanovda396452014-03-27 12:09:24 -04002355 return _signature_fromstr(sigcls, obj, text_sig)
Yury Selivanov7d2bfed2014-02-03 02:46:07 -05002356
2357 # No '__text_signature__' was found for the 'obj' class.
2358 # Last option is to check if its '__init__' is
2359 # object.__init__ or type.__init__.
Larry Hastings2623c8c2014-02-08 22:15:29 -08002360 if type not in obj.__mro__:
Yury Selivanove7dcc5e2014-01-27 19:29:45 -05002361 # We have a class (not metaclass), but no user-defined
2362 # __init__ or __new__ for it
Yury Selivanovbf304fc2015-05-30 17:08:36 -04002363 if (obj.__init__ is object.__init__ and
2364 obj.__new__ is object.__new__):
Yury Selivanov7d2bfed2014-02-03 02:46:07 -05002365 # Return a signature of 'object' builtin.
2366 return signature(object)
Yury Selivanovbf304fc2015-05-30 17:08:36 -04002367 else:
2368 raise ValueError(
2369 'no signature found for builtin type {!r}'.format(obj))
Yury Selivanove7dcc5e2014-01-27 19:29:45 -05002370
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002371 elif not isinstance(obj, _NonUserDefinedCallables):
2372 # An object with __call__
2373 # We also check that the 'obj' is not an instance of
2374 # _WrapperDescriptor or _MethodWrapper to avoid
2375 # infinite recursion (and even potential segfault)
Yury Selivanov421f0c72014-01-29 12:05:40 -05002376 call = _signature_get_user_defined_method(type(obj), '__call__')
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002377 if call is not None:
Larry Hastings2623c8c2014-02-08 22:15:29 -08002378 try:
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002379 sig = _signature_from_callable(
Yury Selivanovda396452014-03-27 12:09:24 -04002380 call,
2381 follow_wrapper_chains=follow_wrapper_chains,
2382 skip_bound_arg=skip_bound_arg,
2383 sigcls=sigcls)
Larry Hastings2623c8c2014-02-08 22:15:29 -08002384 except ValueError as ex:
2385 msg = 'no signature found for {!r}'.format(obj)
2386 raise ValueError(msg) from ex
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002387
2388 if sig is not None:
2389 # For classes and objects we skip the first parameter of their
2390 # __call__, __new__, or __init__ methods
Yury Selivanov57d240e2014-02-19 16:27:23 -05002391 if skip_bound_arg:
2392 return _signature_bound_method(sig)
2393 else:
2394 return sig
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002395
2396 if isinstance(obj, types.BuiltinFunctionType):
2397 # Raise a nicer error message for builtins
2398 msg = 'no signature found for builtin function {!r}'.format(obj)
2399 raise ValueError(msg)
2400
2401 raise ValueError('callable {!r} is not supported by signature'.format(obj))
2402
2403
2404class _void:
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002405 """A private marker - used in Parameter & Signature."""
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002406
2407
2408class _empty:
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002409 """Marker object for Signature.empty and Parameter.empty."""
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002410
2411
Yury Selivanov21e83a52014-03-27 11:23:13 -04002412class _ParameterKind(enum.IntEnum):
2413 POSITIONAL_ONLY = 0
2414 POSITIONAL_OR_KEYWORD = 1
2415 VAR_POSITIONAL = 2
2416 KEYWORD_ONLY = 3
2417 VAR_KEYWORD = 4
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002418
2419 def __str__(self):
Yury Selivanov21e83a52014-03-27 11:23:13 -04002420 return self._name_
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002421
Dong-hee Na4aa30062018-06-08 12:46:31 +09002422 @property
2423 def description(self):
2424 return _PARAM_NAME_MAPPING[self]
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002425
Yury Selivanov21e83a52014-03-27 11:23:13 -04002426_POSITIONAL_ONLY = _ParameterKind.POSITIONAL_ONLY
2427_POSITIONAL_OR_KEYWORD = _ParameterKind.POSITIONAL_OR_KEYWORD
2428_VAR_POSITIONAL = _ParameterKind.VAR_POSITIONAL
2429_KEYWORD_ONLY = _ParameterKind.KEYWORD_ONLY
2430_VAR_KEYWORD = _ParameterKind.VAR_KEYWORD
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002431
Dong-hee Naa9cab432018-05-30 00:04:08 +09002432_PARAM_NAME_MAPPING = {
2433 _POSITIONAL_ONLY: 'positional-only',
2434 _POSITIONAL_OR_KEYWORD: 'positional or keyword',
2435 _VAR_POSITIONAL: 'variadic positional',
2436 _KEYWORD_ONLY: 'keyword-only',
2437 _VAR_KEYWORD: 'variadic keyword'
2438}
2439
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002440
2441class Parameter:
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002442 """Represents a parameter in a function signature.
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002443
2444 Has the following public attributes:
2445
2446 * name : str
2447 The name of the parameter as a string.
2448 * default : object
2449 The default value for the parameter if specified. If the
Yury Selivanov8757ead2014-01-28 16:39:25 -05002450 parameter has no default value, this attribute is set to
2451 `Parameter.empty`.
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002452 * annotation
2453 The annotation for the parameter if specified. If the
Yury Selivanov8757ead2014-01-28 16:39:25 -05002454 parameter has no annotation, this attribute is set to
2455 `Parameter.empty`.
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002456 * kind : str
2457 Describes how argument values are bound to the parameter.
2458 Possible values: `Parameter.POSITIONAL_ONLY`,
2459 `Parameter.POSITIONAL_OR_KEYWORD`, `Parameter.VAR_POSITIONAL`,
2460 `Parameter.KEYWORD_ONLY`, `Parameter.VAR_KEYWORD`.
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002461 """
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002462
Yury Selivanov3f73ca22014-04-08 11:30:45 -04002463 __slots__ = ('_name', '_kind', '_default', '_annotation')
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002464
2465 POSITIONAL_ONLY = _POSITIONAL_ONLY
2466 POSITIONAL_OR_KEYWORD = _POSITIONAL_OR_KEYWORD
2467 VAR_POSITIONAL = _VAR_POSITIONAL
2468 KEYWORD_ONLY = _KEYWORD_ONLY
2469 VAR_KEYWORD = _VAR_KEYWORD
2470
2471 empty = _empty
2472
Yury Selivanov3f73ca22014-04-08 11:30:45 -04002473 def __init__(self, name, kind, *, default=_empty, annotation=_empty):
Dong-hee Naa9cab432018-05-30 00:04:08 +09002474 try:
2475 self._kind = _ParameterKind(kind)
2476 except ValueError:
2477 raise ValueError(f'value {kind!r} is not a valid Parameter.kind')
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002478 if default is not _empty:
Dong-hee Naa9cab432018-05-30 00:04:08 +09002479 if self._kind in (_VAR_POSITIONAL, _VAR_KEYWORD):
2480 msg = '{} parameters cannot have default values'
Dong-hee Na4aa30062018-06-08 12:46:31 +09002481 msg = msg.format(self._kind.description)
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002482 raise ValueError(msg)
2483 self._default = default
2484 self._annotation = annotation
2485
Yury Selivanov2393dca2014-01-27 15:07:58 -05002486 if name is _empty:
2487 raise ValueError('name is a required attribute for Parameter')
2488
2489 if not isinstance(name, str):
Dong-hee Naa9cab432018-05-30 00:04:08 +09002490 msg = 'name must be a str, not a {}'.format(type(name).__name__)
2491 raise TypeError(msg)
Yury Selivanov2393dca2014-01-27 15:07:58 -05002492
Nick Coghlanb4b966e2016-06-04 14:40:03 -07002493 if name[0] == '.' and name[1:].isdigit():
2494 # These are implicit arguments generated by comprehensions. In
2495 # order to provide a friendlier interface to users, we recast
2496 # their name as "implicitN" and treat them as positional-only.
2497 # See issue 19611.
Dong-hee Naa9cab432018-05-30 00:04:08 +09002498 if self._kind != _POSITIONAL_OR_KEYWORD:
2499 msg = (
2500 'implicit arguments must be passed as '
2501 'positional or keyword arguments, not {}'
Nick Coghlanb4b966e2016-06-04 14:40:03 -07002502 )
Dong-hee Na4aa30062018-06-08 12:46:31 +09002503 msg = msg.format(self._kind.description)
Dong-hee Naa9cab432018-05-30 00:04:08 +09002504 raise ValueError(msg)
Nick Coghlanb4b966e2016-06-04 14:40:03 -07002505 self._kind = _POSITIONAL_ONLY
2506 name = 'implicit{}'.format(name[1:])
2507
Yury Selivanov2393dca2014-01-27 15:07:58 -05002508 if not name.isidentifier():
2509 raise ValueError('{!r} is not a valid parameter name'.format(name))
2510
2511 self._name = name
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002512
Yury Selivanova5d63dd2014-03-27 11:31:43 -04002513 def __reduce__(self):
2514 return (type(self),
2515 (self._name, self._kind),
Yury Selivanov3f73ca22014-04-08 11:30:45 -04002516 {'_default': self._default,
Yury Selivanova5d63dd2014-03-27 11:31:43 -04002517 '_annotation': self._annotation})
2518
2519 def __setstate__(self, state):
Yury Selivanova5d63dd2014-03-27 11:31:43 -04002520 self._default = state['_default']
2521 self._annotation = state['_annotation']
2522
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002523 @property
2524 def name(self):
2525 return self._name
2526
2527 @property
2528 def default(self):
2529 return self._default
2530
2531 @property
2532 def annotation(self):
2533 return self._annotation
2534
2535 @property
2536 def kind(self):
2537 return self._kind
2538
Yury Selivanov3f73ca22014-04-08 11:30:45 -04002539 def replace(self, *, name=_void, kind=_void,
2540 annotation=_void, default=_void):
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002541 """Creates a customized copy of the Parameter."""
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002542
2543 if name is _void:
2544 name = self._name
2545
2546 if kind is _void:
2547 kind = self._kind
2548
2549 if annotation is _void:
2550 annotation = self._annotation
2551
2552 if default is _void:
2553 default = self._default
2554
Yury Selivanov3f73ca22014-04-08 11:30:45 -04002555 return type(self)(name, kind, default=default, annotation=annotation)
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002556
2557 def __str__(self):
2558 kind = self.kind
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002559 formatted = self._name
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002560
2561 # Add annotation and default value
2562 if self._annotation is not _empty:
Dong-hee Na762b9572017-11-16 03:30:59 +09002563 formatted = '{}: {}'.format(formatted,
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002564 formatannotation(self._annotation))
2565
2566 if self._default is not _empty:
Dong-hee Na762b9572017-11-16 03:30:59 +09002567 if self._annotation is not _empty:
2568 formatted = '{} = {}'.format(formatted, repr(self._default))
2569 else:
2570 formatted = '{}={}'.format(formatted, repr(self._default))
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002571
2572 if kind == _VAR_POSITIONAL:
2573 formatted = '*' + formatted
2574 elif kind == _VAR_KEYWORD:
2575 formatted = '**' + formatted
2576
2577 return formatted
2578
2579 def __repr__(self):
Yury Selivanovf229bc52015-05-15 12:53:56 -04002580 return '<{} "{}">'.format(self.__class__.__name__, self)
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002581
Yury Selivanov67ae50e2014-04-08 11:46:50 -04002582 def __hash__(self):
Yury Selivanov08d4a4f2014-09-12 15:48:02 -04002583 return hash((self.name, self.kind, self.annotation, self.default))
Yury Selivanov67ae50e2014-04-08 11:46:50 -04002584
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002585 def __eq__(self, other):
Serhiy Storchaka2489bd52015-07-18 23:20:50 +03002586 if self is other:
2587 return True
Serhiy Storchaka3018cc42015-07-18 23:19:05 +03002588 if not isinstance(other, Parameter):
2589 return NotImplemented
2590 return (self._name == other._name and
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002591 self._kind == other._kind and
2592 self._default == other._default and
2593 self._annotation == other._annotation)
2594
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002595
2596class BoundArguments:
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002597 """Result of `Signature.bind` call. Holds the mapping of arguments
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002598 to the function's parameters.
2599
2600 Has the following public attributes:
2601
2602 * arguments : OrderedDict
2603 An ordered mutable mapping of parameters' names to arguments' values.
2604 Does not contain arguments' default values.
2605 * signature : Signature
2606 The Signature object that created this instance.
2607 * args : tuple
2608 Tuple of positional arguments values.
2609 * kwargs : dict
2610 Dict of keyword arguments values.
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002611 """
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002612
Yury Selivanov6abe0322015-05-13 17:18:41 -04002613 __slots__ = ('arguments', '_signature', '__weakref__')
2614
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002615 def __init__(self, signature, arguments):
2616 self.arguments = arguments
2617 self._signature = signature
2618
2619 @property
2620 def signature(self):
2621 return self._signature
2622
2623 @property
2624 def args(self):
2625 args = []
2626 for param_name, param in self._signature.parameters.items():
Yury Selivanov3f73ca22014-04-08 11:30:45 -04002627 if param.kind in (_VAR_KEYWORD, _KEYWORD_ONLY):
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002628 break
2629
2630 try:
2631 arg = self.arguments[param_name]
2632 except KeyError:
2633 # We're done here. Other arguments
2634 # will be mapped in 'BoundArguments.kwargs'
2635 break
2636 else:
2637 if param.kind == _VAR_POSITIONAL:
2638 # *args
2639 args.extend(arg)
2640 else:
2641 # plain argument
2642 args.append(arg)
2643
2644 return tuple(args)
2645
2646 @property
2647 def kwargs(self):
2648 kwargs = {}
2649 kwargs_started = False
2650 for param_name, param in self._signature.parameters.items():
2651 if not kwargs_started:
Yury Selivanov3f73ca22014-04-08 11:30:45 -04002652 if param.kind in (_VAR_KEYWORD, _KEYWORD_ONLY):
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002653 kwargs_started = True
2654 else:
2655 if param_name not in self.arguments:
2656 kwargs_started = True
2657 continue
2658
2659 if not kwargs_started:
2660 continue
2661
2662 try:
2663 arg = self.arguments[param_name]
2664 except KeyError:
2665 pass
2666 else:
2667 if param.kind == _VAR_KEYWORD:
2668 # **kwargs
2669 kwargs.update(arg)
2670 else:
2671 # plain keyword argument
2672 kwargs[param_name] = arg
2673
2674 return kwargs
2675
Yury Selivanovb907a512015-05-16 13:45:09 -04002676 def apply_defaults(self):
2677 """Set default values for missing arguments.
2678
2679 For variable-positional arguments (*args) the default is an
2680 empty tuple.
2681
2682 For variable-keyword arguments (**kwargs) the default is an
2683 empty dict.
2684 """
2685 arguments = self.arguments
Yury Selivanovb907a512015-05-16 13:45:09 -04002686 new_arguments = []
2687 for name, param in self._signature.parameters.items():
2688 try:
2689 new_arguments.append((name, arguments[name]))
2690 except KeyError:
2691 if param.default is not _empty:
2692 val = param.default
2693 elif param.kind is _VAR_POSITIONAL:
2694 val = ()
2695 elif param.kind is _VAR_KEYWORD:
2696 val = {}
2697 else:
2698 # This BoundArguments was likely produced by
2699 # Signature.bind_partial().
2700 continue
2701 new_arguments.append((name, val))
2702 self.arguments = OrderedDict(new_arguments)
2703
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002704 def __eq__(self, other):
Serhiy Storchaka2489bd52015-07-18 23:20:50 +03002705 if self is other:
2706 return True
Serhiy Storchaka3018cc42015-07-18 23:19:05 +03002707 if not isinstance(other, BoundArguments):
2708 return NotImplemented
2709 return (self.signature == other.signature and
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002710 self.arguments == other.arguments)
2711
Yury Selivanov6abe0322015-05-13 17:18:41 -04002712 def __setstate__(self, state):
2713 self._signature = state['_signature']
2714 self.arguments = state['arguments']
2715
2716 def __getstate__(self):
2717 return {'_signature': self._signature, 'arguments': self.arguments}
2718
Yury Selivanov3f6538f2015-05-14 18:47:17 -04002719 def __repr__(self):
2720 args = []
2721 for arg, value in self.arguments.items():
2722 args.append('{}={!r}'.format(arg, value))
Yury Selivanovf229bc52015-05-15 12:53:56 -04002723 return '<{} ({})>'.format(self.__class__.__name__, ', '.join(args))
Yury Selivanov3f6538f2015-05-14 18:47:17 -04002724
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002725
2726class Signature:
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002727 """A Signature object represents the overall signature of a function.
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002728 It stores a Parameter object for each parameter accepted by the
2729 function, as well as information specific to the function itself.
2730
2731 A Signature object has the following public attributes and methods:
2732
2733 * parameters : OrderedDict
2734 An ordered mapping of parameters' names to the corresponding
2735 Parameter objects (keyword-only arguments are in the same order
2736 as listed in `code.co_varnames`).
2737 * return_annotation : object
2738 The annotation for the return type of the function if specified.
2739 If the function has no annotation for its return type, this
Yury Selivanov8757ead2014-01-28 16:39:25 -05002740 attribute is set to `Signature.empty`.
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002741 * bind(*args, **kwargs) -> BoundArguments
2742 Creates a mapping from positional and keyword arguments to
2743 parameters.
2744 * bind_partial(*args, **kwargs) -> BoundArguments
2745 Creates a partial mapping from positional and keyword arguments
2746 to parameters (simulating 'functools.partial' behavior.)
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002747 """
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002748
2749 __slots__ = ('_return_annotation', '_parameters')
2750
2751 _parameter_cls = Parameter
2752 _bound_arguments_cls = BoundArguments
2753
2754 empty = _empty
2755
2756 def __init__(self, parameters=None, *, return_annotation=_empty,
2757 __validate_parameters__=True):
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002758 """Constructs Signature from the given list of Parameter
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002759 objects and 'return_annotation'. All arguments are optional.
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002760 """
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002761
2762 if parameters is None:
2763 params = OrderedDict()
2764 else:
2765 if __validate_parameters__:
2766 params = OrderedDict()
2767 top_kind = _POSITIONAL_ONLY
Yury Selivanov07a9e452014-01-29 10:58:16 -05002768 kind_defaults = False
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002769
2770 for idx, param in enumerate(parameters):
2771 kind = param.kind
Yury Selivanov2393dca2014-01-27 15:07:58 -05002772 name = param.name
2773
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002774 if kind < top_kind:
Dong-hee Naa9cab432018-05-30 00:04:08 +09002775 msg = (
2776 'wrong parameter order: {} parameter before {} '
2777 'parameter'
2778 )
Dong-hee Na4aa30062018-06-08 12:46:31 +09002779 msg = msg.format(top_kind.description,
2780 kind.description)
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002781 raise ValueError(msg)
Yury Selivanov07a9e452014-01-29 10:58:16 -05002782 elif kind > top_kind:
2783 kind_defaults = False
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002784 top_kind = kind
2785
Yury Selivanov3f73ca22014-04-08 11:30:45 -04002786 if kind in (_POSITIONAL_ONLY, _POSITIONAL_OR_KEYWORD):
Yury Selivanov07a9e452014-01-29 10:58:16 -05002787 if param.default is _empty:
2788 if kind_defaults:
2789 # No default for this parameter, but the
2790 # previous parameter of the same kind had
2791 # a default
2792 msg = 'non-default argument follows default ' \
2793 'argument'
2794 raise ValueError(msg)
2795 else:
2796 # There is a default for this parameter.
2797 kind_defaults = True
2798
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002799 if name in params:
2800 msg = 'duplicate parameter name: {!r}'.format(name)
2801 raise ValueError(msg)
Yury Selivanov2393dca2014-01-27 15:07:58 -05002802
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002803 params[name] = param
2804 else:
2805 params = OrderedDict(((param.name, param)
2806 for param in parameters))
2807
2808 self._parameters = types.MappingProxyType(params)
2809 self._return_annotation = return_annotation
2810
2811 @classmethod
2812 def from_function(cls, func):
Matthias Bussonnierded87d82018-10-19 16:40:45 -07002813 """Constructs Signature for the given python function.
Yury Selivanov57c74fc2015-05-20 23:07:02 -04002814
Matthias Bussonnierded87d82018-10-19 16:40:45 -07002815 Deprecated since Python 3.5, use `Signature.from_callable()`.
2816 """
2817
2818 warnings.warn("inspect.Signature.from_function() is deprecated since "
2819 "Python 3.5, use Signature.from_callable()",
Berker Peksagb5601582015-05-21 23:40:54 +03002820 DeprecationWarning, stacklevel=2)
Yury Selivanovcf45f022015-05-20 14:38:50 -04002821 return _signature_from_function(cls, func)
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002822
Larry Hastings44e2eaa2013-11-23 15:37:55 -08002823 @classmethod
2824 def from_builtin(cls, func):
Matthias Bussonnierded87d82018-10-19 16:40:45 -07002825 """Constructs Signature for the given builtin function.
Yury Selivanov57c74fc2015-05-20 23:07:02 -04002826
Matthias Bussonnierded87d82018-10-19 16:40:45 -07002827 Deprecated since Python 3.5, use `Signature.from_callable()`.
2828 """
2829
2830 warnings.warn("inspect.Signature.from_builtin() is deprecated since "
2831 "Python 3.5, use Signature.from_callable()",
Berker Peksagb5601582015-05-21 23:40:54 +03002832 DeprecationWarning, stacklevel=2)
Yury Selivanov57d240e2014-02-19 16:27:23 -05002833 return _signature_from_builtin(cls, func)
Larry Hastings44e2eaa2013-11-23 15:37:55 -08002834
Yury Selivanovda396452014-03-27 12:09:24 -04002835 @classmethod
Yury Selivanovbcd4fc12015-05-20 14:30:08 -04002836 def from_callable(cls, obj, *, follow_wrapped=True):
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002837 """Constructs Signature for the given callable object."""
Yury Selivanovbcd4fc12015-05-20 14:30:08 -04002838 return _signature_from_callable(obj, sigcls=cls,
2839 follow_wrapper_chains=follow_wrapped)
Yury Selivanovda396452014-03-27 12:09:24 -04002840
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002841 @property
2842 def parameters(self):
2843 return self._parameters
2844
2845 @property
2846 def return_annotation(self):
2847 return self._return_annotation
2848
2849 def replace(self, *, parameters=_void, return_annotation=_void):
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002850 """Creates a customized copy of the Signature.
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002851 Pass 'parameters' and/or 'return_annotation' arguments
2852 to override them in the new copy.
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002853 """
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002854
2855 if parameters is _void:
2856 parameters = self.parameters.values()
2857
2858 if return_annotation is _void:
2859 return_annotation = self._return_annotation
2860
2861 return type(self)(parameters,
2862 return_annotation=return_annotation)
2863
Yury Selivanov08d4a4f2014-09-12 15:48:02 -04002864 def _hash_basis(self):
2865 params = tuple(param for param in self.parameters.values()
2866 if param.kind != _KEYWORD_ONLY)
2867
2868 kwo_params = {param.name: param for param in self.parameters.values()
2869 if param.kind == _KEYWORD_ONLY}
2870
2871 return params, kwo_params, self.return_annotation
2872
Yury Selivanov67ae50e2014-04-08 11:46:50 -04002873 def __hash__(self):
Yury Selivanov08d4a4f2014-09-12 15:48:02 -04002874 params, kwo_params, return_annotation = self._hash_basis()
2875 kwo_params = frozenset(kwo_params.values())
2876 return hash((params, kwo_params, return_annotation))
Yury Selivanov67ae50e2014-04-08 11:46:50 -04002877
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002878 def __eq__(self, other):
Serhiy Storchaka2489bd52015-07-18 23:20:50 +03002879 if self is other:
2880 return True
Serhiy Storchaka3018cc42015-07-18 23:19:05 +03002881 if not isinstance(other, Signature):
2882 return NotImplemented
Serhiy Storchaka2489bd52015-07-18 23:20:50 +03002883 return self._hash_basis() == other._hash_basis()
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002884
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002885 def _bind(self, args, kwargs, *, partial=False):
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002886 """Private method. Don't use directly."""
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002887
2888 arguments = OrderedDict()
2889
2890 parameters = iter(self.parameters.values())
2891 parameters_ex = ()
2892 arg_vals = iter(args)
2893
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002894 while True:
2895 # Let's iterate through the positional arguments and corresponding
2896 # parameters
2897 try:
2898 arg_val = next(arg_vals)
2899 except StopIteration:
2900 # No more positional arguments
2901 try:
2902 param = next(parameters)
2903 except StopIteration:
2904 # No more parameters. That's it. Just need to check that
2905 # we have no `kwargs` after this while loop
2906 break
2907 else:
2908 if param.kind == _VAR_POSITIONAL:
2909 # That's OK, just empty *args. Let's start parsing
2910 # kwargs
2911 break
2912 elif param.name in kwargs:
2913 if param.kind == _POSITIONAL_ONLY:
2914 msg = '{arg!r} parameter is positional only, ' \
2915 'but was passed as a keyword'
2916 msg = msg.format(arg=param.name)
2917 raise TypeError(msg) from None
2918 parameters_ex = (param,)
2919 break
2920 elif (param.kind == _VAR_KEYWORD or
2921 param.default is not _empty):
2922 # That's fine too - we have a default value for this
2923 # parameter. So, lets start parsing `kwargs`, starting
2924 # with the current parameter
2925 parameters_ex = (param,)
2926 break
2927 else:
Yury Selivanov38b0d5a2014-01-28 17:27:39 -05002928 # No default, not VAR_KEYWORD, not VAR_POSITIONAL,
2929 # not in `kwargs`
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002930 if partial:
2931 parameters_ex = (param,)
2932 break
2933 else:
Yury Selivanov86872752015-05-19 00:27:49 -04002934 msg = 'missing a required argument: {arg!r}'
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002935 msg = msg.format(arg=param.name)
2936 raise TypeError(msg) from None
2937 else:
2938 # We have a positional argument to process
2939 try:
2940 param = next(parameters)
2941 except StopIteration:
2942 raise TypeError('too many positional arguments') from None
2943 else:
2944 if param.kind in (_VAR_KEYWORD, _KEYWORD_ONLY):
2945 # Looks like we have no parameter for this positional
2946 # argument
Yury Selivanov86872752015-05-19 00:27:49 -04002947 raise TypeError(
2948 'too many positional arguments') from None
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002949
2950 if param.kind == _VAR_POSITIONAL:
2951 # We have an '*args'-like argument, let's fill it with
2952 # all positional arguments we have left and move on to
2953 # the next phase
2954 values = [arg_val]
2955 values.extend(arg_vals)
2956 arguments[param.name] = tuple(values)
2957 break
2958
2959 if param.name in kwargs:
Yury Selivanov86872752015-05-19 00:27:49 -04002960 raise TypeError(
2961 'multiple values for argument {arg!r}'.format(
2962 arg=param.name)) from None
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002963
2964 arguments[param.name] = arg_val
2965
2966 # Now, we iterate through the remaining parameters to process
2967 # keyword arguments
2968 kwargs_param = None
2969 for param in itertools.chain(parameters_ex, parameters):
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002970 if param.kind == _VAR_KEYWORD:
2971 # Memorize that we have a '**kwargs'-like parameter
2972 kwargs_param = param
2973 continue
2974
Yury Selivanov38b0d5a2014-01-28 17:27:39 -05002975 if param.kind == _VAR_POSITIONAL:
2976 # Named arguments don't refer to '*args'-like parameters.
2977 # We only arrive here if the positional arguments ended
2978 # before reaching the last parameter before *args.
2979 continue
2980
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002981 param_name = param.name
2982 try:
2983 arg_val = kwargs.pop(param_name)
2984 except KeyError:
2985 # We have no value for this parameter. It's fine though,
2986 # if it has a default value, or it is an '*args'-like
2987 # parameter, left alone by the processing of positional
2988 # arguments.
2989 if (not partial and param.kind != _VAR_POSITIONAL and
2990 param.default is _empty):
Yury Selivanov86872752015-05-19 00:27:49 -04002991 raise TypeError('missing a required argument: {arg!r}'. \
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002992 format(arg=param_name)) from None
2993
2994 else:
Yury Selivanov9b9ac952014-01-28 20:54:28 -05002995 if param.kind == _POSITIONAL_ONLY:
2996 # This should never happen in case of a properly built
2997 # Signature object (but let's have this check here
2998 # to ensure correct behaviour just in case)
2999 raise TypeError('{arg!r} parameter is positional only, '
3000 'but was passed as a keyword'. \
3001 format(arg=param.name))
3002
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07003003 arguments[param_name] = arg_val
3004
3005 if kwargs:
3006 if kwargs_param is not None:
3007 # Process our '**kwargs'-like parameter
3008 arguments[kwargs_param.name] = kwargs
3009 else:
Yury Selivanov86872752015-05-19 00:27:49 -04003010 raise TypeError(
3011 'got an unexpected keyword argument {arg!r}'.format(
3012 arg=next(iter(kwargs))))
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07003013
3014 return self._bound_arguments_cls(self, arguments)
3015
Yury Selivanovc45873e2014-01-29 12:10:27 -05003016 def bind(*args, **kwargs):
Yury Selivanov5a23bd02014-03-29 13:47:11 -04003017 """Get a BoundArguments object, that maps the passed `args`
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07003018 and `kwargs` to the function's signature. Raises `TypeError`
3019 if the passed arguments can not be bound.
Yury Selivanov5a23bd02014-03-29 13:47:11 -04003020 """
Yury Selivanovc45873e2014-01-29 12:10:27 -05003021 return args[0]._bind(args[1:], kwargs)
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07003022
Yury Selivanovc45873e2014-01-29 12:10:27 -05003023 def bind_partial(*args, **kwargs):
Yury Selivanov5a23bd02014-03-29 13:47:11 -04003024 """Get a BoundArguments object, that partially maps the
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07003025 passed `args` and `kwargs` to the function's signature.
3026 Raises `TypeError` if the passed arguments can not be bound.
Yury Selivanov5a23bd02014-03-29 13:47:11 -04003027 """
Yury Selivanovc45873e2014-01-29 12:10:27 -05003028 return args[0]._bind(args[1:], kwargs, partial=True)
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07003029
Yury Selivanova5d63dd2014-03-27 11:31:43 -04003030 def __reduce__(self):
3031 return (type(self),
3032 (tuple(self._parameters.values()),),
3033 {'_return_annotation': self._return_annotation})
3034
3035 def __setstate__(self, state):
3036 self._return_annotation = state['_return_annotation']
3037
Yury Selivanov374375d2014-03-27 12:41:53 -04003038 def __repr__(self):
Yury Selivanovf229bc52015-05-15 12:53:56 -04003039 return '<{} {}>'.format(self.__class__.__name__, self)
Yury Selivanov374375d2014-03-27 12:41:53 -04003040
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07003041 def __str__(self):
3042 result = []
Yury Selivanov2393dca2014-01-27 15:07:58 -05003043 render_pos_only_separator = False
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07003044 render_kw_only_separator = True
Yury Selivanov2393dca2014-01-27 15:07:58 -05003045 for param in self.parameters.values():
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07003046 formatted = str(param)
3047
3048 kind = param.kind
Yury Selivanov2393dca2014-01-27 15:07:58 -05003049
3050 if kind == _POSITIONAL_ONLY:
3051 render_pos_only_separator = True
3052 elif render_pos_only_separator:
3053 # It's not a positional-only parameter, and the flag
3054 # is set to 'True' (there were pos-only params before.)
3055 result.append('/')
3056 render_pos_only_separator = False
3057
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07003058 if kind == _VAR_POSITIONAL:
3059 # OK, we have an '*args'-like parameter, so we won't need
3060 # a '*' to separate keyword-only arguments
3061 render_kw_only_separator = False
3062 elif kind == _KEYWORD_ONLY and render_kw_only_separator:
3063 # We have a keyword-only parameter to render and we haven't
3064 # rendered an '*args'-like parameter before, so add a '*'
3065 # separator to the parameters list ("foo(arg1, *, arg2)" case)
3066 result.append('*')
3067 # This condition should be only triggered once, so
3068 # reset the flag
3069 render_kw_only_separator = False
3070
3071 result.append(formatted)
3072
Yury Selivanov2393dca2014-01-27 15:07:58 -05003073 if render_pos_only_separator:
3074 # There were only positional-only parameters, hence the
3075 # flag was not reset to 'False'
3076 result.append('/')
3077
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07003078 rendered = '({})'.format(', '.join(result))
3079
3080 if self.return_annotation is not _empty:
3081 anno = formatannotation(self.return_annotation)
3082 rendered += ' -> {}'.format(anno)
3083
3084 return rendered
Nick Coghlanf94a16b2013-09-22 22:46:49 +10003085
Yury Selivanovda396452014-03-27 12:09:24 -04003086
Yury Selivanovbcd4fc12015-05-20 14:30:08 -04003087def signature(obj, *, follow_wrapped=True):
Yury Selivanov5a23bd02014-03-29 13:47:11 -04003088 """Get a signature object for the passed callable."""
Yury Selivanovbcd4fc12015-05-20 14:30:08 -04003089 return Signature.from_callable(obj, follow_wrapped=follow_wrapped)
Yury Selivanovda396452014-03-27 12:09:24 -04003090
3091
Nick Coghlanf94a16b2013-09-22 22:46:49 +10003092def _main():
3093 """ Logic for inspecting an object given at command line """
3094 import argparse
3095 import importlib
3096
3097 parser = argparse.ArgumentParser()
3098 parser.add_argument(
3099 'object',
3100 help="The object to be analysed. "
3101 "It supports the 'module:qualname' syntax")
3102 parser.add_argument(
3103 '-d', '--details', action='store_true',
3104 help='Display info about the module rather than its source code')
3105
3106 args = parser.parse_args()
3107
3108 target = args.object
3109 mod_name, has_attrs, attrs = target.partition(":")
3110 try:
3111 obj = module = importlib.import_module(mod_name)
3112 except Exception as exc:
3113 msg = "Failed to import {} ({}: {})".format(mod_name,
3114 type(exc).__name__,
3115 exc)
3116 print(msg, file=sys.stderr)
3117 exit(2)
3118
3119 if has_attrs:
3120 parts = attrs.split(".")
3121 obj = module
3122 for part in parts:
3123 obj = getattr(obj, part)
3124
3125 if module.__name__ in sys.builtin_module_names:
3126 print("Can't get info for builtin modules.", file=sys.stderr)
3127 exit(1)
3128
3129 if args.details:
3130 print('Target: {}'.format(target))
3131 print('Origin: {}'.format(getsourcefile(module)))
3132 print('Cached: {}'.format(module.__cached__))
3133 if obj is module:
3134 print('Loader: {}'.format(repr(module.__loader__)))
3135 if hasattr(module, '__path__'):
3136 print('Submodule search path: {}'.format(module.__path__))
3137 else:
3138 try:
3139 __, lineno = findsource(obj)
3140 except Exception:
3141 pass
3142 else:
3143 print('Line: {}'.format(lineno))
3144
3145 print('\n')
3146 else:
3147 print(getsource(obj))
3148
3149
3150if __name__ == "__main__":
3151 _main()