blob: cbf38e7d1813c919c5552ca37c43a72b4cbbc885 [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
Benjamin Peterson25cd7eb2010-03-30 18:42:32 +000019 getargspec(), getargvalues(), getcallargs() - get info about function arguments
Yury Selivanov0cf3ed62014-04-01 10:17:08 -040020 getfullargspec() - same, with support for Python 3 features
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +000021 formatargspec(), formatargvalues() - format an argument spec
22 getouterframes(), getinnerframes() - get info about frames
23 currentframe() - get the current stack frame
24 stack(), trace() - get info about frames on the stack or in a traceback
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
Larry Hastings44e2eaa2013-11-23 15:37:55 -080034import ast
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
113 Data descriptors have both a __get__ and a __set__ attribute. Examples are
114 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)
122 return hasattr(tp, "__set__") and hasattr(tp, "__get__")
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
Christian Heimes7131fd92008-02-19 14:21:46 +0000171def isgeneratorfunction(object):
172 """Return true if the object is a user-defined generator function.
173
174 Generator function objects provides same attributes as functions.
175
Alexander Belopolsky977a6842010-08-16 20:17:07 +0000176 See help(isfunction) for attributes listing."""
Georg Brandlb1441c72009-01-03 22:33:39 +0000177 return bool((isfunction(object) or ismethod(object)) and
Yury Selivanov75445082015-05-11 22:57:16 -0400178 object.__code__.co_flags & CO_GENERATOR and
179 not object.__code__.co_flags & CO_COROUTINE)
180
181def iscoroutinefunction(object):
182 """Return true if the object is a coroutine function.
183
184 Coroutine functions are defined with "async def" syntax,
185 or generators decorated with "types.coroutine".
186 """
187 return bool((isfunction(object) or ismethod(object)) and
188 object.__code__.co_flags & (CO_ITERABLE_COROUTINE |
189 CO_COROUTINE))
190
191def isawaitable(object):
192 """Return true if the object can be used in "await" expression."""
193 return isinstance(object, collections.abc.Awaitable)
Christian Heimes7131fd92008-02-19 14:21:46 +0000194
195def isgenerator(object):
196 """Return true if the object is a generator.
197
198 Generator objects provide these attributes:
Ezio Melotti30b9d5d2013-08-17 15:50:46 +0300199 __iter__ defined to support iteration over container
Christian Heimes7131fd92008-02-19 14:21:46 +0000200 close raises a new GeneratorExit exception inside the
201 generator to terminate the iteration
202 gi_code code object
203 gi_frame frame object or possibly None once the generator has
204 been exhausted
205 gi_running set to 1 when generator is executing, 0 otherwise
206 next return the next item from the container
207 send resumes the generator and "sends" a value that becomes
208 the result of the current yield-expression
209 throw used to raise an exception inside the generator"""
Yury Selivanov75445082015-05-11 22:57:16 -0400210 return (isinstance(object, types.GeneratorType) and
211 not object.gi_code.co_flags & CO_COROUTINE)
212
213def iscoroutine(object):
214 """Return true if the object is a coroutine."""
Yury Selivanovff542232015-05-21 12:03:21 -0400215 return isinstance(object, collections.abc.Coroutine)
Christian Heimes7131fd92008-02-19 14:21:46 +0000216
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000217def istraceback(object):
218 """Return true if the object is a traceback.
219
220 Traceback objects provide these attributes:
221 tb_frame frame object at this level
222 tb_lasti index of last attempted instruction in bytecode
223 tb_lineno current line number in Python source code
224 tb_next next inner traceback object (called by this level)"""
Tim Peters28bc59f2001-09-16 08:40:16 +0000225 return isinstance(object, types.TracebackType)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000226
227def isframe(object):
228 """Return true if the object is a frame object.
229
230 Frame objects provide these attributes:
231 f_back next outer frame object (this frame's caller)
232 f_builtins built-in namespace seen by this frame
233 f_code code object being executed in this frame
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000234 f_globals global namespace seen by this frame
235 f_lasti index of last attempted instruction in bytecode
236 f_lineno current line number in Python source code
237 f_locals local namespace seen by this frame
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000238 f_trace tracing function for this frame, or None"""
Tim Peters28bc59f2001-09-16 08:40:16 +0000239 return isinstance(object, types.FrameType)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000240
241def iscode(object):
242 """Return true if the object is a code object.
243
244 Code objects provide these attributes:
245 co_argcount number of arguments (not including * or ** args)
246 co_code string of raw compiled bytecode
247 co_consts tuple of constants used in the bytecode
248 co_filename name of file in which this code object was created
249 co_firstlineno number of first line in Python source code
250 co_flags bitmap: 1=optimized | 2=newlocals | 4=*arg | 8=**arg
251 co_lnotab encoded mapping of line numbers to bytecode indices
252 co_name name with which this code object was defined
253 co_names tuple of names of local variables
254 co_nlocals number of local variables
255 co_stacksize virtual machine stack space required
256 co_varnames tuple of names of arguments and local variables"""
Tim Peters28bc59f2001-09-16 08:40:16 +0000257 return isinstance(object, types.CodeType)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000258
259def isbuiltin(object):
260 """Return true if the object is a built-in function or method.
261
262 Built-in functions and methods provide these attributes:
263 __doc__ documentation string
264 __name__ original name of this function or method
265 __self__ instance to which a method is bound, or None"""
Tim Peters28bc59f2001-09-16 08:40:16 +0000266 return isinstance(object, types.BuiltinFunctionType)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000267
268def isroutine(object):
269 """Return true if the object is any kind of function or method."""
Tim Peters536d2262001-09-20 05:13:38 +0000270 return (isbuiltin(object)
271 or isfunction(object)
272 or ismethod(object)
273 or ismethoddescriptor(object))
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000274
Christian Heimesbe5b30b2008-03-03 19:18:51 +0000275def isabstract(object):
276 """Return true if the object is an abstract base class (ABC)."""
Benjamin Petersona0dfa822009-11-13 02:25:08 +0000277 return bool(isinstance(object, type) and object.__flags__ & TPFLAGS_IS_ABSTRACT)
Christian Heimesbe5b30b2008-03-03 19:18:51 +0000278
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000279def getmembers(object, predicate=None):
280 """Return all members of an object as (name, value) pairs sorted by name.
281 Optionally, only return members that satisfy a given predicate."""
Antoine Pitrou86a8a9a2011-12-21 09:57:40 +0100282 if isclass(object):
283 mro = (object,) + getmro(object)
284 else:
285 mro = ()
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000286 results = []
Ethan Furmane03ea372013-09-25 07:14:41 -0700287 processed = set()
288 names = dir(object)
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700289 # :dd any DynamicClassAttributes to the list of names if object is a class;
Ethan Furmane03ea372013-09-25 07:14:41 -0700290 # this may result in duplicate entries if, for example, a virtual
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700291 # attribute with the same name as a DynamicClassAttribute exists
Ethan Furmane03ea372013-09-25 07:14:41 -0700292 try:
293 for base in object.__bases__:
294 for k, v in base.__dict__.items():
295 if isinstance(v, types.DynamicClassAttribute):
296 names.append(k)
297 except AttributeError:
298 pass
299 for key in names:
Ethan Furman63c141c2013-10-18 00:27:39 -0700300 # First try to get the value via getattr. Some descriptors don't
301 # like calling their __get__ (see bug #1785), so fall back to
302 # looking in the __dict__.
303 try:
304 value = getattr(object, key)
305 # handle the duplicate key
306 if key in processed:
307 raise AttributeError
308 except AttributeError:
309 for base in mro:
310 if key in base.__dict__:
311 value = base.__dict__[key]
312 break
313 else:
314 # could be a (currently) missing slot member, or a buggy
315 # __dir__; discard and move on
Antoine Pitrou86a8a9a2011-12-21 09:57:40 +0100316 continue
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000317 if not predicate or predicate(value):
318 results.append((key, value))
Ethan Furmane03ea372013-09-25 07:14:41 -0700319 processed.add(key)
320 results.sort(key=lambda pair: pair[0])
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000321 return results
322
Christian Heimes25bb7832008-01-11 16:17:00 +0000323Attribute = namedtuple('Attribute', 'name kind defining_class object')
324
Tim Peters13b49d32001-09-23 02:00:29 +0000325def classify_class_attrs(cls):
326 """Return list of attribute-descriptor tuples.
327
328 For each name in dir(cls), the return list contains a 4-tuple
329 with these elements:
330
331 0. The name (a string).
332
333 1. The kind of attribute this is, one of these strings:
334 'class method' created via classmethod()
335 'static method' created via staticmethod()
336 'property' created via property()
Ethan Furmane03ea372013-09-25 07:14:41 -0700337 'method' any other flavor of method or descriptor
Tim Peters13b49d32001-09-23 02:00:29 +0000338 'data' not a method
339
340 2. The class which defined this attribute (a class).
341
Ethan Furmane03ea372013-09-25 07:14:41 -0700342 3. The object as obtained by calling getattr; if this fails, or if the
343 resulting object does not live anywhere in the class' mro (including
344 metaclasses) then the object is looked up in the defining class's
345 dict (found by walking the mro).
Ethan Furman668dede2013-09-14 18:53:26 -0700346
347 If one of the items in dir(cls) is stored in the metaclass it will now
348 be discovered and not have None be listed as the class in which it was
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700349 defined. Any items whose home class cannot be discovered are skipped.
Tim Peters13b49d32001-09-23 02:00:29 +0000350 """
351
352 mro = getmro(cls)
Ethan Furman668dede2013-09-14 18:53:26 -0700353 metamro = getmro(type(cls)) # for attributes stored in the metaclass
Ethan Furmane03ea372013-09-25 07:14:41 -0700354 metamro = tuple([cls for cls in metamro if cls not in (type, object)])
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700355 class_bases = (cls,) + mro
356 all_bases = class_bases + metamro
Tim Peters13b49d32001-09-23 02:00:29 +0000357 names = dir(cls)
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700358 # :dd any DynamicClassAttributes to the list of names;
Ethan Furmane03ea372013-09-25 07:14:41 -0700359 # this may result in duplicate entries if, for example, a virtual
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700360 # attribute with the same name as a DynamicClassAttribute exists.
Ethan Furman63c141c2013-10-18 00:27:39 -0700361 for base in mro:
Ethan Furmane03ea372013-09-25 07:14:41 -0700362 for k, v in base.__dict__.items():
363 if isinstance(v, types.DynamicClassAttribute):
364 names.append(k)
Tim Peters13b49d32001-09-23 02:00:29 +0000365 result = []
Ethan Furmane03ea372013-09-25 07:14:41 -0700366 processed = set()
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700367
Tim Peters13b49d32001-09-23 02:00:29 +0000368 for name in names:
Antoine Pitrou86a8a9a2011-12-21 09:57:40 +0100369 # Get the object associated with the name, and where it was defined.
Ethan Furmane03ea372013-09-25 07:14:41 -0700370 # Normal objects will be looked up with both getattr and directly in
371 # its class' dict (in case getattr fails [bug #1785], and also to look
372 # for a docstring).
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700373 # For DynamicClassAttributes on the second pass we only look in the
Ethan Furmane03ea372013-09-25 07:14:41 -0700374 # class's dict.
375 #
Tim Peters13b49d32001-09-23 02:00:29 +0000376 # Getting an obj from the __dict__ sometimes reveals more than
377 # using getattr. Static and class methods are dramatic examples.
Antoine Pitrou86a8a9a2011-12-21 09:57:40 +0100378 homecls = None
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700379 get_obj = None
380 dict_obj = None
Ethan Furmane03ea372013-09-25 07:14:41 -0700381 if name not in processed:
382 try:
Ethan Furmana8b07072013-10-18 01:22:08 -0700383 if name == '__dict__':
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700384 raise Exception("__dict__ is special, don't want the proxy")
Ethan Furmane03ea372013-09-25 07:14:41 -0700385 get_obj = getattr(cls, name)
386 except Exception as exc:
387 pass
388 else:
Ethan Furmane03ea372013-09-25 07:14:41 -0700389 homecls = getattr(get_obj, "__objclass__", homecls)
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700390 if homecls not in class_bases:
Ethan Furmane03ea372013-09-25 07:14:41 -0700391 # if the resulting object does not live somewhere in the
Ethan Furman63c141c2013-10-18 00:27:39 -0700392 # mro, drop it and search the mro manually
Ethan Furmane03ea372013-09-25 07:14:41 -0700393 homecls = None
Ethan Furman63c141c2013-10-18 00:27:39 -0700394 last_cls = None
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700395 # first look in the classes
396 for srch_cls in class_bases:
Ethan Furman63c141c2013-10-18 00:27:39 -0700397 srch_obj = getattr(srch_cls, name, None)
Yury Selivanovbf341fb2015-05-21 15:41:57 -0400398 if srch_obj is get_obj:
Ethan Furman63c141c2013-10-18 00:27:39 -0700399 last_cls = srch_cls
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700400 # then check the metaclasses
401 for srch_cls in metamro:
402 try:
403 srch_obj = srch_cls.__getattr__(cls, name)
404 except AttributeError:
405 continue
Yury Selivanovbf341fb2015-05-21 15:41:57 -0400406 if srch_obj is get_obj:
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700407 last_cls = srch_cls
Ethan Furman63c141c2013-10-18 00:27:39 -0700408 if last_cls is not None:
409 homecls = last_cls
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700410 for base in all_bases:
Ethan Furmane03ea372013-09-25 07:14:41 -0700411 if name in base.__dict__:
412 dict_obj = base.__dict__[name]
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700413 if homecls not in metamro:
414 homecls = base
Ethan Furmane03ea372013-09-25 07:14:41 -0700415 break
Ethan Furman63c141c2013-10-18 00:27:39 -0700416 if homecls is None:
417 # unable to locate the attribute anywhere, most likely due to
418 # buggy custom __dir__; discard and move on
419 continue
Yury Selivanovbf341fb2015-05-21 15:41:57 -0400420 obj = get_obj if get_obj is not None else dict_obj
Ethan Furmane03ea372013-09-25 07:14:41 -0700421 # Classify the object or its descriptor.
Ethan Furman63c141c2013-10-18 00:27:39 -0700422 if isinstance(dict_obj, staticmethod):
Tim Peters13b49d32001-09-23 02:00:29 +0000423 kind = "static method"
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700424 obj = dict_obj
Ethan Furman63c141c2013-10-18 00:27:39 -0700425 elif isinstance(dict_obj, classmethod):
Tim Peters13b49d32001-09-23 02:00:29 +0000426 kind = "class method"
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700427 obj = dict_obj
428 elif isinstance(dict_obj, property):
Tim Peters13b49d32001-09-23 02:00:29 +0000429 kind = "property"
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700430 obj = dict_obj
Yury Selivanov0860a0b2014-01-31 14:28:44 -0500431 elif isroutine(obj):
Tim Peters13b49d32001-09-23 02:00:29 +0000432 kind = "method"
Antoine Pitrou86a8a9a2011-12-21 09:57:40 +0100433 else:
Ethan Furmane03ea372013-09-25 07:14:41 -0700434 kind = "data"
Christian Heimes25bb7832008-01-11 16:17:00 +0000435 result.append(Attribute(name, kind, homecls, obj))
Ethan Furmane03ea372013-09-25 07:14:41 -0700436 processed.add(name)
Tim Peters13b49d32001-09-23 02:00:29 +0000437 return result
438
Tim Peterse0b2d7a2001-09-22 06:10:55 +0000439# ----------------------------------------------------------- class helpers
Tim Peterse0b2d7a2001-09-22 06:10:55 +0000440
441def getmro(cls):
442 "Return tuple of base classes (including cls) in method resolution order."
Benjamin Petersonb82c8e52010-11-04 00:38:49 +0000443 return cls.__mro__
Tim Peterse0b2d7a2001-09-22 06:10:55 +0000444
Nick Coghlane8c45d62013-07-28 20:00:01 +1000445# -------------------------------------------------------- function helpers
446
447def unwrap(func, *, stop=None):
448 """Get the object wrapped by *func*.
449
450 Follows the chain of :attr:`__wrapped__` attributes returning the last
451 object in the chain.
452
453 *stop* is an optional callback accepting an object in the wrapper chain
454 as its sole argument that allows the unwrapping to be terminated early if
455 the callback returns a true value. If the callback never returns a true
456 value, the last object in the chain is returned as usual. For example,
457 :func:`signature` uses this to stop unwrapping if any object in the
458 chain has a ``__signature__`` attribute defined.
459
460 :exc:`ValueError` is raised if a cycle is encountered.
461
462 """
463 if stop is None:
464 def _is_wrapper(f):
465 return hasattr(f, '__wrapped__')
466 else:
467 def _is_wrapper(f):
468 return hasattr(f, '__wrapped__') and not stop(f)
469 f = func # remember the original func for error reporting
470 memo = {id(f)} # Memoise by id to tolerate non-hashable objects
471 while _is_wrapper(func):
472 func = func.__wrapped__
473 id_func = id(func)
474 if id_func in memo:
475 raise ValueError('wrapper loop when unwrapping {!r}'.format(f))
476 memo.add(id_func)
477 return func
478
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000479# -------------------------------------------------- source code extraction
480def indentsize(line):
481 """Return the indent size, in spaces, at the start of a line of text."""
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000482 expline = line.expandtabs()
483 return len(expline) - len(expline.lstrip())
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000484
Serhiy Storchaka5cf2b7252015-04-03 22:38:53 +0300485def _findclass(func):
486 cls = sys.modules.get(func.__module__)
487 if cls is None:
488 return None
489 for name in func.__qualname__.split('.')[:-1]:
490 cls = getattr(cls, name)
491 if not isclass(cls):
492 return None
493 return cls
494
495def _finddoc(obj):
496 if isclass(obj):
497 for base in obj.__mro__:
498 if base is not object:
499 try:
500 doc = base.__doc__
501 except AttributeError:
502 continue
503 if doc is not None:
504 return doc
505 return None
506
507 if ismethod(obj):
508 name = obj.__func__.__name__
509 self = obj.__self__
510 if (isclass(self) and
511 getattr(getattr(self, name, None), '__func__') is obj.__func__):
512 # classmethod
513 cls = self
514 else:
515 cls = self.__class__
516 elif isfunction(obj):
517 name = obj.__name__
518 cls = _findclass(obj)
519 if cls is None or getattr(cls, name) is not obj:
520 return None
521 elif isbuiltin(obj):
522 name = obj.__name__
523 self = obj.__self__
524 if (isclass(self) and
525 self.__qualname__ + '.' + name == obj.__qualname__):
526 # classmethod
527 cls = self
528 else:
529 cls = self.__class__
530 elif ismethoddescriptor(obj) or isdatadescriptor(obj):
531 name = obj.__name__
532 cls = obj.__objclass__
533 if getattr(cls, name) is not obj:
534 return None
535 elif isinstance(obj, property):
536 func = f.fget
537 name = func.__name__
538 cls = _findclass(func)
539 if cls is None or getattr(cls, name) is not obj:
540 return None
541 else:
542 return None
543
544 for base in cls.__mro__:
545 try:
546 doc = getattr(base, name).__doc__
547 except AttributeError:
548 continue
549 if doc is not None:
550 return doc
551 return None
552
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000553def getdoc(object):
554 """Get the documentation string for an object.
555
556 All tabs are expanded to spaces. To clean up docstrings that are
557 indented to line up with blocks of code, any whitespace than can be
558 uniformly removed from the second line onwards is removed."""
Tim Peters24008312002-03-17 18:56:20 +0000559 try:
560 doc = object.__doc__
561 except AttributeError:
562 return None
Serhiy Storchaka5cf2b7252015-04-03 22:38:53 +0300563 if doc is None:
564 try:
565 doc = _finddoc(object)
566 except (AttributeError, TypeError):
567 return None
Guido van Rossum3172c5d2007-10-16 18:12:55 +0000568 if not isinstance(doc, str):
Tim Peters24008312002-03-17 18:56:20 +0000569 return None
Georg Brandl0c77a822008-06-10 16:37:50 +0000570 return cleandoc(doc)
571
572def cleandoc(doc):
573 """Clean up indentation from docstrings.
574
575 Any whitespace that can be uniformly removed from the second line
576 onwards is removed."""
Tim Peters24008312002-03-17 18:56:20 +0000577 try:
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000578 lines = doc.expandtabs().split('\n')
Tim Peters24008312002-03-17 18:56:20 +0000579 except UnicodeError:
580 return None
581 else:
Ka-Ping Yeea59ef7b2002-11-30 03:53:15 +0000582 # Find minimum indentation of any non-blank lines after first line.
Christian Heimesa37d4c62007-12-04 23:02:19 +0000583 margin = sys.maxsize
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000584 for line in lines[1:]:
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000585 content = len(line.lstrip())
Ka-Ping Yeea59ef7b2002-11-30 03:53:15 +0000586 if content:
587 indent = len(line) - content
588 margin = min(margin, indent)
589 # Remove indentation.
590 if lines:
591 lines[0] = lines[0].lstrip()
Christian Heimesa37d4c62007-12-04 23:02:19 +0000592 if margin < sys.maxsize:
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000593 for i in range(1, len(lines)): lines[i] = lines[i][margin:]
Ka-Ping Yeea59ef7b2002-11-30 03:53:15 +0000594 # Remove any trailing or leading blank lines.
595 while lines and not lines[-1]:
596 lines.pop()
597 while lines and not lines[0]:
598 lines.pop(0)
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000599 return '\n'.join(lines)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000600
601def getfile(object):
Ka-Ping Yeec113c242001-03-02 02:08:53 +0000602 """Work out which source or compiled file an object was defined in."""
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000603 if ismodule(object):
604 if hasattr(object, '__file__'):
605 return object.__file__
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +0000606 raise TypeError('{!r} is a built-in module'.format(object))
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000607 if isclass(object):
Yury Selivanov2eed8b72014-01-27 13:24:56 -0500608 if hasattr(object, '__module__'):
609 object = sys.modules.get(object.__module__)
610 if hasattr(object, '__file__'):
611 return object.__file__
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +0000612 raise TypeError('{!r} is a built-in class'.format(object))
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000613 if ismethod(object):
Christian Heimesff737952007-11-27 10:40:20 +0000614 object = object.__func__
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000615 if isfunction(object):
Neal Norwitz221085d2007-02-25 20:55:47 +0000616 object = object.__code__
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000617 if istraceback(object):
618 object = object.tb_frame
619 if isframe(object):
620 object = object.f_code
621 if iscode(object):
622 return object.co_filename
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +0000623 raise TypeError('{!r} is not a module, class, method, '
624 'function, traceback, frame, or code object'.format(object))
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000625
Christian Heimes25bb7832008-01-11 16:17:00 +0000626ModuleInfo = namedtuple('ModuleInfo', 'name suffix mode module_type')
627
Ka-Ping Yee4d6fc7f2001-04-10 11:43:00 +0000628def getmoduleinfo(path):
629 """Get the module name, suffix, mode, and module type for a given file."""
Brett Cannoncb66eb02012-05-11 12:58:42 -0400630 warnings.warn('inspect.getmoduleinfo() is deprecated', DeprecationWarning,
631 2)
Brett Cannone4f41de2013-06-16 13:13:40 -0400632 with warnings.catch_warnings():
633 warnings.simplefilter('ignore', PendingDeprecationWarning)
634 import imp
Ka-Ping Yee4d6fc7f2001-04-10 11:43:00 +0000635 filename = os.path.basename(path)
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000636 suffixes = [(-len(suffix), suffix, mode, mtype)
637 for suffix, mode, mtype in imp.get_suffixes()]
Ka-Ping Yee4d6fc7f2001-04-10 11:43:00 +0000638 suffixes.sort() # try longest suffixes first, in case they overlap
639 for neglen, suffix, mode, mtype in suffixes:
640 if filename[neglen:] == suffix:
Christian Heimes25bb7832008-01-11 16:17:00 +0000641 return ModuleInfo(filename[:neglen], suffix, mode, mtype)
Ka-Ping Yee4d6fc7f2001-04-10 11:43:00 +0000642
643def getmodulename(path):
644 """Return the module name for a given file, or None."""
Nick Coghlan76e07702012-07-18 23:14:57 +1000645 fname = os.path.basename(path)
646 # Check for paths that look like an actual module file
647 suffixes = [(-len(suffix), suffix)
648 for suffix in importlib.machinery.all_suffixes()]
649 suffixes.sort() # try longest suffixes first, in case they overlap
650 for neglen, suffix in suffixes:
651 if fname.endswith(suffix):
652 return fname[:neglen]
653 return None
Ka-Ping Yee4d6fc7f2001-04-10 11:43:00 +0000654
Ka-Ping Yeec113c242001-03-02 02:08:53 +0000655def getsourcefile(object):
R. David Murraya1b37402010-06-17 02:04:29 +0000656 """Return the filename that can be used to locate an object's source.
657 Return None if no way can be identified to get the source.
658 """
Ka-Ping Yeec113c242001-03-02 02:08:53 +0000659 filename = getfile(object)
Brett Cannoncb66eb02012-05-11 12:58:42 -0400660 all_bytecode_suffixes = importlib.machinery.DEBUG_BYTECODE_SUFFIXES[:]
661 all_bytecode_suffixes += importlib.machinery.OPTIMIZED_BYTECODE_SUFFIXES[:]
662 if any(filename.endswith(s) for s in all_bytecode_suffixes):
663 filename = (os.path.splitext(filename)[0] +
664 importlib.machinery.SOURCE_SUFFIXES[0])
665 elif any(filename.endswith(s) for s in
666 importlib.machinery.EXTENSION_SUFFIXES):
667 return None
Thomas Wouters477c8d52006-05-27 19:21:47 +0000668 if os.path.exists(filename):
669 return filename
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000670 # only return a non-existent filename if the module has a PEP 302 loader
Brett Cannon4c14b5d2013-05-04 13:56:58 -0400671 if getattr(getmodule(object, filename), '__loader__', None) is not None:
Ka-Ping Yeec113c242001-03-02 02:08:53 +0000672 return filename
R. David Murraya1b37402010-06-17 02:04:29 +0000673 # or it is in the linecache
674 if filename in linecache.cache:
675 return filename
Ka-Ping Yeec113c242001-03-02 02:08:53 +0000676
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000677def getabsfile(object, _filename=None):
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000678 """Return an absolute path to the source or compiled file for an object.
Ka-Ping Yeec113c242001-03-02 02:08:53 +0000679
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000680 The idea is for each object to have a unique origin, so this routine
681 normalizes the result as much as possible."""
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000682 if _filename is None:
683 _filename = getsourcefile(object) or getfile(object)
684 return os.path.normcase(os.path.abspath(_filename))
Ka-Ping Yeec113c242001-03-02 02:08:53 +0000685
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000686modulesbyfile = {}
Thomas Wouters89f507f2006-12-13 04:49:30 +0000687_filesbymodname = {}
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000688
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000689def getmodule(object, _filename=None):
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000690 """Return the module an object was defined in, or None if not found."""
Ka-Ping Yee202c99b2001-04-13 09:15:08 +0000691 if ismodule(object):
692 return object
Johannes Gijsbers93245262004-09-11 15:53:22 +0000693 if hasattr(object, '__module__'):
Ka-Ping Yee8b58b842001-03-01 13:56:16 +0000694 return sys.modules.get(object.__module__)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000695 # Try the filename to modulename cache
696 if _filename is not None and _filename in modulesbyfile:
697 return sys.modules.get(modulesbyfile[_filename])
698 # Try the cache again with the absolute file name
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000699 try:
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000700 file = getabsfile(object, _filename)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000701 except TypeError:
702 return None
Raymond Hettinger54f02222002-06-01 14:18:47 +0000703 if file in modulesbyfile:
Ka-Ping Yeeb38bbbd2003-03-28 16:29:50 +0000704 return sys.modules.get(modulesbyfile[file])
Thomas Wouters89f507f2006-12-13 04:49:30 +0000705 # Update the filename to module name cache and check yet again
706 # Copy sys.modules in order to cope with changes while iterating
Éric Araujoa74f8ef2011-11-29 16:58:53 +0100707 for modname, module in list(sys.modules.items()):
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000708 if ismodule(module) and hasattr(module, '__file__'):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000709 f = module.__file__
710 if f == _filesbymodname.get(modname, None):
711 # Have already mapped this module, so skip it
712 continue
713 _filesbymodname[modname] = f
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000714 f = getabsfile(module)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000715 # Always map to the name the module knows itself by
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000716 modulesbyfile[f] = modulesbyfile[
717 os.path.realpath(f)] = module.__name__
Raymond Hettinger54f02222002-06-01 14:18:47 +0000718 if file in modulesbyfile:
Ka-Ping Yeeb38bbbd2003-03-28 16:29:50 +0000719 return sys.modules.get(modulesbyfile[file])
Thomas Wouters89f507f2006-12-13 04:49:30 +0000720 # Check the main module
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000721 main = sys.modules['__main__']
Brett Cannon4a671fe2003-06-15 22:33:28 +0000722 if not hasattr(object, '__name__'):
723 return None
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000724 if hasattr(main, object.__name__):
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000725 mainobject = getattr(main, object.__name__)
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000726 if mainobject is object:
727 return main
Thomas Wouters89f507f2006-12-13 04:49:30 +0000728 # Check builtins
Georg Brandl1a3284e2007-12-02 09:40:06 +0000729 builtin = sys.modules['builtins']
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000730 if hasattr(builtin, object.__name__):
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000731 builtinobject = getattr(builtin, object.__name__)
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000732 if builtinobject is object:
733 return builtin
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000734
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000735def findsource(object):
736 """Return the entire source file and starting line number for an object.
737
738 The argument may be a module, class, method, function, traceback, frame,
739 or code object. The source code is returned as a list of all the lines
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200740 in the file and the line number indexes a line in that list. An OSError
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000741 is raised if the source code cannot be retrieved."""
Benjamin Peterson9620cc02011-06-11 15:53:11 -0500742
Yury Selivanovef1e7502014-12-08 16:05:34 -0500743 file = getsourcefile(object)
744 if file:
745 # Invalidate cache if needed.
746 linecache.checkcache(file)
747 else:
748 file = getfile(object)
749 # Allow filenames in form of "<something>" to pass through.
750 # `doctest` monkeypatches `linecache` module to enable
751 # inspection, so let `linecache.getlines` to be called.
752 if not (file.startswith('<') and file.endswith('>')):
753 raise OSError('source code not available')
Benjamin Peterson9620cc02011-06-11 15:53:11 -0500754
Thomas Wouters89f507f2006-12-13 04:49:30 +0000755 module = getmodule(object, file)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000756 if module:
757 lines = linecache.getlines(file, module.__dict__)
758 else:
759 lines = linecache.getlines(file)
Neil Schemenauerf06f8532002-03-23 23:51:04 +0000760 if not lines:
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200761 raise OSError('could not get source code')
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000762
763 if ismodule(object):
764 return lines, 0
765
766 if isclass(object):
767 name = object.__name__
Thomas Wouters89f507f2006-12-13 04:49:30 +0000768 pat = re.compile(r'^(\s*)class\s*' + name + r'\b')
769 # make some effort to find the best matching class definition:
770 # use the one with the least indentation, which is the one
771 # that's most probably not inside a function definition.
772 candidates = []
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000773 for i in range(len(lines)):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000774 match = pat.match(lines[i])
775 if match:
776 # if it's at toplevel, it's already the best one
777 if lines[i][0] == 'c':
778 return lines, i
779 # else add whitespace to candidate list
780 candidates.append((match.group(1), i))
781 if candidates:
782 # this will sort by whitespace, and by line number,
783 # less whitespace first
784 candidates.sort()
785 return lines, candidates[0][1]
Jeremy Hyltonab919022003-06-27 18:41:20 +0000786 else:
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200787 raise OSError('could not find class definition')
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000788
789 if ismethod(object):
Christian Heimesff737952007-11-27 10:40:20 +0000790 object = object.__func__
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000791 if isfunction(object):
Neal Norwitz221085d2007-02-25 20:55:47 +0000792 object = object.__code__
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000793 if istraceback(object):
794 object = object.tb_frame
795 if isframe(object):
796 object = object.f_code
797 if iscode(object):
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000798 if not hasattr(object, 'co_firstlineno'):
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200799 raise OSError('could not find function definition')
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000800 lnum = object.co_firstlineno - 1
Johannes Gijsbers1542f342004-12-12 16:46:28 +0000801 pat = re.compile(r'^(\s*def\s)|(.*(?<!\w)lambda(:|\s))|^(\s*@)')
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000802 while lnum > 0:
Ka-Ping Yeea6e59712001-03-10 09:31:55 +0000803 if pat.match(lines[lnum]): break
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000804 lnum = lnum - 1
805 return lines, lnum
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200806 raise OSError('could not find code object')
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000807
808def getcomments(object):
Jeremy Hyltonb4c17c82002-03-28 23:01:56 +0000809 """Get lines of comments immediately preceding an object's source code.
810
811 Returns None when source can't be found.
812 """
813 try:
814 lines, lnum = findsource(object)
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200815 except (OSError, TypeError):
Jeremy Hyltonb4c17c82002-03-28 23:01:56 +0000816 return None
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000817
818 if ismodule(object):
819 # Look for a comment block at the top of the file.
820 start = 0
Ka-Ping Yeeb910efe2001-04-12 13:17:17 +0000821 if lines and lines[0][:2] == '#!': start = 1
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000822 while start < len(lines) and lines[start].strip() in ('', '#'):
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000823 start = start + 1
Ka-Ping Yeeb910efe2001-04-12 13:17:17 +0000824 if start < len(lines) and lines[start][:1] == '#':
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000825 comments = []
826 end = start
827 while end < len(lines) and lines[end][:1] == '#':
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000828 comments.append(lines[end].expandtabs())
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000829 end = end + 1
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000830 return ''.join(comments)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000831
832 # Look for a preceding block of comments at the same indentation.
833 elif lnum > 0:
834 indent = indentsize(lines[lnum])
835 end = lnum - 1
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000836 if end >= 0 and lines[end].lstrip()[:1] == '#' and \
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000837 indentsize(lines[end]) == indent:
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000838 comments = [lines[end].expandtabs().lstrip()]
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000839 if end > 0:
840 end = end - 1
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000841 comment = lines[end].expandtabs().lstrip()
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000842 while comment[:1] == '#' and indentsize(lines[end]) == indent:
843 comments[:0] = [comment]
844 end = end - 1
845 if end < 0: break
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000846 comment = lines[end].expandtabs().lstrip()
847 while comments and comments[0].strip() == '#':
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000848 comments[:1] = []
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000849 while comments and comments[-1].strip() == '#':
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000850 comments[-1:] = []
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000851 return ''.join(comments)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000852
Tim Peters4efb6e92001-06-29 23:51:08 +0000853class EndOfBlock(Exception): pass
854
855class BlockFinder:
856 """Provide a tokeneater() method to detect the end of a code block."""
857 def __init__(self):
858 self.indent = 0
Johannes Gijsbersa5855d52005-03-12 16:37:11 +0000859 self.islambda = False
Johannes Gijsbers1542f342004-12-12 16:46:28 +0000860 self.started = False
861 self.passline = False
Armin Rigodd5c0232005-09-25 11:45:45 +0000862 self.last = 1
Tim Peters4efb6e92001-06-29 23:51:08 +0000863
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000864 def tokeneater(self, type, token, srowcol, erowcol, line):
Tim Peters4efb6e92001-06-29 23:51:08 +0000865 if not self.started:
Armin Rigodd5c0232005-09-25 11:45:45 +0000866 # look for the first "def", "class" or "lambda"
Johannes Gijsbers1542f342004-12-12 16:46:28 +0000867 if token in ("def", "class", "lambda"):
Johannes Gijsbersa5855d52005-03-12 16:37:11 +0000868 if token == "lambda":
869 self.islambda = True
Johannes Gijsbers1542f342004-12-12 16:46:28 +0000870 self.started = True
Armin Rigodd5c0232005-09-25 11:45:45 +0000871 self.passline = True # skip to the end of the line
Tim Peters4efb6e92001-06-29 23:51:08 +0000872 elif type == tokenize.NEWLINE:
Armin Rigodd5c0232005-09-25 11:45:45 +0000873 self.passline = False # stop skipping when a NEWLINE is seen
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000874 self.last = srowcol[0]
Armin Rigodd5c0232005-09-25 11:45:45 +0000875 if self.islambda: # lambdas always end at the first NEWLINE
876 raise EndOfBlock
Johannes Gijsbers1542f342004-12-12 16:46:28 +0000877 elif self.passline:
878 pass
Tim Peters4efb6e92001-06-29 23:51:08 +0000879 elif type == tokenize.INDENT:
880 self.indent = self.indent + 1
Johannes Gijsbers1542f342004-12-12 16:46:28 +0000881 self.passline = True
Tim Peters4efb6e92001-06-29 23:51:08 +0000882 elif type == tokenize.DEDENT:
883 self.indent = self.indent - 1
Armin Rigodd5c0232005-09-25 11:45:45 +0000884 # the end of matching indent/dedent pairs end a block
885 # (note that this only works for "def"/"class" blocks,
886 # not e.g. for "if: else:" or "try: finally:" blocks)
887 if self.indent <= 0:
888 raise EndOfBlock
889 elif self.indent == 0 and type not in (tokenize.COMMENT, tokenize.NL):
890 # any other token on the same indentation level end the previous
891 # block as well, except the pseudo-tokens COMMENT and NL.
892 raise EndOfBlock
Tim Peters4efb6e92001-06-29 23:51:08 +0000893
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000894def getblock(lines):
895 """Extract the block of code at the top of the given list of lines."""
Armin Rigodd5c0232005-09-25 11:45:45 +0000896 blockfinder = BlockFinder()
Tim Peters4efb6e92001-06-29 23:51:08 +0000897 try:
Trent Nelson428de652008-03-18 22:41:35 +0000898 tokens = tokenize.generate_tokens(iter(lines).__next__)
899 for _token in tokens:
900 blockfinder.tokeneater(*_token)
Armin Rigodd5c0232005-09-25 11:45:45 +0000901 except (EndOfBlock, IndentationError):
902 pass
903 return lines[:blockfinder.last]
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000904
Antoine Pitroua8723a02015-04-15 00:41:29 +0200905def _line_number_helper(code_obj, lines, lnum):
906 """Return a list of source lines and starting line number for a code object.
907
908 The arguments must be a code object with lines and lnum from findsource.
909 """
910 _, end_line = list(dis.findlinestarts(code_obj))[-1]
911 return lines[lnum:end_line], lnum + 1
912
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000913def getsourcelines(object):
914 """Return a list of source lines and starting line number for an object.
915
916 The argument may be a module, class, method, function, traceback, frame,
917 or code object. The source code is returned as a list of the lines
918 corresponding to the object and the line number indicates where in the
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200919 original source file the first line of code was found. An OSError is
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000920 raised if the source code cannot be retrieved."""
Yury Selivanov081bbf62014-09-26 17:34:54 -0400921 object = unwrap(object)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000922 lines, lnum = findsource(object)
923
Antoine Pitroua8723a02015-04-15 00:41:29 +0200924 if ismodule(object):
925 return lines, 0
926 elif iscode(object):
927 return _line_number_helper(object, lines, lnum)
928 elif isfunction(object):
929 return _line_number_helper(object.__code__, lines, lnum)
930 elif ismethod(object):
931 return _line_number_helper(object.__func__.__code__, lines, lnum)
932 else:
933 return getblock(lines[lnum:]), lnum + 1
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000934
935def getsource(object):
936 """Return the text of the source code for an object.
937
938 The argument may be a module, class, method, function, traceback, frame,
939 or code object. The source code is returned as a single string. An
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200940 OSError is raised if the source code cannot be retrieved."""
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000941 lines, lnum = getsourcelines(object)
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000942 return ''.join(lines)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000943
944# --------------------------------------------------- class tree extraction
945def walktree(classes, children, parent):
946 """Recursive helper function for getclasstree()."""
947 results = []
Raymond Hettingera1a992c2005-03-11 06:46:45 +0000948 classes.sort(key=attrgetter('__module__', '__name__'))
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000949 for c in classes:
950 results.append((c, c.__bases__))
Raymond Hettinger54f02222002-06-01 14:18:47 +0000951 if c in children:
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000952 results.append(walktree(children[c], children, c))
953 return results
954
Georg Brandl5ce83a02009-06-01 17:23:51 +0000955def getclasstree(classes, unique=False):
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000956 """Arrange the given list of classes into a hierarchy of nested lists.
957
958 Where a nested list appears, it contains classes derived from the class
959 whose entry immediately precedes the list. Each entry is a 2-tuple
960 containing a class and a tuple of its base classes. If the 'unique'
961 argument is true, exactly one entry appears in the returned structure
962 for each class in the given list. Otherwise, classes using multiple
963 inheritance and their descendants will appear multiple times."""
964 children = {}
965 roots = []
966 for c in classes:
967 if c.__bases__:
968 for parent in c.__bases__:
Raymond Hettinger54f02222002-06-01 14:18:47 +0000969 if not parent in children:
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000970 children[parent] = []
Serhiy Storchaka362c1b52013-09-05 17:14:32 +0300971 if c not in children[parent]:
972 children[parent].append(c)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000973 if unique and parent in classes: break
974 elif c not in roots:
975 roots.append(c)
Raymond Hettingere0d49722002-06-02 18:55:56 +0000976 for parent in children:
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000977 if parent not in classes:
978 roots.append(parent)
979 return walktree(roots, children, None)
980
981# ------------------------------------------------ argument list extraction
Christian Heimes25bb7832008-01-11 16:17:00 +0000982Arguments = namedtuple('Arguments', 'args, varargs, varkw')
983
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000984def getargs(co):
985 """Get information about the arguments accepted by a code object.
986
Guido van Rossum2e65f892007-02-28 22:03:49 +0000987 Three things are returned: (args, varargs, varkw), where
Georg Brandlc1c4bf82010-10-15 16:07:41 +0000988 'args' is the list of argument names. Keyword-only arguments are
989 appended. 'varargs' and 'varkw' are the names of the * and **
990 arguments or None."""
Guido van Rossum2e65f892007-02-28 22:03:49 +0000991 args, varargs, kwonlyargs, varkw = _getfullargs(co)
Christian Heimes25bb7832008-01-11 16:17:00 +0000992 return Arguments(args + kwonlyargs, varargs, varkw)
Guido van Rossum2e65f892007-02-28 22:03:49 +0000993
994def _getfullargs(co):
995 """Get information about the arguments accepted by a code object.
996
997 Four things are returned: (args, varargs, kwonlyargs, varkw), where
Georg Brandlc1c4bf82010-10-15 16:07:41 +0000998 'args' and 'kwonlyargs' are lists of argument names, and 'varargs'
999 and 'varkw' are the names of the * and ** arguments or None."""
Jeremy Hylton64967882003-06-27 18:14:39 +00001000
1001 if not iscode(co):
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00001002 raise TypeError('{!r} is not a code object'.format(co))
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001003
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001004 nargs = co.co_argcount
1005 names = co.co_varnames
Guido van Rossum2e65f892007-02-28 22:03:49 +00001006 nkwargs = co.co_kwonlyargcount
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001007 args = list(names[:nargs])
Guido van Rossum2e65f892007-02-28 22:03:49 +00001008 kwonlyargs = list(names[nargs:nargs+nkwargs])
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001009 step = 0
1010
Guido van Rossum2e65f892007-02-28 22:03:49 +00001011 nargs += nkwargs
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001012 varargs = None
1013 if co.co_flags & CO_VARARGS:
1014 varargs = co.co_varnames[nargs]
1015 nargs = nargs + 1
1016 varkw = None
1017 if co.co_flags & CO_VARKEYWORDS:
1018 varkw = co.co_varnames[nargs]
Guido van Rossum2e65f892007-02-28 22:03:49 +00001019 return args, varargs, kwonlyargs, varkw
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001020
Christian Heimes25bb7832008-01-11 16:17:00 +00001021
1022ArgSpec = namedtuple('ArgSpec', 'args varargs keywords defaults')
1023
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001024def getargspec(func):
1025 """Get the names and default values of a function's arguments.
1026
Guido van Rossume82881c2014-07-15 12:29:11 -07001027 A tuple of four things is returned: (args, varargs, keywords, defaults).
1028 'args' is a list of the argument names, including keyword-only argument names.
1029 'varargs' and 'keywords' are the names of the * and ** arguments or None.
Jeremy Hylton64967882003-06-27 18:14:39 +00001030 'defaults' is an n-tuple of the default values of the last n arguments.
Guido van Rossuma8add0e2007-05-14 22:03:55 +00001031
Yury Selivanov0cf3ed62014-04-01 10:17:08 -04001032 Use the getfullargspec() API for Python 3 code, as annotations
Guido van Rossum2e65f892007-02-28 22:03:49 +00001033 and keyword arguments are supported. getargspec() will raise ValueError
1034 if the func has either annotations or keyword arguments.
1035 """
1036
1037 args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults, ann = \
1038 getfullargspec(func)
1039 if kwonlyargs or ann:
Collin Winterce36ad82007-08-30 01:19:48 +00001040 raise ValueError("Function has keyword-only arguments or annotations"
1041 ", use getfullargspec() API which can support them")
Christian Heimes25bb7832008-01-11 16:17:00 +00001042 return ArgSpec(args, varargs, varkw, defaults)
1043
1044FullArgSpec = namedtuple('FullArgSpec',
Benjamin Peterson3d4ca742008-11-12 21:39:01 +00001045 'args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults, annotations')
Guido van Rossum2e65f892007-02-28 22:03:49 +00001046
1047def getfullargspec(func):
Yury Selivanovd82eddc2014-01-29 11:24:39 -05001048 """Get the names and default values of a callable object's arguments.
Guido van Rossum2e65f892007-02-28 22:03:49 +00001049
Brett Cannon504d8852007-09-07 02:12:14 +00001050 A tuple of seven things is returned:
1051 (args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults annotations).
Georg Brandlc1c4bf82010-10-15 16:07:41 +00001052 'args' is a list of the argument names.
Guido van Rossum2e65f892007-02-28 22:03:49 +00001053 'varargs' and 'varkw' are the names of the * and ** arguments or None.
1054 'defaults' is an n-tuple of the default values of the last n arguments.
1055 'kwonlyargs' is a list of keyword-only argument names.
1056 'kwonlydefaults' is a dictionary mapping names from kwonlyargs to defaults.
1057 'annotations' is a dictionary mapping argument names to annotations.
Guido van Rossuma8add0e2007-05-14 22:03:55 +00001058
Guido van Rossum2e65f892007-02-28 22:03:49 +00001059 The first four items in the tuple correspond to getargspec().
Jeremy Hylton64967882003-06-27 18:14:39 +00001060 """
1061
Yury Selivanov57d240e2014-02-19 16:27:23 -05001062 try:
1063 # Re: `skip_bound_arg=False`
1064 #
Yury Selivanovd82eddc2014-01-29 11:24:39 -05001065 # There is a notable difference in behaviour between getfullargspec
1066 # and Signature: the former always returns 'self' parameter for bound
1067 # methods, whereas the Signature always shows the actual calling
1068 # signature of the passed object.
1069 #
1070 # To simulate this behaviour, we "unbind" bound methods, to trick
1071 # inspect.signature to always return their first parameter ("self",
1072 # usually)
Yury Selivanovd82eddc2014-01-29 11:24:39 -05001073
Yury Selivanov57d240e2014-02-19 16:27:23 -05001074 # Re: `follow_wrapper_chains=False`
1075 #
1076 # getfullargspec() historically ignored __wrapped__ attributes,
1077 # so we ensure that remains the case in 3.3+
Yury Selivanovd82eddc2014-01-29 11:24:39 -05001078
Yury Selivanov5a23bd02014-03-29 13:47:11 -04001079 sig = _signature_from_callable(func,
1080 follow_wrapper_chains=False,
1081 skip_bound_arg=False,
1082 sigcls=Signature)
Yury Selivanovd82eddc2014-01-29 11:24:39 -05001083 except Exception as ex:
1084 # Most of the times 'signature' will raise ValueError.
1085 # But, it can also raise AttributeError, and, maybe something
1086 # else. So to be fully backwards compatible, we catch all
1087 # possible exceptions here, and reraise a TypeError.
1088 raise TypeError('unsupported callable') from ex
1089
1090 args = []
1091 varargs = None
1092 varkw = None
1093 kwonlyargs = []
1094 defaults = ()
1095 annotations = {}
1096 defaults = ()
1097 kwdefaults = {}
1098
1099 if sig.return_annotation is not sig.empty:
1100 annotations['return'] = sig.return_annotation
1101
1102 for param in sig.parameters.values():
1103 kind = param.kind
1104 name = param.name
1105
1106 if kind is _POSITIONAL_ONLY:
1107 args.append(name)
1108 elif kind is _POSITIONAL_OR_KEYWORD:
1109 args.append(name)
1110 if param.default is not param.empty:
1111 defaults += (param.default,)
1112 elif kind is _VAR_POSITIONAL:
1113 varargs = name
1114 elif kind is _KEYWORD_ONLY:
1115 kwonlyargs.append(name)
1116 if param.default is not param.empty:
1117 kwdefaults[name] = param.default
1118 elif kind is _VAR_KEYWORD:
1119 varkw = name
1120
1121 if param.annotation is not param.empty:
1122 annotations[name] = param.annotation
1123
1124 if not kwdefaults:
1125 # compatibility with 'func.__kwdefaults__'
1126 kwdefaults = None
1127
1128 if not defaults:
1129 # compatibility with 'func.__defaults__'
1130 defaults = None
1131
Yury Selivanovd82eddc2014-01-29 11:24:39 -05001132 return FullArgSpec(args, varargs, varkw, defaults,
1133 kwonlyargs, kwdefaults, annotations)
1134
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001135
Christian Heimes25bb7832008-01-11 16:17:00 +00001136ArgInfo = namedtuple('ArgInfo', 'args varargs keywords locals')
1137
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001138def getargvalues(frame):
1139 """Get information about arguments passed into a particular frame.
1140
1141 A tuple of four things is returned: (args, varargs, varkw, locals).
Georg Brandlc1c4bf82010-10-15 16:07:41 +00001142 'args' is a list of the argument names.
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001143 'varargs' and 'varkw' are the names of the * and ** arguments or None.
1144 'locals' is the locals dictionary of the given frame."""
1145 args, varargs, varkw = getargs(frame.f_code)
Benjamin Peterson1a6e0d02008-10-25 15:49:17 +00001146 return ArgInfo(args, varargs, varkw, frame.f_locals)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001147
Guido van Rossum2e65f892007-02-28 22:03:49 +00001148def formatannotation(annotation, base_module=None):
1149 if isinstance(annotation, type):
Georg Brandl1a3284e2007-12-02 09:40:06 +00001150 if annotation.__module__ in ('builtins', base_module):
Serhiy Storchaka521e5862014-07-22 15:00:37 +03001151 return annotation.__qualname__
1152 return annotation.__module__+'.'+annotation.__qualname__
Guido van Rossum2e65f892007-02-28 22:03:49 +00001153 return repr(annotation)
Guido van Rossuma8add0e2007-05-14 22:03:55 +00001154
Guido van Rossum2e65f892007-02-28 22:03:49 +00001155def formatannotationrelativeto(object):
Guido van Rossuma8add0e2007-05-14 22:03:55 +00001156 module = getattr(object, '__module__', None)
1157 def _formatannotation(annotation):
1158 return formatannotation(annotation, module)
1159 return _formatannotation
Guido van Rossum2e65f892007-02-28 22:03:49 +00001160
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001161def formatargspec(args, varargs=None, varkw=None, defaults=None,
Guido van Rossum2e65f892007-02-28 22:03:49 +00001162 kwonlyargs=(), kwonlydefaults={}, annotations={},
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001163 formatarg=str,
1164 formatvarargs=lambda name: '*' + name,
1165 formatvarkw=lambda name: '**' + name,
1166 formatvalue=lambda value: '=' + repr(value),
Guido van Rossum2e65f892007-02-28 22:03:49 +00001167 formatreturns=lambda text: ' -> ' + text,
Georg Brandlc1c4bf82010-10-15 16:07:41 +00001168 formatannotation=formatannotation):
Guido van Rossuma8add0e2007-05-14 22:03:55 +00001169 """Format an argument spec from the values returned by getargspec
Guido van Rossum2e65f892007-02-28 22:03:49 +00001170 or getfullargspec.
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001171
Guido van Rossum2e65f892007-02-28 22:03:49 +00001172 The first seven arguments are (args, varargs, varkw, defaults,
1173 kwonlyargs, kwonlydefaults, annotations). The other five arguments
1174 are the corresponding optional formatting functions that are called to
1175 turn names and values into strings. The last argument is an optional
1176 function to format the sequence of arguments."""
1177 def formatargandannotation(arg):
1178 result = formatarg(arg)
1179 if arg in annotations:
1180 result += ': ' + formatannotation(annotations[arg])
1181 return result
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001182 specs = []
1183 if defaults:
1184 firstdefault = len(args) - len(defaults)
Benjamin Petersonb58dda72009-01-18 22:27:04 +00001185 for i, arg in enumerate(args):
Georg Brandlc1c4bf82010-10-15 16:07:41 +00001186 spec = formatargandannotation(arg)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001187 if defaults and i >= firstdefault:
1188 spec = spec + formatvalue(defaults[i - firstdefault])
1189 specs.append(spec)
Raymond Hettinger936654b2002-06-01 03:06:31 +00001190 if varargs is not None:
Guido van Rossum2e65f892007-02-28 22:03:49 +00001191 specs.append(formatvarargs(formatargandannotation(varargs)))
1192 else:
1193 if kwonlyargs:
1194 specs.append('*')
1195 if kwonlyargs:
1196 for kwonlyarg in kwonlyargs:
1197 spec = formatargandannotation(kwonlyarg)
Benjamin Peterson9953a8d2009-01-17 04:15:01 +00001198 if kwonlydefaults and kwonlyarg in kwonlydefaults:
Guido van Rossum2e65f892007-02-28 22:03:49 +00001199 spec += formatvalue(kwonlydefaults[kwonlyarg])
1200 specs.append(spec)
Raymond Hettinger936654b2002-06-01 03:06:31 +00001201 if varkw is not None:
Guido van Rossum2e65f892007-02-28 22:03:49 +00001202 specs.append(formatvarkw(formatargandannotation(varkw)))
Neal Norwitz9d72bb42007-04-17 08:48:32 +00001203 result = '(' + ', '.join(specs) + ')'
Guido van Rossum2e65f892007-02-28 22:03:49 +00001204 if 'return' in annotations:
1205 result += formatreturns(formatannotation(annotations['return']))
1206 return result
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001207
1208def formatargvalues(args, varargs, varkw, locals,
1209 formatarg=str,
1210 formatvarargs=lambda name: '*' + name,
1211 formatvarkw=lambda name: '**' + name,
Georg Brandlc1c4bf82010-10-15 16:07:41 +00001212 formatvalue=lambda value: '=' + repr(value)):
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001213 """Format an argument spec from the 4 values returned by getargvalues.
1214
1215 The first four arguments are (args, varargs, varkw, locals). The
1216 next four arguments are the corresponding optional formatting functions
1217 that are called to turn names and values into strings. The ninth
1218 argument is an optional function to format the sequence of arguments."""
1219 def convert(name, locals=locals,
1220 formatarg=formatarg, formatvalue=formatvalue):
1221 return formatarg(name) + formatvalue(locals[name])
1222 specs = []
1223 for i in range(len(args)):
Georg Brandlc1c4bf82010-10-15 16:07:41 +00001224 specs.append(convert(args[i]))
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001225 if varargs:
1226 specs.append(formatvarargs(varargs) + formatvalue(locals[varargs]))
1227 if varkw:
1228 specs.append(formatvarkw(varkw) + formatvalue(locals[varkw]))
Neal Norwitz9d72bb42007-04-17 08:48:32 +00001229 return '(' + ', '.join(specs) + ')'
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001230
Benjamin Petersone109c702011-06-24 09:37:26 -05001231def _missing_arguments(f_name, argnames, pos, values):
1232 names = [repr(name) for name in argnames if name not in values]
1233 missing = len(names)
1234 if missing == 1:
1235 s = names[0]
1236 elif missing == 2:
1237 s = "{} and {}".format(*names)
1238 else:
Yury Selivanovdccfa132014-03-27 18:42:52 -04001239 tail = ", {} and {}".format(*names[-2:])
Benjamin Petersone109c702011-06-24 09:37:26 -05001240 del names[-2:]
1241 s = ", ".join(names) + tail
1242 raise TypeError("%s() missing %i required %s argument%s: %s" %
1243 (f_name, missing,
1244 "positional" if pos else "keyword-only",
1245 "" if missing == 1 else "s", s))
1246
1247def _too_many(f_name, args, kwonly, varargs, defcount, given, values):
Benjamin Petersonb204a422011-06-05 22:04:07 -05001248 atleast = len(args) - defcount
Benjamin Petersonb204a422011-06-05 22:04:07 -05001249 kwonly_given = len([arg for arg in kwonly if arg in values])
1250 if varargs:
1251 plural = atleast != 1
1252 sig = "at least %d" % (atleast,)
1253 elif defcount:
1254 plural = True
1255 sig = "from %d to %d" % (atleast, len(args))
1256 else:
1257 plural = len(args) != 1
1258 sig = str(len(args))
1259 kwonly_sig = ""
1260 if kwonly_given:
1261 msg = " positional argument%s (and %d keyword-only argument%s)"
1262 kwonly_sig = (msg % ("s" if given != 1 else "", kwonly_given,
1263 "s" if kwonly_given != 1 else ""))
1264 raise TypeError("%s() takes %s positional argument%s but %d%s %s given" %
1265 (f_name, sig, "s" if plural else "", given, kwonly_sig,
1266 "was" if given == 1 and not kwonly_given else "were"))
1267
Benjamin Peterson3e6ab172014-01-02 12:24:08 -06001268def getcallargs(*func_and_positional, **named):
Benjamin Peterson25cd7eb2010-03-30 18:42:32 +00001269 """Get the mapping of arguments to values.
1270
1271 A dict is returned, with keys the function argument names (including the
1272 names of the * and ** arguments, if any), and values the respective bound
1273 values from 'positional' and 'named'."""
Benjamin Peterson3e6ab172014-01-02 12:24:08 -06001274 func = func_and_positional[0]
1275 positional = func_and_positional[1:]
Benjamin Peterson25cd7eb2010-03-30 18:42:32 +00001276 spec = getfullargspec(func)
1277 args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults, ann = spec
1278 f_name = func.__name__
1279 arg2value = {}
1280
Benjamin Petersonb204a422011-06-05 22:04:07 -05001281
Benjamin Peterson25cd7eb2010-03-30 18:42:32 +00001282 if ismethod(func) and func.__self__ is not None:
1283 # implicit 'self' (or 'cls' for classmethods) argument
1284 positional = (func.__self__,) + positional
1285 num_pos = len(positional)
Benjamin Peterson25cd7eb2010-03-30 18:42:32 +00001286 num_args = len(args)
1287 num_defaults = len(defaults) if defaults else 0
Benjamin Peterson25cd7eb2010-03-30 18:42:32 +00001288
Benjamin Petersonb204a422011-06-05 22:04:07 -05001289 n = min(num_pos, num_args)
1290 for i in range(n):
1291 arg2value[args[i]] = positional[i]
1292 if varargs:
1293 arg2value[varargs] = tuple(positional[n:])
1294 possible_kwargs = set(args + kwonlyargs)
Benjamin Peterson25cd7eb2010-03-30 18:42:32 +00001295 if varkw:
Benjamin Petersonb204a422011-06-05 22:04:07 -05001296 arg2value[varkw] = {}
1297 for kw, value in named.items():
1298 if kw not in possible_kwargs:
1299 if not varkw:
1300 raise TypeError("%s() got an unexpected keyword argument %r" %
1301 (f_name, kw))
1302 arg2value[varkw][kw] = value
1303 continue
1304 if kw in arg2value:
1305 raise TypeError("%s() got multiple values for argument %r" %
1306 (f_name, kw))
1307 arg2value[kw] = value
1308 if num_pos > num_args and not varargs:
Benjamin Petersone109c702011-06-24 09:37:26 -05001309 _too_many(f_name, args, kwonlyargs, varargs, num_defaults,
1310 num_pos, arg2value)
Benjamin Petersonb204a422011-06-05 22:04:07 -05001311 if num_pos < num_args:
Benjamin Petersone109c702011-06-24 09:37:26 -05001312 req = args[:num_args - num_defaults]
1313 for arg in req:
Benjamin Petersonb204a422011-06-05 22:04:07 -05001314 if arg not in arg2value:
Benjamin Petersone109c702011-06-24 09:37:26 -05001315 _missing_arguments(f_name, req, True, arg2value)
Benjamin Petersonb204a422011-06-05 22:04:07 -05001316 for i, arg in enumerate(args[num_args - num_defaults:]):
1317 if arg not in arg2value:
1318 arg2value[arg] = defaults[i]
Benjamin Petersone109c702011-06-24 09:37:26 -05001319 missing = 0
Benjamin Petersonb204a422011-06-05 22:04:07 -05001320 for kwarg in kwonlyargs:
1321 if kwarg not in arg2value:
Yury Selivanov875df202014-03-27 18:23:03 -04001322 if kwonlydefaults and kwarg in kwonlydefaults:
Benjamin Petersone109c702011-06-24 09:37:26 -05001323 arg2value[kwarg] = kwonlydefaults[kwarg]
1324 else:
1325 missing += 1
1326 if missing:
1327 _missing_arguments(f_name, kwonlyargs, False, arg2value)
Benjamin Peterson25cd7eb2010-03-30 18:42:32 +00001328 return arg2value
1329
Nick Coghlan2f92e542012-06-23 19:39:55 +10001330ClosureVars = namedtuple('ClosureVars', 'nonlocals globals builtins unbound')
1331
1332def getclosurevars(func):
1333 """
1334 Get the mapping of free variables to their current values.
1335
Meador Inge8fda3592012-07-19 21:33:21 -05001336 Returns a named tuple of dicts mapping the current nonlocal, global
Nick Coghlan2f92e542012-06-23 19:39:55 +10001337 and builtin references as seen by the body of the function. A final
1338 set of unbound names that could not be resolved is also provided.
1339 """
1340
1341 if ismethod(func):
1342 func = func.__func__
1343
1344 if not isfunction(func):
1345 raise TypeError("'{!r}' is not a Python function".format(func))
1346
1347 code = func.__code__
1348 # Nonlocal references are named in co_freevars and resolved
1349 # by looking them up in __closure__ by positional index
1350 if func.__closure__ is None:
1351 nonlocal_vars = {}
1352 else:
1353 nonlocal_vars = {
1354 var : cell.cell_contents
1355 for var, cell in zip(code.co_freevars, func.__closure__)
1356 }
1357
1358 # Global and builtin references are named in co_names and resolved
1359 # by looking them up in __globals__ or __builtins__
1360 global_ns = func.__globals__
1361 builtin_ns = global_ns.get("__builtins__", builtins.__dict__)
1362 if ismodule(builtin_ns):
1363 builtin_ns = builtin_ns.__dict__
1364 global_vars = {}
1365 builtin_vars = {}
1366 unbound_names = set()
1367 for name in code.co_names:
1368 if name in ("None", "True", "False"):
1369 # Because these used to be builtins instead of keywords, they
1370 # may still show up as name references. We ignore them.
1371 continue
1372 try:
1373 global_vars[name] = global_ns[name]
1374 except KeyError:
1375 try:
1376 builtin_vars[name] = builtin_ns[name]
1377 except KeyError:
1378 unbound_names.add(name)
1379
1380 return ClosureVars(nonlocal_vars, global_vars,
1381 builtin_vars, unbound_names)
1382
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001383# -------------------------------------------------- stack frame extraction
Christian Heimes25bb7832008-01-11 16:17:00 +00001384
1385Traceback = namedtuple('Traceback', 'filename lineno function code_context index')
1386
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001387def getframeinfo(frame, context=1):
1388 """Get information about a frame or traceback object.
1389
1390 A tuple of five things is returned: the filename, the line number of
1391 the current line, the function name, a list of lines of context from
1392 the source code, and the index of the current line within that list.
1393 The optional second argument specifies the number of lines of context
1394 to return, which are centered around the current line."""
1395 if istraceback(frame):
Andrew M. Kuchlingba8b6bc2004-06-05 14:11:59 +00001396 lineno = frame.tb_lineno
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001397 frame = frame.tb_frame
Andrew M. Kuchlingba8b6bc2004-06-05 14:11:59 +00001398 else:
1399 lineno = frame.f_lineno
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001400 if not isframe(frame):
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00001401 raise TypeError('{!r} is not a frame or traceback object'.format(frame))
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001402
Neil Schemenauerf06f8532002-03-23 23:51:04 +00001403 filename = getsourcefile(frame) or getfile(frame)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001404 if context > 0:
Guido van Rossum54e54c62001-09-04 19:14:14 +00001405 start = lineno - 1 - context//2
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001406 try:
1407 lines, lnum = findsource(frame)
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02001408 except OSError:
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +00001409 lines = index = None
1410 else:
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001411 start = max(start, 1)
Raymond Hettingera0501712004-06-15 11:22:53 +00001412 start = max(0, min(start, len(lines) - context))
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001413 lines = lines[start:start+context]
Ka-Ping Yee59ade082001-03-01 03:55:35 +00001414 index = lineno - 1 - start
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001415 else:
1416 lines = index = None
1417
Christian Heimes25bb7832008-01-11 16:17:00 +00001418 return Traceback(filename, lineno, frame.f_code.co_name, lines, index)
Ka-Ping Yee59ade082001-03-01 03:55:35 +00001419
1420def getlineno(frame):
1421 """Get the line number from a frame object, allowing for optimization."""
Michael W. Hudsondd32a912002-08-15 14:59:02 +00001422 # FrameType.f_lineno is now a descriptor that grovels co_lnotab
1423 return frame.f_lineno
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001424
Antoine Pitroucdcafb72014-08-24 10:50:28 -04001425FrameInfo = namedtuple('FrameInfo', ('frame',) + Traceback._fields)
1426
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001427def getouterframes(frame, context=1):
1428 """Get a list of records for a frame and all higher (calling) frames.
1429
1430 Each record contains a frame object, filename, line number, function
1431 name, a list of lines of context, and index within the context."""
1432 framelist = []
1433 while frame:
Antoine Pitroucdcafb72014-08-24 10:50:28 -04001434 frameinfo = (frame,) + getframeinfo(frame, context)
1435 framelist.append(FrameInfo(*frameinfo))
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001436 frame = frame.f_back
1437 return framelist
1438
1439def getinnerframes(tb, context=1):
1440 """Get a list of records for a traceback's frame and all lower frames.
1441
1442 Each record contains a frame object, filename, line number, function
1443 name, a list of lines of context, and index within the context."""
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001444 framelist = []
1445 while tb:
Antoine Pitroucdcafb72014-08-24 10:50:28 -04001446 frameinfo = (tb.tb_frame,) + getframeinfo(tb, context)
1447 framelist.append(FrameInfo(*frameinfo))
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001448 tb = tb.tb_next
1449 return framelist
1450
Benjamin Peterson42ac4752010-08-09 13:05:35 +00001451def currentframe():
Benjamin Petersona3a3fc62010-08-09 15:49:56 +00001452 """Return the frame of the caller or None if this is not possible."""
Benjamin Peterson42ac4752010-08-09 13:05:35 +00001453 return sys._getframe(1) if hasattr(sys, "_getframe") else None
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001454
1455def stack(context=1):
1456 """Return a list of records for the stack above the caller's frame."""
Jeremy Hyltonab919022003-06-27 18:41:20 +00001457 return getouterframes(sys._getframe(1), context)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001458
1459def trace(context=1):
Tim Peters85ba6732001-02-28 08:26:44 +00001460 """Return a list of records for the stack below the current exception."""
Fred Draked451ec12002-04-26 02:29:55 +00001461 return getinnerframes(sys.exc_info()[2], context)
Michael Foord95fc51d2010-11-20 15:07:30 +00001462
1463
1464# ------------------------------------------------ static version of getattr
1465
1466_sentinel = object()
1467
Michael Foorde5162652010-11-20 16:40:44 +00001468def _static_getmro(klass):
1469 return type.__dict__['__mro__'].__get__(klass)
1470
Michael Foord95fc51d2010-11-20 15:07:30 +00001471def _check_instance(obj, attr):
1472 instance_dict = {}
1473 try:
1474 instance_dict = object.__getattribute__(obj, "__dict__")
1475 except AttributeError:
1476 pass
Michael Foorddcebe0f2011-03-15 19:20:44 -04001477 return dict.get(instance_dict, attr, _sentinel)
Michael Foord95fc51d2010-11-20 15:07:30 +00001478
1479
1480def _check_class(klass, attr):
Michael Foorde5162652010-11-20 16:40:44 +00001481 for entry in _static_getmro(klass):
Michael Foorda51623b2011-12-18 22:01:40 +00001482 if _shadowed_dict(type(entry)) is _sentinel:
Michael Foorddcebe0f2011-03-15 19:20:44 -04001483 try:
1484 return entry.__dict__[attr]
1485 except KeyError:
1486 pass
Michael Foord95fc51d2010-11-20 15:07:30 +00001487 return _sentinel
1488
Michael Foord35184ed2010-11-20 16:58:30 +00001489def _is_type(obj):
1490 try:
1491 _static_getmro(obj)
1492 except TypeError:
1493 return False
1494 return True
1495
Michael Foorddcebe0f2011-03-15 19:20:44 -04001496def _shadowed_dict(klass):
1497 dict_attr = type.__dict__["__dict__"]
1498 for entry in _static_getmro(klass):
1499 try:
1500 class_dict = dict_attr.__get__(entry)["__dict__"]
1501 except KeyError:
1502 pass
1503 else:
1504 if not (type(class_dict) is types.GetSetDescriptorType and
1505 class_dict.__name__ == "__dict__" and
1506 class_dict.__objclass__ is entry):
Michael Foorda51623b2011-12-18 22:01:40 +00001507 return class_dict
1508 return _sentinel
Michael Foord95fc51d2010-11-20 15:07:30 +00001509
1510def getattr_static(obj, attr, default=_sentinel):
1511 """Retrieve attributes without triggering dynamic lookup via the
1512 descriptor protocol, __getattr__ or __getattribute__.
1513
1514 Note: this function may not be able to retrieve all attributes
1515 that getattr can fetch (like dynamically created attributes)
1516 and may find attributes that getattr can't (like descriptors
1517 that raise AttributeError). It can also return descriptor objects
1518 instead of instance members in some cases. See the
1519 documentation for details.
1520 """
1521 instance_result = _sentinel
Michael Foord35184ed2010-11-20 16:58:30 +00001522 if not _is_type(obj):
Michael Foordcc7ebb82010-11-20 16:20:16 +00001523 klass = type(obj)
Michael Foorda51623b2011-12-18 22:01:40 +00001524 dict_attr = _shadowed_dict(klass)
1525 if (dict_attr is _sentinel or
1526 type(dict_attr) is types.MemberDescriptorType):
Michael Foorddcebe0f2011-03-15 19:20:44 -04001527 instance_result = _check_instance(obj, attr)
Michael Foord95fc51d2010-11-20 15:07:30 +00001528 else:
1529 klass = obj
1530
1531 klass_result = _check_class(klass, attr)
1532
1533 if instance_result is not _sentinel and klass_result is not _sentinel:
1534 if (_check_class(type(klass_result), '__get__') is not _sentinel and
1535 _check_class(type(klass_result), '__set__') is not _sentinel):
1536 return klass_result
1537
1538 if instance_result is not _sentinel:
1539 return instance_result
1540 if klass_result is not _sentinel:
1541 return klass_result
1542
1543 if obj is klass:
1544 # for types we check the metaclass too
Michael Foorde5162652010-11-20 16:40:44 +00001545 for entry in _static_getmro(type(klass)):
Michael Foord3ba95f82011-12-22 01:13:37 +00001546 if _shadowed_dict(type(entry)) is _sentinel:
1547 try:
1548 return entry.__dict__[attr]
1549 except KeyError:
1550 pass
Michael Foord95fc51d2010-11-20 15:07:30 +00001551 if default is not _sentinel:
1552 return default
1553 raise AttributeError(attr)
Nick Coghlane0f04652010-11-21 03:44:04 +00001554
1555
Nick Coghlan04e2e3f2012-06-23 19:52:05 +10001556# ------------------------------------------------ generator introspection
1557
Nick Coghlan7921b9f2010-11-30 06:36:04 +00001558GEN_CREATED = 'GEN_CREATED'
1559GEN_RUNNING = 'GEN_RUNNING'
1560GEN_SUSPENDED = 'GEN_SUSPENDED'
1561GEN_CLOSED = 'GEN_CLOSED'
Nick Coghlane0f04652010-11-21 03:44:04 +00001562
1563def getgeneratorstate(generator):
1564 """Get current state of a generator-iterator.
1565
1566 Possible states are:
1567 GEN_CREATED: Waiting to start execution.
1568 GEN_RUNNING: Currently being executed by the interpreter.
1569 GEN_SUSPENDED: Currently suspended at a yield expression.
1570 GEN_CLOSED: Execution has completed.
1571 """
1572 if generator.gi_running:
1573 return GEN_RUNNING
1574 if generator.gi_frame is None:
1575 return GEN_CLOSED
1576 if generator.gi_frame.f_lasti == -1:
1577 return GEN_CREATED
1578 return GEN_SUSPENDED
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07001579
1580
Nick Coghlan04e2e3f2012-06-23 19:52:05 +10001581def getgeneratorlocals(generator):
1582 """
1583 Get the mapping of generator local variables to their current values.
1584
1585 A dict is returned, with the keys the local variable names and values the
1586 bound values."""
1587
1588 if not isgenerator(generator):
1589 raise TypeError("'{!r}' is not a Python generator".format(generator))
1590
1591 frame = getattr(generator, "gi_frame", None)
1592 if frame is not None:
1593 return generator.gi_frame.f_locals
1594 else:
1595 return {}
1596
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07001597###############################################################################
1598### Function Signature Object (PEP 362)
1599###############################################################################
1600
1601
1602_WrapperDescriptor = type(type.__call__)
1603_MethodWrapper = type(all.__call__)
Larry Hastings5c661892014-01-24 06:17:25 -08001604_ClassMethodWrapper = type(int.__dict__['from_bytes'])
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07001605
1606_NonUserDefinedCallables = (_WrapperDescriptor,
1607 _MethodWrapper,
Larry Hastings5c661892014-01-24 06:17:25 -08001608 _ClassMethodWrapper,
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07001609 types.BuiltinFunctionType)
1610
1611
Yury Selivanov421f0c72014-01-29 12:05:40 -05001612def _signature_get_user_defined_method(cls, method_name):
Yury Selivanov5a23bd02014-03-29 13:47:11 -04001613 """Private helper. Checks if ``cls`` has an attribute
1614 named ``method_name`` and returns it only if it is a
1615 pure python function.
1616 """
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07001617 try:
1618 meth = getattr(cls, method_name)
1619 except AttributeError:
1620 return
1621 else:
1622 if not isinstance(meth, _NonUserDefinedCallables):
1623 # Once '__signature__' will be added to 'C'-level
1624 # callables, this check won't be necessary
1625 return meth
1626
1627
Yury Selivanov62560fb2014-01-28 12:26:24 -05001628def _signature_get_partial(wrapped_sig, partial, extra_args=()):
Yury Selivanov5a23bd02014-03-29 13:47:11 -04001629 """Private helper to calculate how 'wrapped_sig' signature will
1630 look like after applying a 'functools.partial' object (or alike)
1631 on it.
1632 """
Yury Selivanov62560fb2014-01-28 12:26:24 -05001633
Yury Selivanov3f73ca22014-04-08 11:30:45 -04001634 old_params = wrapped_sig.parameters
1635 new_params = OrderedDict(old_params.items())
Yury Selivanovda5fe4f2014-01-27 17:28:37 -05001636
1637 partial_args = partial.args or ()
1638 partial_keywords = partial.keywords or {}
1639
1640 if extra_args:
1641 partial_args = extra_args + partial_args
1642
1643 try:
1644 ba = wrapped_sig.bind_partial(*partial_args, **partial_keywords)
1645 except TypeError as ex:
1646 msg = 'partial object {!r} has incorrect arguments'.format(partial)
1647 raise ValueError(msg) from ex
1648
Yury Selivanovda5fe4f2014-01-27 17:28:37 -05001649
Yury Selivanov3f73ca22014-04-08 11:30:45 -04001650 transform_to_kwonly = False
1651 for param_name, param in old_params.items():
1652 try:
1653 arg_value = ba.arguments[param_name]
1654 except KeyError:
1655 pass
1656 else:
1657 if param.kind is _POSITIONAL_ONLY:
1658 # If positional-only parameter is bound by partial,
1659 # it effectively disappears from the signature
1660 new_params.pop(param_name)
1661 continue
1662
1663 if param.kind is _POSITIONAL_OR_KEYWORD:
1664 if param_name in partial_keywords:
1665 # This means that this parameter, and all parameters
1666 # after it should be keyword-only (and var-positional
1667 # should be removed). Here's why. Consider the following
1668 # function:
1669 # foo(a, b, *args, c):
1670 # pass
1671 #
1672 # "partial(foo, a='spam')" will have the following
1673 # signature: "(*, a='spam', b, c)". Because attempting
1674 # to call that partial with "(10, 20)" arguments will
1675 # raise a TypeError, saying that "a" argument received
1676 # multiple values.
1677 transform_to_kwonly = True
1678 # Set the new default value
1679 new_params[param_name] = param.replace(default=arg_value)
1680 else:
1681 # was passed as a positional argument
1682 new_params.pop(param.name)
1683 continue
1684
1685 if param.kind is _KEYWORD_ONLY:
1686 # Set the new default value
1687 new_params[param_name] = param.replace(default=arg_value)
1688
1689 if transform_to_kwonly:
1690 assert param.kind is not _POSITIONAL_ONLY
1691
1692 if param.kind is _POSITIONAL_OR_KEYWORD:
1693 new_param = new_params[param_name].replace(kind=_KEYWORD_ONLY)
1694 new_params[param_name] = new_param
1695 new_params.move_to_end(param_name)
1696 elif param.kind in (_KEYWORD_ONLY, _VAR_KEYWORD):
1697 new_params.move_to_end(param_name)
1698 elif param.kind is _VAR_POSITIONAL:
1699 new_params.pop(param.name)
Yury Selivanovda5fe4f2014-01-27 17:28:37 -05001700
1701 return wrapped_sig.replace(parameters=new_params.values())
1702
1703
Yury Selivanov62560fb2014-01-28 12:26:24 -05001704def _signature_bound_method(sig):
Yury Selivanov5a23bd02014-03-29 13:47:11 -04001705 """Private helper to transform signatures for unbound
1706 functions to bound methods.
1707 """
Yury Selivanov62560fb2014-01-28 12:26:24 -05001708
1709 params = tuple(sig.parameters.values())
1710
1711 if not params or params[0].kind in (_VAR_KEYWORD, _KEYWORD_ONLY):
1712 raise ValueError('invalid method signature')
1713
1714 kind = params[0].kind
1715 if kind in (_POSITIONAL_OR_KEYWORD, _POSITIONAL_ONLY):
1716 # Drop first parameter:
1717 # '(p1, p2[, ...])' -> '(p2[, ...])'
1718 params = params[1:]
1719 else:
1720 if kind is not _VAR_POSITIONAL:
1721 # Unless we add a new parameter type we never
1722 # get here
1723 raise ValueError('invalid argument type')
1724 # It's a var-positional parameter.
1725 # Do nothing. '(*args[, ...])' -> '(*args[, ...])'
1726
1727 return sig.replace(parameters=params)
1728
1729
Yury Selivanovb77511d2014-01-29 10:46:14 -05001730def _signature_is_builtin(obj):
Yury Selivanov5a23bd02014-03-29 13:47:11 -04001731 """Private helper to test if `obj` is a callable that might
1732 support Argument Clinic's __text_signature__ protocol.
1733 """
Yury Selivanov1d241832014-02-02 12:51:20 -05001734 return (isbuiltin(obj) or
Yury Selivanovb77511d2014-01-29 10:46:14 -05001735 ismethoddescriptor(obj) or
Yury Selivanov1d241832014-02-02 12:51:20 -05001736 isinstance(obj, _NonUserDefinedCallables) or
Yury Selivanovb77511d2014-01-29 10:46:14 -05001737 # Can't test 'isinstance(type)' here, as it would
1738 # also be True for regular python classes
1739 obj in (type, object))
1740
1741
Yury Selivanov63da7c72014-01-31 14:48:37 -05001742def _signature_is_functionlike(obj):
Yury Selivanov5a23bd02014-03-29 13:47:11 -04001743 """Private helper to test if `obj` is a duck type of FunctionType.
1744 A good example of such objects are functions compiled with
1745 Cython, which have all attributes that a pure Python function
1746 would have, but have their code statically compiled.
1747 """
Yury Selivanov63da7c72014-01-31 14:48:37 -05001748
1749 if not callable(obj) or isclass(obj):
1750 # All function-like objects are obviously callables,
1751 # and not classes.
1752 return False
1753
1754 name = getattr(obj, '__name__', None)
1755 code = getattr(obj, '__code__', None)
1756 defaults = getattr(obj, '__defaults__', _void) # Important to use _void ...
1757 kwdefaults = getattr(obj, '__kwdefaults__', _void) # ... and not None here
1758 annotations = getattr(obj, '__annotations__', None)
1759
1760 return (isinstance(code, types.CodeType) and
1761 isinstance(name, str) and
1762 (defaults is None or isinstance(defaults, tuple)) and
1763 (kwdefaults is None or isinstance(kwdefaults, dict)) and
1764 isinstance(annotations, dict))
1765
1766
Yury Selivanovd82eddc2014-01-29 11:24:39 -05001767def _signature_get_bound_param(spec):
Yury Selivanov5a23bd02014-03-29 13:47:11 -04001768 """ Private helper to get first parameter name from a
1769 __text_signature__ of a builtin method, which should
1770 be in the following format: '($param1, ...)'.
1771 Assumptions are that the first argument won't have
1772 a default value or an annotation.
1773 """
Yury Selivanovd82eddc2014-01-29 11:24:39 -05001774
1775 assert spec.startswith('($')
1776
1777 pos = spec.find(',')
1778 if pos == -1:
1779 pos = spec.find(')')
1780
1781 cpos = spec.find(':')
1782 assert cpos == -1 or cpos > pos
1783
1784 cpos = spec.find('=')
1785 assert cpos == -1 or cpos > pos
1786
1787 return spec[2:pos]
1788
1789
Larry Hastings2623c8c2014-02-08 22:15:29 -08001790def _signature_strip_non_python_syntax(signature):
1791 """
Yury Selivanov5a23bd02014-03-29 13:47:11 -04001792 Private helper function. Takes a signature in Argument Clinic's
1793 extended signature format.
1794
Larry Hastings2623c8c2014-02-08 22:15:29 -08001795 Returns a tuple of three things:
1796 * that signature re-rendered in standard Python syntax,
1797 * the index of the "self" parameter (generally 0), or None if
1798 the function does not have a "self" parameter, and
1799 * the index of the last "positional only" parameter,
1800 or None if the signature has no positional-only parameters.
1801 """
1802
1803 if not signature:
1804 return signature, None, None
1805
1806 self_parameter = None
1807 last_positional_only = None
1808
1809 lines = [l.encode('ascii') for l in signature.split('\n')]
1810 generator = iter(lines).__next__
1811 token_stream = tokenize.tokenize(generator)
1812
1813 delayed_comma = False
1814 skip_next_comma = False
1815 text = []
1816 add = text.append
1817
1818 current_parameter = 0
1819 OP = token.OP
1820 ERRORTOKEN = token.ERRORTOKEN
1821
1822 # token stream always starts with ENCODING token, skip it
1823 t = next(token_stream)
1824 assert t.type == tokenize.ENCODING
1825
1826 for t in token_stream:
1827 type, string = t.type, t.string
1828
1829 if type == OP:
1830 if string == ',':
1831 if skip_next_comma:
1832 skip_next_comma = False
1833 else:
1834 assert not delayed_comma
1835 delayed_comma = True
1836 current_parameter += 1
1837 continue
1838
1839 if string == '/':
1840 assert not skip_next_comma
1841 assert last_positional_only is None
1842 skip_next_comma = True
1843 last_positional_only = current_parameter - 1
1844 continue
1845
1846 if (type == ERRORTOKEN) and (string == '$'):
1847 assert self_parameter is None
1848 self_parameter = current_parameter
1849 continue
1850
1851 if delayed_comma:
1852 delayed_comma = False
1853 if not ((type == OP) and (string == ')')):
1854 add(', ')
1855 add(string)
1856 if (string == ','):
1857 add(' ')
1858 clean_signature = ''.join(text)
1859 return clean_signature, self_parameter, last_positional_only
1860
1861
Yury Selivanov57d240e2014-02-19 16:27:23 -05001862def _signature_fromstr(cls, obj, s, skip_bound_arg=True):
Yury Selivanov5a23bd02014-03-29 13:47:11 -04001863 """Private helper to parse content of '__text_signature__'
1864 and return a Signature based on it.
1865 """
1866
Yury Selivanov7d2bfed2014-02-03 02:46:07 -05001867 Parameter = cls._parameter_cls
1868
Larry Hastings2623c8c2014-02-08 22:15:29 -08001869 clean_signature, self_parameter, last_positional_only = \
1870 _signature_strip_non_python_syntax(s)
Yury Selivanov7d2bfed2014-02-03 02:46:07 -05001871
Larry Hastings2623c8c2014-02-08 22:15:29 -08001872 program = "def foo" + clean_signature + ": pass"
Yury Selivanov7d2bfed2014-02-03 02:46:07 -05001873
1874 try:
Larry Hastings2623c8c2014-02-08 22:15:29 -08001875 module = ast.parse(program)
Yury Selivanov7d2bfed2014-02-03 02:46:07 -05001876 except SyntaxError:
1877 module = None
1878
1879 if not isinstance(module, ast.Module):
1880 raise ValueError("{!r} builtin has invalid signature".format(obj))
1881
1882 f = module.body[0]
1883
1884 parameters = []
1885 empty = Parameter.empty
1886 invalid = object()
1887
1888 module = None
1889 module_dict = {}
1890 module_name = getattr(obj, '__module__', None)
1891 if module_name:
1892 module = sys.modules.get(module_name, None)
1893 if module:
1894 module_dict = module.__dict__
1895 sys_module_dict = sys.modules
1896
1897 def parse_name(node):
1898 assert isinstance(node, ast.arg)
1899 if node.annotation != None:
1900 raise ValueError("Annotations are not currently supported")
1901 return node.arg
1902
1903 def wrap_value(s):
1904 try:
1905 value = eval(s, module_dict)
1906 except NameError:
1907 try:
1908 value = eval(s, sys_module_dict)
1909 except NameError:
1910 raise RuntimeError()
1911
1912 if isinstance(value, str):
1913 return ast.Str(value)
1914 if isinstance(value, (int, float)):
1915 return ast.Num(value)
1916 if isinstance(value, bytes):
1917 return ast.Bytes(value)
1918 if value in (True, False, None):
1919 return ast.NameConstant(value)
1920 raise RuntimeError()
1921
1922 class RewriteSymbolics(ast.NodeTransformer):
1923 def visit_Attribute(self, node):
1924 a = []
1925 n = node
1926 while isinstance(n, ast.Attribute):
1927 a.append(n.attr)
1928 n = n.value
1929 if not isinstance(n, ast.Name):
1930 raise RuntimeError()
1931 a.append(n.id)
1932 value = ".".join(reversed(a))
1933 return wrap_value(value)
1934
1935 def visit_Name(self, node):
1936 if not isinstance(node.ctx, ast.Load):
1937 raise ValueError()
1938 return wrap_value(node.id)
1939
1940 def p(name_node, default_node, default=empty):
1941 name = parse_name(name_node)
1942 if name is invalid:
1943 return None
1944 if default_node and default_node is not _empty:
1945 try:
1946 default_node = RewriteSymbolics().visit(default_node)
1947 o = ast.literal_eval(default_node)
1948 except ValueError:
1949 o = invalid
1950 if o is invalid:
1951 return None
1952 default = o if o is not invalid else default
1953 parameters.append(Parameter(name, kind, default=default, annotation=empty))
1954
1955 # non-keyword-only parameters
1956 args = reversed(f.args.args)
1957 defaults = reversed(f.args.defaults)
1958 iter = itertools.zip_longest(args, defaults, fillvalue=None)
Larry Hastings2623c8c2014-02-08 22:15:29 -08001959 if last_positional_only is not None:
1960 kind = Parameter.POSITIONAL_ONLY
1961 else:
1962 kind = Parameter.POSITIONAL_OR_KEYWORD
1963 for i, (name, default) in enumerate(reversed(list(iter))):
Yury Selivanov7d2bfed2014-02-03 02:46:07 -05001964 p(name, default)
Larry Hastings2623c8c2014-02-08 22:15:29 -08001965 if i == last_positional_only:
1966 kind = Parameter.POSITIONAL_OR_KEYWORD
Yury Selivanov7d2bfed2014-02-03 02:46:07 -05001967
1968 # *args
1969 if f.args.vararg:
1970 kind = Parameter.VAR_POSITIONAL
1971 p(f.args.vararg, empty)
1972
1973 # keyword-only arguments
1974 kind = Parameter.KEYWORD_ONLY
1975 for name, default in zip(f.args.kwonlyargs, f.args.kw_defaults):
1976 p(name, default)
1977
1978 # **kwargs
1979 if f.args.kwarg:
1980 kind = Parameter.VAR_KEYWORD
1981 p(f.args.kwarg, empty)
1982
Larry Hastings2623c8c2014-02-08 22:15:29 -08001983 if self_parameter is not None:
Yury Selivanov8c185ee2014-02-21 01:32:42 -05001984 # Possibly strip the bound argument:
1985 # - We *always* strip first bound argument if
1986 # it is a module.
1987 # - We don't strip first bound argument if
1988 # skip_bound_arg is False.
Yury Selivanov7d2bfed2014-02-03 02:46:07 -05001989 assert parameters
Yury Selivanov8c185ee2014-02-21 01:32:42 -05001990 _self = getattr(obj, '__self__', None)
1991 self_isbound = _self is not None
1992 self_ismodule = ismodule(_self)
1993 if self_isbound and (self_ismodule or skip_bound_arg):
Yury Selivanov7d2bfed2014-02-03 02:46:07 -05001994 parameters.pop(0)
1995 else:
1996 # for builtins, self parameter is always positional-only!
1997 p = parameters[0].replace(kind=Parameter.POSITIONAL_ONLY)
1998 parameters[0] = p
1999
2000 return cls(parameters, return_annotation=cls.empty)
2001
2002
Yury Selivanov57d240e2014-02-19 16:27:23 -05002003def _signature_from_builtin(cls, func, skip_bound_arg=True):
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002004 """Private helper function to get signature for
2005 builtin callables.
2006 """
2007
Yury Selivanov57d240e2014-02-19 16:27:23 -05002008 if not _signature_is_builtin(func):
2009 raise TypeError("{!r} is not a Python builtin "
2010 "function".format(func))
2011
2012 s = getattr(func, "__text_signature__", None)
2013 if not s:
2014 raise ValueError("no signature found for builtin {!r}".format(func))
2015
2016 return _signature_fromstr(cls, func, s, skip_bound_arg)
2017
2018
Yury Selivanovcf45f022015-05-20 14:38:50 -04002019def _signature_from_function(cls, func):
2020 """Private helper: constructs Signature for the given python function."""
2021
2022 is_duck_function = False
2023 if not isfunction(func):
2024 if _signature_is_functionlike(func):
2025 is_duck_function = True
2026 else:
2027 # If it's not a pure Python function, and not a duck type
2028 # of pure function:
2029 raise TypeError('{!r} is not a Python function'.format(func))
2030
2031 Parameter = cls._parameter_cls
2032
2033 # Parameter information.
2034 func_code = func.__code__
2035 pos_count = func_code.co_argcount
2036 arg_names = func_code.co_varnames
2037 positional = tuple(arg_names[:pos_count])
2038 keyword_only_count = func_code.co_kwonlyargcount
2039 keyword_only = arg_names[pos_count:(pos_count + keyword_only_count)]
2040 annotations = func.__annotations__
2041 defaults = func.__defaults__
2042 kwdefaults = func.__kwdefaults__
2043
2044 if defaults:
2045 pos_default_count = len(defaults)
2046 else:
2047 pos_default_count = 0
2048
2049 parameters = []
2050
2051 # Non-keyword-only parameters w/o defaults.
2052 non_default_count = pos_count - pos_default_count
2053 for name in positional[:non_default_count]:
2054 annotation = annotations.get(name, _empty)
2055 parameters.append(Parameter(name, annotation=annotation,
2056 kind=_POSITIONAL_OR_KEYWORD))
2057
2058 # ... w/ defaults.
2059 for offset, name in enumerate(positional[non_default_count:]):
2060 annotation = annotations.get(name, _empty)
2061 parameters.append(Parameter(name, annotation=annotation,
2062 kind=_POSITIONAL_OR_KEYWORD,
2063 default=defaults[offset]))
2064
2065 # *args
2066 if func_code.co_flags & CO_VARARGS:
2067 name = arg_names[pos_count + keyword_only_count]
2068 annotation = annotations.get(name, _empty)
2069 parameters.append(Parameter(name, annotation=annotation,
2070 kind=_VAR_POSITIONAL))
2071
2072 # Keyword-only parameters.
2073 for name in keyword_only:
2074 default = _empty
2075 if kwdefaults is not None:
2076 default = kwdefaults.get(name, _empty)
2077
2078 annotation = annotations.get(name, _empty)
2079 parameters.append(Parameter(name, annotation=annotation,
2080 kind=_KEYWORD_ONLY,
2081 default=default))
2082 # **kwargs
2083 if func_code.co_flags & CO_VARKEYWORDS:
2084 index = pos_count + keyword_only_count
2085 if func_code.co_flags & CO_VARARGS:
2086 index += 1
2087
2088 name = arg_names[index]
2089 annotation = annotations.get(name, _empty)
2090 parameters.append(Parameter(name, annotation=annotation,
2091 kind=_VAR_KEYWORD))
2092
2093 # Is 'func' is a pure Python function - don't validate the
2094 # parameters list (for correct order and defaults), it should be OK.
2095 return cls(parameters,
2096 return_annotation=annotations.get('return', _empty),
2097 __validate_parameters__=is_duck_function)
2098
2099
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002100def _signature_from_callable(obj, *,
2101 follow_wrapper_chains=True,
2102 skip_bound_arg=True,
2103 sigcls):
2104
2105 """Private helper function to get signature for arbitrary
2106 callable objects.
2107 """
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002108
2109 if not callable(obj):
2110 raise TypeError('{!r} is not a callable object'.format(obj))
2111
2112 if isinstance(obj, types.MethodType):
2113 # In this case we skip the first parameter of the underlying
2114 # function (usually `self` or `cls`).
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002115 sig = _signature_from_callable(
Yury Selivanovda396452014-03-27 12:09:24 -04002116 obj.__func__,
2117 follow_wrapper_chains=follow_wrapper_chains,
2118 skip_bound_arg=skip_bound_arg,
2119 sigcls=sigcls)
2120
Yury Selivanov57d240e2014-02-19 16:27:23 -05002121 if skip_bound_arg:
2122 return _signature_bound_method(sig)
2123 else:
2124 return sig
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002125
Nick Coghlane8c45d62013-07-28 20:00:01 +10002126 # Was this function wrapped by a decorator?
Yury Selivanov57d240e2014-02-19 16:27:23 -05002127 if follow_wrapper_chains:
2128 obj = unwrap(obj, stop=(lambda f: hasattr(f, "__signature__")))
Nick Coghlane8c45d62013-07-28 20:00:01 +10002129
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002130 try:
2131 sig = obj.__signature__
2132 except AttributeError:
2133 pass
2134 else:
2135 if sig is not None:
Yury Selivanov42407ab2014-06-23 10:23:50 -07002136 if not isinstance(sig, Signature):
2137 raise TypeError(
2138 'unexpected object {!r} in __signature__ '
2139 'attribute'.format(sig))
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002140 return sig
2141
Yury Selivanovda5fe4f2014-01-27 17:28:37 -05002142 try:
2143 partialmethod = obj._partialmethod
2144 except AttributeError:
2145 pass
2146 else:
Yury Selivanov0486f812014-01-29 12:18:59 -05002147 if isinstance(partialmethod, functools.partialmethod):
2148 # Unbound partialmethod (see functools.partialmethod)
2149 # This means, that we need to calculate the signature
2150 # as if it's a regular partial object, but taking into
2151 # account that the first positional argument
2152 # (usually `self`, or `cls`) will not be passed
2153 # automatically (as for boundmethods)
Yury Selivanovda5fe4f2014-01-27 17:28:37 -05002154
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002155 wrapped_sig = _signature_from_callable(
Yury Selivanovda396452014-03-27 12:09:24 -04002156 partialmethod.func,
2157 follow_wrapper_chains=follow_wrapper_chains,
2158 skip_bound_arg=skip_bound_arg,
2159 sigcls=sigcls)
2160
Yury Selivanov0486f812014-01-29 12:18:59 -05002161 sig = _signature_get_partial(wrapped_sig, partialmethod, (None,))
Yury Selivanovda5fe4f2014-01-27 17:28:37 -05002162
Yury Selivanov0486f812014-01-29 12:18:59 -05002163 first_wrapped_param = tuple(wrapped_sig.parameters.values())[0]
2164 new_params = (first_wrapped_param,) + tuple(sig.parameters.values())
Yury Selivanovda5fe4f2014-01-27 17:28:37 -05002165
Yury Selivanov0486f812014-01-29 12:18:59 -05002166 return sig.replace(parameters=new_params)
Yury Selivanovda5fe4f2014-01-27 17:28:37 -05002167
Yury Selivanov63da7c72014-01-31 14:48:37 -05002168 if isfunction(obj) or _signature_is_functionlike(obj):
2169 # If it's a pure Python function, or an object that is duck type
2170 # of a Python function (Cython functions, for instance), then:
Yury Selivanovcf45f022015-05-20 14:38:50 -04002171 return _signature_from_function(sigcls, obj)
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002172
Yury Selivanova773de02014-02-21 18:30:53 -05002173 if _signature_is_builtin(obj):
Yury Selivanovda396452014-03-27 12:09:24 -04002174 return _signature_from_builtin(sigcls, obj,
Yury Selivanova773de02014-02-21 18:30:53 -05002175 skip_bound_arg=skip_bound_arg)
2176
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002177 if isinstance(obj, functools.partial):
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002178 wrapped_sig = _signature_from_callable(
Yury Selivanovda396452014-03-27 12:09:24 -04002179 obj.func,
2180 follow_wrapper_chains=follow_wrapper_chains,
2181 skip_bound_arg=skip_bound_arg,
2182 sigcls=sigcls)
Yury Selivanov62560fb2014-01-28 12:26:24 -05002183 return _signature_get_partial(wrapped_sig, obj)
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002184
2185 sig = None
2186 if isinstance(obj, type):
2187 # obj is a class or a metaclass
2188
2189 # First, let's see if it has an overloaded __call__ defined
2190 # in its metaclass
Yury Selivanov421f0c72014-01-29 12:05:40 -05002191 call = _signature_get_user_defined_method(type(obj), '__call__')
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002192 if call is not None:
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002193 sig = _signature_from_callable(
Yury Selivanovda396452014-03-27 12:09:24 -04002194 call,
2195 follow_wrapper_chains=follow_wrapper_chains,
2196 skip_bound_arg=skip_bound_arg,
2197 sigcls=sigcls)
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002198 else:
2199 # Now we check if the 'obj' class has a '__new__' method
Yury Selivanov421f0c72014-01-29 12:05:40 -05002200 new = _signature_get_user_defined_method(obj, '__new__')
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002201 if new is not None:
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002202 sig = _signature_from_callable(
Yury Selivanovda396452014-03-27 12:09:24 -04002203 new,
2204 follow_wrapper_chains=follow_wrapper_chains,
2205 skip_bound_arg=skip_bound_arg,
2206 sigcls=sigcls)
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002207 else:
2208 # Finally, we should have at least __init__ implemented
Yury Selivanov421f0c72014-01-29 12:05:40 -05002209 init = _signature_get_user_defined_method(obj, '__init__')
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002210 if init is not None:
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002211 sig = _signature_from_callable(
Yury Selivanovda396452014-03-27 12:09:24 -04002212 init,
2213 follow_wrapper_chains=follow_wrapper_chains,
2214 skip_bound_arg=skip_bound_arg,
2215 sigcls=sigcls)
Yury Selivanove7dcc5e2014-01-27 19:29:45 -05002216
2217 if sig is None:
Yury Selivanov7d2bfed2014-02-03 02:46:07 -05002218 # At this point we know, that `obj` is a class, with no user-
2219 # defined '__init__', '__new__', or class-level '__call__'
2220
Larry Hastings2623c8c2014-02-08 22:15:29 -08002221 for base in obj.__mro__[:-1]:
Yury Selivanov7d2bfed2014-02-03 02:46:07 -05002222 # Since '__text_signature__' is implemented as a
2223 # descriptor that extracts text signature from the
2224 # class docstring, if 'obj' is derived from a builtin
2225 # class, its own '__text_signature__' may be 'None'.
Larry Hastings2623c8c2014-02-08 22:15:29 -08002226 # Therefore, we go through the MRO (except the last
2227 # class in there, which is 'object') to find the first
Yury Selivanov7d2bfed2014-02-03 02:46:07 -05002228 # class with non-empty text signature.
2229 try:
2230 text_sig = base.__text_signature__
2231 except AttributeError:
2232 pass
2233 else:
2234 if text_sig:
2235 # If 'obj' class has a __text_signature__ attribute:
2236 # return a signature based on it
Yury Selivanovda396452014-03-27 12:09:24 -04002237 return _signature_fromstr(sigcls, obj, text_sig)
Yury Selivanov7d2bfed2014-02-03 02:46:07 -05002238
2239 # No '__text_signature__' was found for the 'obj' class.
2240 # Last option is to check if its '__init__' is
2241 # object.__init__ or type.__init__.
Larry Hastings2623c8c2014-02-08 22:15:29 -08002242 if type not in obj.__mro__:
Yury Selivanove7dcc5e2014-01-27 19:29:45 -05002243 # We have a class (not metaclass), but no user-defined
2244 # __init__ or __new__ for it
Yury Selivanov7d2bfed2014-02-03 02:46:07 -05002245 if obj.__init__ is object.__init__:
2246 # Return a signature of 'object' builtin.
2247 return signature(object)
Yury Selivanove7dcc5e2014-01-27 19:29:45 -05002248
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002249 elif not isinstance(obj, _NonUserDefinedCallables):
2250 # An object with __call__
2251 # We also check that the 'obj' is not an instance of
2252 # _WrapperDescriptor or _MethodWrapper to avoid
2253 # infinite recursion (and even potential segfault)
Yury Selivanov421f0c72014-01-29 12:05:40 -05002254 call = _signature_get_user_defined_method(type(obj), '__call__')
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002255 if call is not None:
Larry Hastings2623c8c2014-02-08 22:15:29 -08002256 try:
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002257 sig = _signature_from_callable(
Yury Selivanovda396452014-03-27 12:09:24 -04002258 call,
2259 follow_wrapper_chains=follow_wrapper_chains,
2260 skip_bound_arg=skip_bound_arg,
2261 sigcls=sigcls)
Larry Hastings2623c8c2014-02-08 22:15:29 -08002262 except ValueError as ex:
2263 msg = 'no signature found for {!r}'.format(obj)
2264 raise ValueError(msg) from ex
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002265
2266 if sig is not None:
2267 # For classes and objects we skip the first parameter of their
2268 # __call__, __new__, or __init__ methods
Yury Selivanov57d240e2014-02-19 16:27:23 -05002269 if skip_bound_arg:
2270 return _signature_bound_method(sig)
2271 else:
2272 return sig
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002273
2274 if isinstance(obj, types.BuiltinFunctionType):
2275 # Raise a nicer error message for builtins
2276 msg = 'no signature found for builtin function {!r}'.format(obj)
2277 raise ValueError(msg)
2278
2279 raise ValueError('callable {!r} is not supported by signature'.format(obj))
2280
2281
2282class _void:
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002283 """A private marker - used in Parameter & Signature."""
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002284
2285
2286class _empty:
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002287 """Marker object for Signature.empty and Parameter.empty."""
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002288
2289
Yury Selivanov21e83a52014-03-27 11:23:13 -04002290class _ParameterKind(enum.IntEnum):
2291 POSITIONAL_ONLY = 0
2292 POSITIONAL_OR_KEYWORD = 1
2293 VAR_POSITIONAL = 2
2294 KEYWORD_ONLY = 3
2295 VAR_KEYWORD = 4
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002296
2297 def __str__(self):
Yury Selivanov21e83a52014-03-27 11:23:13 -04002298 return self._name_
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002299
2300
Yury Selivanov21e83a52014-03-27 11:23:13 -04002301_POSITIONAL_ONLY = _ParameterKind.POSITIONAL_ONLY
2302_POSITIONAL_OR_KEYWORD = _ParameterKind.POSITIONAL_OR_KEYWORD
2303_VAR_POSITIONAL = _ParameterKind.VAR_POSITIONAL
2304_KEYWORD_ONLY = _ParameterKind.KEYWORD_ONLY
2305_VAR_KEYWORD = _ParameterKind.VAR_KEYWORD
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002306
2307
2308class Parameter:
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002309 """Represents a parameter in a function signature.
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002310
2311 Has the following public attributes:
2312
2313 * name : str
2314 The name of the parameter as a string.
2315 * default : object
2316 The default value for the parameter if specified. If the
Yury Selivanov8757ead2014-01-28 16:39:25 -05002317 parameter has no default value, this attribute is set to
2318 `Parameter.empty`.
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002319 * annotation
2320 The annotation for the parameter if specified. If the
Yury Selivanov8757ead2014-01-28 16:39:25 -05002321 parameter has no annotation, this attribute is set to
2322 `Parameter.empty`.
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002323 * kind : str
2324 Describes how argument values are bound to the parameter.
2325 Possible values: `Parameter.POSITIONAL_ONLY`,
2326 `Parameter.POSITIONAL_OR_KEYWORD`, `Parameter.VAR_POSITIONAL`,
2327 `Parameter.KEYWORD_ONLY`, `Parameter.VAR_KEYWORD`.
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002328 """
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002329
Yury Selivanov3f73ca22014-04-08 11:30:45 -04002330 __slots__ = ('_name', '_kind', '_default', '_annotation')
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002331
2332 POSITIONAL_ONLY = _POSITIONAL_ONLY
2333 POSITIONAL_OR_KEYWORD = _POSITIONAL_OR_KEYWORD
2334 VAR_POSITIONAL = _VAR_POSITIONAL
2335 KEYWORD_ONLY = _KEYWORD_ONLY
2336 VAR_KEYWORD = _VAR_KEYWORD
2337
2338 empty = _empty
2339
Yury Selivanov3f73ca22014-04-08 11:30:45 -04002340 def __init__(self, name, kind, *, default=_empty, annotation=_empty):
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002341
2342 if kind not in (_POSITIONAL_ONLY, _POSITIONAL_OR_KEYWORD,
2343 _VAR_POSITIONAL, _KEYWORD_ONLY, _VAR_KEYWORD):
2344 raise ValueError("invalid value for 'Parameter.kind' attribute")
2345 self._kind = kind
2346
2347 if default is not _empty:
2348 if kind in (_VAR_POSITIONAL, _VAR_KEYWORD):
2349 msg = '{} parameters cannot have default values'.format(kind)
2350 raise ValueError(msg)
2351 self._default = default
2352 self._annotation = annotation
2353
Yury Selivanov2393dca2014-01-27 15:07:58 -05002354 if name is _empty:
2355 raise ValueError('name is a required attribute for Parameter')
2356
2357 if not isinstance(name, str):
2358 raise TypeError("name must be a str, not a {!r}".format(name))
2359
2360 if not name.isidentifier():
2361 raise ValueError('{!r} is not a valid parameter name'.format(name))
2362
2363 self._name = name
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002364
Yury Selivanova5d63dd2014-03-27 11:31:43 -04002365 def __reduce__(self):
2366 return (type(self),
2367 (self._name, self._kind),
Yury Selivanov3f73ca22014-04-08 11:30:45 -04002368 {'_default': self._default,
Yury Selivanova5d63dd2014-03-27 11:31:43 -04002369 '_annotation': self._annotation})
2370
2371 def __setstate__(self, state):
Yury Selivanova5d63dd2014-03-27 11:31:43 -04002372 self._default = state['_default']
2373 self._annotation = state['_annotation']
2374
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002375 @property
2376 def name(self):
2377 return self._name
2378
2379 @property
2380 def default(self):
2381 return self._default
2382
2383 @property
2384 def annotation(self):
2385 return self._annotation
2386
2387 @property
2388 def kind(self):
2389 return self._kind
2390
Yury Selivanov3f73ca22014-04-08 11:30:45 -04002391 def replace(self, *, name=_void, kind=_void,
2392 annotation=_void, default=_void):
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002393 """Creates a customized copy of the Parameter."""
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002394
2395 if name is _void:
2396 name = self._name
2397
2398 if kind is _void:
2399 kind = self._kind
2400
2401 if annotation is _void:
2402 annotation = self._annotation
2403
2404 if default is _void:
2405 default = self._default
2406
Yury Selivanov3f73ca22014-04-08 11:30:45 -04002407 return type(self)(name, kind, default=default, annotation=annotation)
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002408
2409 def __str__(self):
2410 kind = self.kind
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002411 formatted = self._name
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002412
2413 # Add annotation and default value
2414 if self._annotation is not _empty:
2415 formatted = '{}:{}'.format(formatted,
2416 formatannotation(self._annotation))
2417
2418 if self._default is not _empty:
2419 formatted = '{}={}'.format(formatted, repr(self._default))
2420
2421 if kind == _VAR_POSITIONAL:
2422 formatted = '*' + formatted
2423 elif kind == _VAR_KEYWORD:
2424 formatted = '**' + formatted
2425
2426 return formatted
2427
2428 def __repr__(self):
Yury Selivanovf229bc52015-05-15 12:53:56 -04002429 return '<{} "{}">'.format(self.__class__.__name__, self)
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002430
Yury Selivanov67ae50e2014-04-08 11:46:50 -04002431 def __hash__(self):
Yury Selivanov08d4a4f2014-09-12 15:48:02 -04002432 return hash((self.name, self.kind, self.annotation, self.default))
Yury Selivanov67ae50e2014-04-08 11:46:50 -04002433
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002434 def __eq__(self, other):
Yury Selivanov692b3402015-05-14 18:20:01 -04002435 return (self is other or
2436 (issubclass(other.__class__, Parameter) and
2437 self._name == other._name and
2438 self._kind == other._kind and
2439 self._default == other._default and
2440 self._annotation == other._annotation))
2441
2442 def __ne__(self, other):
2443 return not self.__eq__(other)
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002444
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002445
2446class BoundArguments:
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002447 """Result of `Signature.bind` call. Holds the mapping of arguments
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002448 to the function's parameters.
2449
2450 Has the following public attributes:
2451
2452 * arguments : OrderedDict
2453 An ordered mutable mapping of parameters' names to arguments' values.
2454 Does not contain arguments' default values.
2455 * signature : Signature
2456 The Signature object that created this instance.
2457 * args : tuple
2458 Tuple of positional arguments values.
2459 * kwargs : dict
2460 Dict of keyword arguments values.
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002461 """
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002462
Yury Selivanov6abe0322015-05-13 17:18:41 -04002463 __slots__ = ('arguments', '_signature', '__weakref__')
2464
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002465 def __init__(self, signature, arguments):
2466 self.arguments = arguments
2467 self._signature = signature
2468
2469 @property
2470 def signature(self):
2471 return self._signature
2472
2473 @property
2474 def args(self):
2475 args = []
2476 for param_name, param in self._signature.parameters.items():
Yury Selivanov3f73ca22014-04-08 11:30:45 -04002477 if param.kind in (_VAR_KEYWORD, _KEYWORD_ONLY):
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002478 break
2479
2480 try:
2481 arg = self.arguments[param_name]
2482 except KeyError:
2483 # We're done here. Other arguments
2484 # will be mapped in 'BoundArguments.kwargs'
2485 break
2486 else:
2487 if param.kind == _VAR_POSITIONAL:
2488 # *args
2489 args.extend(arg)
2490 else:
2491 # plain argument
2492 args.append(arg)
2493
2494 return tuple(args)
2495
2496 @property
2497 def kwargs(self):
2498 kwargs = {}
2499 kwargs_started = False
2500 for param_name, param in self._signature.parameters.items():
2501 if not kwargs_started:
Yury Selivanov3f73ca22014-04-08 11:30:45 -04002502 if param.kind in (_VAR_KEYWORD, _KEYWORD_ONLY):
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002503 kwargs_started = True
2504 else:
2505 if param_name not in self.arguments:
2506 kwargs_started = True
2507 continue
2508
2509 if not kwargs_started:
2510 continue
2511
2512 try:
2513 arg = self.arguments[param_name]
2514 except KeyError:
2515 pass
2516 else:
2517 if param.kind == _VAR_KEYWORD:
2518 # **kwargs
2519 kwargs.update(arg)
2520 else:
2521 # plain keyword argument
2522 kwargs[param_name] = arg
2523
2524 return kwargs
2525
Yury Selivanovb907a512015-05-16 13:45:09 -04002526 def apply_defaults(self):
2527 """Set default values for missing arguments.
2528
2529 For variable-positional arguments (*args) the default is an
2530 empty tuple.
2531
2532 For variable-keyword arguments (**kwargs) the default is an
2533 empty dict.
2534 """
2535 arguments = self.arguments
2536 if not arguments:
2537 return
2538 new_arguments = []
2539 for name, param in self._signature.parameters.items():
2540 try:
2541 new_arguments.append((name, arguments[name]))
2542 except KeyError:
2543 if param.default is not _empty:
2544 val = param.default
2545 elif param.kind is _VAR_POSITIONAL:
2546 val = ()
2547 elif param.kind is _VAR_KEYWORD:
2548 val = {}
2549 else:
2550 # This BoundArguments was likely produced by
2551 # Signature.bind_partial().
2552 continue
2553 new_arguments.append((name, val))
2554 self.arguments = OrderedDict(new_arguments)
2555
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002556 def __eq__(self, other):
Yury Selivanov692b3402015-05-14 18:20:01 -04002557 return (self is other or
2558 (issubclass(other.__class__, BoundArguments) and
2559 self.signature == other.signature and
2560 self.arguments == other.arguments))
2561
2562 def __ne__(self, other):
2563 return not self.__eq__(other)
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002564
Yury Selivanov6abe0322015-05-13 17:18:41 -04002565 def __setstate__(self, state):
2566 self._signature = state['_signature']
2567 self.arguments = state['arguments']
2568
2569 def __getstate__(self):
2570 return {'_signature': self._signature, 'arguments': self.arguments}
2571
Yury Selivanov3f6538f2015-05-14 18:47:17 -04002572 def __repr__(self):
2573 args = []
2574 for arg, value in self.arguments.items():
2575 args.append('{}={!r}'.format(arg, value))
Yury Selivanovf229bc52015-05-15 12:53:56 -04002576 return '<{} ({})>'.format(self.__class__.__name__, ', '.join(args))
Yury Selivanov3f6538f2015-05-14 18:47:17 -04002577
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002578
2579class Signature:
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002580 """A Signature object represents the overall signature of a function.
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002581 It stores a Parameter object for each parameter accepted by the
2582 function, as well as information specific to the function itself.
2583
2584 A Signature object has the following public attributes and methods:
2585
2586 * parameters : OrderedDict
2587 An ordered mapping of parameters' names to the corresponding
2588 Parameter objects (keyword-only arguments are in the same order
2589 as listed in `code.co_varnames`).
2590 * return_annotation : object
2591 The annotation for the return type of the function if specified.
2592 If the function has no annotation for its return type, this
Yury Selivanov8757ead2014-01-28 16:39:25 -05002593 attribute is set to `Signature.empty`.
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002594 * bind(*args, **kwargs) -> BoundArguments
2595 Creates a mapping from positional and keyword arguments to
2596 parameters.
2597 * bind_partial(*args, **kwargs) -> BoundArguments
2598 Creates a partial mapping from positional and keyword arguments
2599 to parameters (simulating 'functools.partial' behavior.)
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002600 """
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002601
2602 __slots__ = ('_return_annotation', '_parameters')
2603
2604 _parameter_cls = Parameter
2605 _bound_arguments_cls = BoundArguments
2606
2607 empty = _empty
2608
2609 def __init__(self, parameters=None, *, return_annotation=_empty,
2610 __validate_parameters__=True):
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002611 """Constructs Signature from the given list of Parameter
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002612 objects and 'return_annotation'. All arguments are optional.
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002613 """
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002614
2615 if parameters is None:
2616 params = OrderedDict()
2617 else:
2618 if __validate_parameters__:
2619 params = OrderedDict()
2620 top_kind = _POSITIONAL_ONLY
Yury Selivanov07a9e452014-01-29 10:58:16 -05002621 kind_defaults = False
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002622
2623 for idx, param in enumerate(parameters):
2624 kind = param.kind
Yury Selivanov2393dca2014-01-27 15:07:58 -05002625 name = param.name
2626
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002627 if kind < top_kind:
Yury Selivanov3f73ca22014-04-08 11:30:45 -04002628 msg = 'wrong parameter order: {!r} before {!r}'
Yury Selivanov2393dca2014-01-27 15:07:58 -05002629 msg = msg.format(top_kind, kind)
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002630 raise ValueError(msg)
Yury Selivanov07a9e452014-01-29 10:58:16 -05002631 elif kind > top_kind:
2632 kind_defaults = False
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002633 top_kind = kind
2634
Yury Selivanov3f73ca22014-04-08 11:30:45 -04002635 if kind in (_POSITIONAL_ONLY, _POSITIONAL_OR_KEYWORD):
Yury Selivanov07a9e452014-01-29 10:58:16 -05002636 if param.default is _empty:
2637 if kind_defaults:
2638 # No default for this parameter, but the
2639 # previous parameter of the same kind had
2640 # a default
2641 msg = 'non-default argument follows default ' \
2642 'argument'
2643 raise ValueError(msg)
2644 else:
2645 # There is a default for this parameter.
2646 kind_defaults = True
2647
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002648 if name in params:
2649 msg = 'duplicate parameter name: {!r}'.format(name)
2650 raise ValueError(msg)
Yury Selivanov2393dca2014-01-27 15:07:58 -05002651
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002652 params[name] = param
2653 else:
2654 params = OrderedDict(((param.name, param)
2655 for param in parameters))
2656
2657 self._parameters = types.MappingProxyType(params)
2658 self._return_annotation = return_annotation
2659
2660 @classmethod
2661 def from_function(cls, func):
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002662 """Constructs Signature for the given python function."""
Yury Selivanov57c74fc2015-05-20 23:07:02 -04002663
2664 warnings.warn("inspect.Signature.from_function() is deprecated, "
Berker Peksagb5601582015-05-21 23:40:54 +03002665 "use Signature.from_callable()",
2666 DeprecationWarning, stacklevel=2)
Yury Selivanovcf45f022015-05-20 14:38:50 -04002667 return _signature_from_function(cls, func)
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002668
Larry Hastings44e2eaa2013-11-23 15:37:55 -08002669 @classmethod
2670 def from_builtin(cls, func):
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002671 """Constructs Signature for the given builtin function."""
Yury Selivanov57c74fc2015-05-20 23:07:02 -04002672
2673 warnings.warn("inspect.Signature.from_builtin() is deprecated, "
Berker Peksagb5601582015-05-21 23:40:54 +03002674 "use Signature.from_callable()",
2675 DeprecationWarning, stacklevel=2)
Yury Selivanov57d240e2014-02-19 16:27:23 -05002676 return _signature_from_builtin(cls, func)
Larry Hastings44e2eaa2013-11-23 15:37:55 -08002677
Yury Selivanovda396452014-03-27 12:09:24 -04002678 @classmethod
Yury Selivanovbcd4fc12015-05-20 14:30:08 -04002679 def from_callable(cls, obj, *, follow_wrapped=True):
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002680 """Constructs Signature for the given callable object."""
Yury Selivanovbcd4fc12015-05-20 14:30:08 -04002681 return _signature_from_callable(obj, sigcls=cls,
2682 follow_wrapper_chains=follow_wrapped)
Yury Selivanovda396452014-03-27 12:09:24 -04002683
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002684 @property
2685 def parameters(self):
2686 return self._parameters
2687
2688 @property
2689 def return_annotation(self):
2690 return self._return_annotation
2691
2692 def replace(self, *, parameters=_void, return_annotation=_void):
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002693 """Creates a customized copy of the Signature.
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002694 Pass 'parameters' and/or 'return_annotation' arguments
2695 to override them in the new copy.
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002696 """
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002697
2698 if parameters is _void:
2699 parameters = self.parameters.values()
2700
2701 if return_annotation is _void:
2702 return_annotation = self._return_annotation
2703
2704 return type(self)(parameters,
2705 return_annotation=return_annotation)
2706
Yury Selivanov08d4a4f2014-09-12 15:48:02 -04002707 def _hash_basis(self):
2708 params = tuple(param for param in self.parameters.values()
2709 if param.kind != _KEYWORD_ONLY)
2710
2711 kwo_params = {param.name: param for param in self.parameters.values()
2712 if param.kind == _KEYWORD_ONLY}
2713
2714 return params, kwo_params, self.return_annotation
2715
Yury Selivanov67ae50e2014-04-08 11:46:50 -04002716 def __hash__(self):
Yury Selivanov08d4a4f2014-09-12 15:48:02 -04002717 params, kwo_params, return_annotation = self._hash_basis()
2718 kwo_params = frozenset(kwo_params.values())
2719 return hash((params, kwo_params, return_annotation))
Yury Selivanov67ae50e2014-04-08 11:46:50 -04002720
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002721 def __eq__(self, other):
Yury Selivanov692b3402015-05-14 18:20:01 -04002722 return (self is other or
2723 (isinstance(other, Signature) and
2724 self._hash_basis() == other._hash_basis()))
2725
2726 def __ne__(self, other):
2727 return not self.__eq__(other)
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002728
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002729 def _bind(self, args, kwargs, *, partial=False):
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002730 """Private method. Don't use directly."""
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002731
2732 arguments = OrderedDict()
2733
2734 parameters = iter(self.parameters.values())
2735 parameters_ex = ()
2736 arg_vals = iter(args)
2737
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002738 while True:
2739 # Let's iterate through the positional arguments and corresponding
2740 # parameters
2741 try:
2742 arg_val = next(arg_vals)
2743 except StopIteration:
2744 # No more positional arguments
2745 try:
2746 param = next(parameters)
2747 except StopIteration:
2748 # No more parameters. That's it. Just need to check that
2749 # we have no `kwargs` after this while loop
2750 break
2751 else:
2752 if param.kind == _VAR_POSITIONAL:
2753 # That's OK, just empty *args. Let's start parsing
2754 # kwargs
2755 break
2756 elif param.name in kwargs:
2757 if param.kind == _POSITIONAL_ONLY:
2758 msg = '{arg!r} parameter is positional only, ' \
2759 'but was passed as a keyword'
2760 msg = msg.format(arg=param.name)
2761 raise TypeError(msg) from None
2762 parameters_ex = (param,)
2763 break
2764 elif (param.kind == _VAR_KEYWORD or
2765 param.default is not _empty):
2766 # That's fine too - we have a default value for this
2767 # parameter. So, lets start parsing `kwargs`, starting
2768 # with the current parameter
2769 parameters_ex = (param,)
2770 break
2771 else:
Yury Selivanov38b0d5a2014-01-28 17:27:39 -05002772 # No default, not VAR_KEYWORD, not VAR_POSITIONAL,
2773 # not in `kwargs`
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002774 if partial:
2775 parameters_ex = (param,)
2776 break
2777 else:
Yury Selivanov86872752015-05-19 00:27:49 -04002778 msg = 'missing a required argument: {arg!r}'
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002779 msg = msg.format(arg=param.name)
2780 raise TypeError(msg) from None
2781 else:
2782 # We have a positional argument to process
2783 try:
2784 param = next(parameters)
2785 except StopIteration:
2786 raise TypeError('too many positional arguments') from None
2787 else:
2788 if param.kind in (_VAR_KEYWORD, _KEYWORD_ONLY):
2789 # Looks like we have no parameter for this positional
2790 # argument
Yury Selivanov86872752015-05-19 00:27:49 -04002791 raise TypeError(
2792 'too many positional arguments') from None
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002793
2794 if param.kind == _VAR_POSITIONAL:
2795 # We have an '*args'-like argument, let's fill it with
2796 # all positional arguments we have left and move on to
2797 # the next phase
2798 values = [arg_val]
2799 values.extend(arg_vals)
2800 arguments[param.name] = tuple(values)
2801 break
2802
2803 if param.name in kwargs:
Yury Selivanov86872752015-05-19 00:27:49 -04002804 raise TypeError(
2805 'multiple values for argument {arg!r}'.format(
2806 arg=param.name)) from None
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002807
2808 arguments[param.name] = arg_val
2809
2810 # Now, we iterate through the remaining parameters to process
2811 # keyword arguments
2812 kwargs_param = None
2813 for param in itertools.chain(parameters_ex, parameters):
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002814 if param.kind == _VAR_KEYWORD:
2815 # Memorize that we have a '**kwargs'-like parameter
2816 kwargs_param = param
2817 continue
2818
Yury Selivanov38b0d5a2014-01-28 17:27:39 -05002819 if param.kind == _VAR_POSITIONAL:
2820 # Named arguments don't refer to '*args'-like parameters.
2821 # We only arrive here if the positional arguments ended
2822 # before reaching the last parameter before *args.
2823 continue
2824
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002825 param_name = param.name
2826 try:
2827 arg_val = kwargs.pop(param_name)
2828 except KeyError:
2829 # We have no value for this parameter. It's fine though,
2830 # if it has a default value, or it is an '*args'-like
2831 # parameter, left alone by the processing of positional
2832 # arguments.
2833 if (not partial and param.kind != _VAR_POSITIONAL and
2834 param.default is _empty):
Yury Selivanov86872752015-05-19 00:27:49 -04002835 raise TypeError('missing a required argument: {arg!r}'. \
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002836 format(arg=param_name)) from None
2837
2838 else:
Yury Selivanov9b9ac952014-01-28 20:54:28 -05002839 if param.kind == _POSITIONAL_ONLY:
2840 # This should never happen in case of a properly built
2841 # Signature object (but let's have this check here
2842 # to ensure correct behaviour just in case)
2843 raise TypeError('{arg!r} parameter is positional only, '
2844 'but was passed as a keyword'. \
2845 format(arg=param.name))
2846
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002847 arguments[param_name] = arg_val
2848
2849 if kwargs:
2850 if kwargs_param is not None:
2851 # Process our '**kwargs'-like parameter
2852 arguments[kwargs_param.name] = kwargs
2853 else:
Yury Selivanov86872752015-05-19 00:27:49 -04002854 raise TypeError(
2855 'got an unexpected keyword argument {arg!r}'.format(
2856 arg=next(iter(kwargs))))
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002857
2858 return self._bound_arguments_cls(self, arguments)
2859
Yury Selivanovc45873e2014-01-29 12:10:27 -05002860 def bind(*args, **kwargs):
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002861 """Get a BoundArguments object, that maps the passed `args`
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002862 and `kwargs` to the function's signature. Raises `TypeError`
2863 if the passed arguments can not be bound.
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002864 """
Yury Selivanovc45873e2014-01-29 12:10:27 -05002865 return args[0]._bind(args[1:], kwargs)
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002866
Yury Selivanovc45873e2014-01-29 12:10:27 -05002867 def bind_partial(*args, **kwargs):
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002868 """Get a BoundArguments object, that partially maps the
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002869 passed `args` and `kwargs` to the function's signature.
2870 Raises `TypeError` if the passed arguments can not be bound.
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002871 """
Yury Selivanovc45873e2014-01-29 12:10:27 -05002872 return args[0]._bind(args[1:], kwargs, partial=True)
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002873
Yury Selivanova5d63dd2014-03-27 11:31:43 -04002874 def __reduce__(self):
2875 return (type(self),
2876 (tuple(self._parameters.values()),),
2877 {'_return_annotation': self._return_annotation})
2878
2879 def __setstate__(self, state):
2880 self._return_annotation = state['_return_annotation']
2881
Yury Selivanov374375d2014-03-27 12:41:53 -04002882 def __repr__(self):
Yury Selivanovf229bc52015-05-15 12:53:56 -04002883 return '<{} {}>'.format(self.__class__.__name__, self)
Yury Selivanov374375d2014-03-27 12:41:53 -04002884
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002885 def __str__(self):
2886 result = []
Yury Selivanov2393dca2014-01-27 15:07:58 -05002887 render_pos_only_separator = False
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002888 render_kw_only_separator = True
Yury Selivanov2393dca2014-01-27 15:07:58 -05002889 for param in self.parameters.values():
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002890 formatted = str(param)
2891
2892 kind = param.kind
Yury Selivanov2393dca2014-01-27 15:07:58 -05002893
2894 if kind == _POSITIONAL_ONLY:
2895 render_pos_only_separator = True
2896 elif render_pos_only_separator:
2897 # It's not a positional-only parameter, and the flag
2898 # is set to 'True' (there were pos-only params before.)
2899 result.append('/')
2900 render_pos_only_separator = False
2901
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002902 if kind == _VAR_POSITIONAL:
2903 # OK, we have an '*args'-like parameter, so we won't need
2904 # a '*' to separate keyword-only arguments
2905 render_kw_only_separator = False
2906 elif kind == _KEYWORD_ONLY and render_kw_only_separator:
2907 # We have a keyword-only parameter to render and we haven't
2908 # rendered an '*args'-like parameter before, so add a '*'
2909 # separator to the parameters list ("foo(arg1, *, arg2)" case)
2910 result.append('*')
2911 # This condition should be only triggered once, so
2912 # reset the flag
2913 render_kw_only_separator = False
2914
2915 result.append(formatted)
2916
Yury Selivanov2393dca2014-01-27 15:07:58 -05002917 if render_pos_only_separator:
2918 # There were only positional-only parameters, hence the
2919 # flag was not reset to 'False'
2920 result.append('/')
2921
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002922 rendered = '({})'.format(', '.join(result))
2923
2924 if self.return_annotation is not _empty:
2925 anno = formatannotation(self.return_annotation)
2926 rendered += ' -> {}'.format(anno)
2927
2928 return rendered
Nick Coghlanf94a16b2013-09-22 22:46:49 +10002929
Yury Selivanovda396452014-03-27 12:09:24 -04002930
Yury Selivanovbcd4fc12015-05-20 14:30:08 -04002931def signature(obj, *, follow_wrapped=True):
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002932 """Get a signature object for the passed callable."""
Yury Selivanovbcd4fc12015-05-20 14:30:08 -04002933 return Signature.from_callable(obj, follow_wrapped=follow_wrapped)
Yury Selivanovda396452014-03-27 12:09:24 -04002934
2935
Nick Coghlanf94a16b2013-09-22 22:46:49 +10002936def _main():
2937 """ Logic for inspecting an object given at command line """
2938 import argparse
2939 import importlib
2940
2941 parser = argparse.ArgumentParser()
2942 parser.add_argument(
2943 'object',
2944 help="The object to be analysed. "
2945 "It supports the 'module:qualname' syntax")
2946 parser.add_argument(
2947 '-d', '--details', action='store_true',
2948 help='Display info about the module rather than its source code')
2949
2950 args = parser.parse_args()
2951
2952 target = args.object
2953 mod_name, has_attrs, attrs = target.partition(":")
2954 try:
2955 obj = module = importlib.import_module(mod_name)
2956 except Exception as exc:
2957 msg = "Failed to import {} ({}: {})".format(mod_name,
2958 type(exc).__name__,
2959 exc)
2960 print(msg, file=sys.stderr)
2961 exit(2)
2962
2963 if has_attrs:
2964 parts = attrs.split(".")
2965 obj = module
2966 for part in parts:
2967 obj = getattr(obj, part)
2968
2969 if module.__name__ in sys.builtin_module_names:
2970 print("Can't get info for builtin modules.", file=sys.stderr)
2971 exit(1)
2972
2973 if args.details:
2974 print('Target: {}'.format(target))
2975 print('Origin: {}'.format(getsourcefile(module)))
2976 print('Cached: {}'.format(module.__cached__))
2977 if obj is module:
2978 print('Loader: {}'.format(repr(module.__loader__)))
2979 if hasattr(module, '__path__'):
2980 print('Submodule search path: {}'.format(module.__path__))
2981 else:
2982 try:
2983 __, lineno = findsource(obj)
2984 except Exception:
2985 pass
2986 else:
2987 print('Line: {}'.format(lineno))
2988
2989 print('\n')
2990 else:
2991 print(getsource(obj))
2992
2993
2994if __name__ == "__main__":
2995 _main()