blob: 74f3b3c3bbb4a81566e4363e6fe9e0b5c33bd3cf [file] [log] [blame]
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001"""Get useful information from live Python objects.
2
3This module encapsulates the interface provided by the internal special
Neal Norwitz221085d2007-02-25 20:55:47 +00004attributes (co_*, im_*, tb_*, etc.) in a friendlier fashion.
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00005It also provides some help for examining source code and class layout.
6
7Here are some of the useful functions provided by this module:
8
Christian Heimes7131fd92008-02-19 14:21:46 +00009 ismodule(), isclass(), ismethod(), isfunction(), isgeneratorfunction(),
10 isgenerator(), istraceback(), isframe(), iscode(), isbuiltin(),
11 isroutine() - check object types
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +000012 getmembers() - get members of an object that satisfy a given condition
13
14 getfile(), getsourcefile(), getsource() - find an object's source code
15 getdoc(), getcomments() - get documentation on an object
16 getmodule() - determine the module that an object came from
17 getclasstree() - arrange classes so as to represent their hierarchy
18
Berker Peksagfa3922c2015-07-31 04:11:29 +030019 getargvalues(), getcallargs() - get info about function arguments
Yury Selivanov0cf3ed62014-04-01 10:17:08 -040020 getfullargspec() - same, with support for Python 3 features
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 Selivanov5376ba92015-06-22 12:19:30 -0400178 object.__code__.co_flags & CO_GENERATOR)
Yury Selivanov75445082015-05-11 22:57:16 -0400179
180def iscoroutinefunction(object):
181 """Return true if the object is a coroutine function.
182
183 Coroutine functions are defined with "async def" syntax,
184 or generators decorated with "types.coroutine".
185 """
186 return bool((isfunction(object) or ismethod(object)) and
Yury Selivanov5376ba92015-06-22 12:19:30 -0400187 object.__code__.co_flags & CO_COROUTINE)
Yury Selivanov75445082015-05-11 22:57:16 -0400188
Christian Heimes7131fd92008-02-19 14:21:46 +0000189def isgenerator(object):
190 """Return true if the object is a generator.
191
192 Generator objects provide these attributes:
Ezio Melotti30b9d5d2013-08-17 15:50:46 +0300193 __iter__ defined to support iteration over container
Christian Heimes7131fd92008-02-19 14:21:46 +0000194 close raises a new GeneratorExit exception inside the
195 generator to terminate the iteration
196 gi_code code object
197 gi_frame frame object or possibly None once the generator has
198 been exhausted
199 gi_running set to 1 when generator is executing, 0 otherwise
200 next return the next item from the container
201 send resumes the generator and "sends" a value that becomes
202 the result of the current yield-expression
203 throw used to raise an exception inside the generator"""
Yury Selivanov5376ba92015-06-22 12:19:30 -0400204 return isinstance(object, types.GeneratorType)
Yury Selivanov75445082015-05-11 22:57:16 -0400205
206def iscoroutine(object):
207 """Return true if the object is a coroutine."""
Yury Selivanov5376ba92015-06-22 12:19:30 -0400208 return isinstance(object, types.CoroutineType)
Christian Heimes7131fd92008-02-19 14:21:46 +0000209
Yury Selivanovfdbeb2b2015-07-03 13:11:35 -0400210def isawaitable(object):
211 """Return true is object can be passed to an ``await`` expression."""
212 return (isinstance(object, types.CoroutineType) or
213 isinstance(object, types.GeneratorType) and
214 object.gi_code.co_flags & CO_ITERABLE_COROUTINE or
215 isinstance(object, collections.abc.Awaitable))
216
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 Storchaka5cf2b722015-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__
Serhiy Storchakaac4bdcc2015-10-29 08:15:50 +0200530 # Should be tested before isdatadescriptor().
531 elif isinstance(obj, property):
532 func = obj.fget
533 name = func.__name__
534 cls = _findclass(func)
535 if cls is None or getattr(cls, name) is not obj:
536 return None
Serhiy Storchaka5cf2b722015-04-03 22:38:53 +0300537 elif ismethoddescriptor(obj) or isdatadescriptor(obj):
538 name = obj.__name__
539 cls = obj.__objclass__
540 if getattr(cls, name) is not obj:
541 return None
Serhiy Storchaka5cf2b722015-04-03 22:38:53 +0300542 else:
543 return None
544
545 for base in cls.__mro__:
546 try:
547 doc = getattr(base, name).__doc__
548 except AttributeError:
549 continue
550 if doc is not None:
551 return doc
552 return None
553
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000554def getdoc(object):
555 """Get the documentation string for an object.
556
557 All tabs are expanded to spaces. To clean up docstrings that are
558 indented to line up with blocks of code, any whitespace than can be
559 uniformly removed from the second line onwards is removed."""
Tim Peters24008312002-03-17 18:56:20 +0000560 try:
561 doc = object.__doc__
562 except AttributeError:
563 return None
Serhiy Storchaka5cf2b722015-04-03 22:38:53 +0300564 if doc is None:
565 try:
566 doc = _finddoc(object)
567 except (AttributeError, TypeError):
568 return None
Guido van Rossum3172c5d2007-10-16 18:12:55 +0000569 if not isinstance(doc, str):
Tim Peters24008312002-03-17 18:56:20 +0000570 return None
Georg Brandl0c77a822008-06-10 16:37:50 +0000571 return cleandoc(doc)
572
573def cleandoc(doc):
574 """Clean up indentation from docstrings.
575
576 Any whitespace that can be uniformly removed from the second line
577 onwards is removed."""
Tim Peters24008312002-03-17 18:56:20 +0000578 try:
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000579 lines = doc.expandtabs().split('\n')
Tim Peters24008312002-03-17 18:56:20 +0000580 except UnicodeError:
581 return None
582 else:
Ka-Ping Yeea59ef7b2002-11-30 03:53:15 +0000583 # Find minimum indentation of any non-blank lines after first line.
Christian Heimesa37d4c62007-12-04 23:02:19 +0000584 margin = sys.maxsize
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000585 for line in lines[1:]:
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000586 content = len(line.lstrip())
Ka-Ping Yeea59ef7b2002-11-30 03:53:15 +0000587 if content:
588 indent = len(line) - content
589 margin = min(margin, indent)
590 # Remove indentation.
591 if lines:
592 lines[0] = lines[0].lstrip()
Christian Heimesa37d4c62007-12-04 23:02:19 +0000593 if margin < sys.maxsize:
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000594 for i in range(1, len(lines)): lines[i] = lines[i][margin:]
Ka-Ping Yeea59ef7b2002-11-30 03:53:15 +0000595 # Remove any trailing or leading blank lines.
596 while lines and not lines[-1]:
597 lines.pop()
598 while lines and not lines[0]:
599 lines.pop(0)
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000600 return '\n'.join(lines)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000601
602def getfile(object):
Ka-Ping Yeec113c242001-03-02 02:08:53 +0000603 """Work out which source or compiled file an object was defined in."""
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000604 if ismodule(object):
605 if hasattr(object, '__file__'):
606 return object.__file__
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +0000607 raise TypeError('{!r} is a built-in module'.format(object))
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000608 if isclass(object):
Yury Selivanov2eed8b72014-01-27 13:24:56 -0500609 if hasattr(object, '__module__'):
610 object = sys.modules.get(object.__module__)
611 if hasattr(object, '__file__'):
612 return object.__file__
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +0000613 raise TypeError('{!r} is a built-in class'.format(object))
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000614 if ismethod(object):
Christian Heimesff737952007-11-27 10:40:20 +0000615 object = object.__func__
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000616 if isfunction(object):
Neal Norwitz221085d2007-02-25 20:55:47 +0000617 object = object.__code__
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000618 if istraceback(object):
619 object = object.tb_frame
620 if isframe(object):
621 object = object.f_code
622 if iscode(object):
623 return object.co_filename
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +0000624 raise TypeError('{!r} is not a module, class, method, '
625 'function, traceback, frame, or code object'.format(object))
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000626
Ka-Ping Yee4d6fc7f2001-04-10 11:43:00 +0000627def getmodulename(path):
628 """Return the module name for a given file, or None."""
Nick Coghlan76e07702012-07-18 23:14:57 +1000629 fname = os.path.basename(path)
630 # Check for paths that look like an actual module file
631 suffixes = [(-len(suffix), suffix)
632 for suffix in importlib.machinery.all_suffixes()]
633 suffixes.sort() # try longest suffixes first, in case they overlap
634 for neglen, suffix in suffixes:
635 if fname.endswith(suffix):
636 return fname[:neglen]
637 return None
Ka-Ping Yee4d6fc7f2001-04-10 11:43:00 +0000638
Ka-Ping Yeec113c242001-03-02 02:08:53 +0000639def getsourcefile(object):
R. David Murraya1b37402010-06-17 02:04:29 +0000640 """Return the filename that can be used to locate an object's source.
641 Return None if no way can be identified to get the source.
642 """
Ka-Ping Yeec113c242001-03-02 02:08:53 +0000643 filename = getfile(object)
Brett Cannoncb66eb02012-05-11 12:58:42 -0400644 all_bytecode_suffixes = importlib.machinery.DEBUG_BYTECODE_SUFFIXES[:]
645 all_bytecode_suffixes += importlib.machinery.OPTIMIZED_BYTECODE_SUFFIXES[:]
646 if any(filename.endswith(s) for s in all_bytecode_suffixes):
647 filename = (os.path.splitext(filename)[0] +
648 importlib.machinery.SOURCE_SUFFIXES[0])
649 elif any(filename.endswith(s) for s in
650 importlib.machinery.EXTENSION_SUFFIXES):
651 return None
Thomas Wouters477c8d52006-05-27 19:21:47 +0000652 if os.path.exists(filename):
653 return filename
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000654 # only return a non-existent filename if the module has a PEP 302 loader
Brett Cannon4c14b5d2013-05-04 13:56:58 -0400655 if getattr(getmodule(object, filename), '__loader__', None) is not None:
Ka-Ping Yeec113c242001-03-02 02:08:53 +0000656 return filename
R. David Murraya1b37402010-06-17 02:04:29 +0000657 # or it is in the linecache
658 if filename in linecache.cache:
659 return filename
Ka-Ping Yeec113c242001-03-02 02:08:53 +0000660
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000661def getabsfile(object, _filename=None):
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000662 """Return an absolute path to the source or compiled file for an object.
Ka-Ping Yeec113c242001-03-02 02:08:53 +0000663
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000664 The idea is for each object to have a unique origin, so this routine
665 normalizes the result as much as possible."""
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000666 if _filename is None:
667 _filename = getsourcefile(object) or getfile(object)
668 return os.path.normcase(os.path.abspath(_filename))
Ka-Ping Yeec113c242001-03-02 02:08:53 +0000669
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000670modulesbyfile = {}
Thomas Wouters89f507f2006-12-13 04:49:30 +0000671_filesbymodname = {}
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000672
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000673def getmodule(object, _filename=None):
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000674 """Return the module an object was defined in, or None if not found."""
Ka-Ping Yee202c99b2001-04-13 09:15:08 +0000675 if ismodule(object):
676 return object
Johannes Gijsbers93245262004-09-11 15:53:22 +0000677 if hasattr(object, '__module__'):
Ka-Ping Yee8b58b842001-03-01 13:56:16 +0000678 return sys.modules.get(object.__module__)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000679 # Try the filename to modulename cache
680 if _filename is not None and _filename in modulesbyfile:
681 return sys.modules.get(modulesbyfile[_filename])
682 # Try the cache again with the absolute file name
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000683 try:
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000684 file = getabsfile(object, _filename)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000685 except TypeError:
686 return None
Raymond Hettinger54f02222002-06-01 14:18:47 +0000687 if file in modulesbyfile:
Ka-Ping Yeeb38bbbd2003-03-28 16:29:50 +0000688 return sys.modules.get(modulesbyfile[file])
Thomas Wouters89f507f2006-12-13 04:49:30 +0000689 # Update the filename to module name cache and check yet again
690 # Copy sys.modules in order to cope with changes while iterating
Éric Araujoa74f8ef2011-11-29 16:58:53 +0100691 for modname, module in list(sys.modules.items()):
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000692 if ismodule(module) and hasattr(module, '__file__'):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000693 f = module.__file__
694 if f == _filesbymodname.get(modname, None):
695 # Have already mapped this module, so skip it
696 continue
697 _filesbymodname[modname] = f
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000698 f = getabsfile(module)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000699 # Always map to the name the module knows itself by
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000700 modulesbyfile[f] = modulesbyfile[
701 os.path.realpath(f)] = module.__name__
Raymond Hettinger54f02222002-06-01 14:18:47 +0000702 if file in modulesbyfile:
Ka-Ping Yeeb38bbbd2003-03-28 16:29:50 +0000703 return sys.modules.get(modulesbyfile[file])
Thomas Wouters89f507f2006-12-13 04:49:30 +0000704 # Check the main module
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000705 main = sys.modules['__main__']
Brett Cannon4a671fe2003-06-15 22:33:28 +0000706 if not hasattr(object, '__name__'):
707 return None
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000708 if hasattr(main, object.__name__):
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000709 mainobject = getattr(main, object.__name__)
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000710 if mainobject is object:
711 return main
Thomas Wouters89f507f2006-12-13 04:49:30 +0000712 # Check builtins
Georg Brandl1a3284e2007-12-02 09:40:06 +0000713 builtin = sys.modules['builtins']
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000714 if hasattr(builtin, object.__name__):
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000715 builtinobject = getattr(builtin, object.__name__)
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000716 if builtinobject is object:
717 return builtin
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000718
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000719def findsource(object):
720 """Return the entire source file and starting line number for an object.
721
722 The argument may be a module, class, method, function, traceback, frame,
723 or code object. The source code is returned as a list of all the lines
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200724 in the file and the line number indexes a line in that list. An OSError
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000725 is raised if the source code cannot be retrieved."""
Benjamin Peterson9620cc02011-06-11 15:53:11 -0500726
Yury Selivanovef1e7502014-12-08 16:05:34 -0500727 file = getsourcefile(object)
728 if file:
729 # Invalidate cache if needed.
730 linecache.checkcache(file)
731 else:
732 file = getfile(object)
733 # Allow filenames in form of "<something>" to pass through.
734 # `doctest` monkeypatches `linecache` module to enable
735 # inspection, so let `linecache.getlines` to be called.
736 if not (file.startswith('<') and file.endswith('>')):
737 raise OSError('source code not available')
Benjamin Peterson9620cc02011-06-11 15:53:11 -0500738
Thomas Wouters89f507f2006-12-13 04:49:30 +0000739 module = getmodule(object, file)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000740 if module:
741 lines = linecache.getlines(file, module.__dict__)
742 else:
743 lines = linecache.getlines(file)
Neil Schemenauerf06f8532002-03-23 23:51:04 +0000744 if not lines:
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200745 raise OSError('could not get source code')
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000746
747 if ismodule(object):
748 return lines, 0
749
750 if isclass(object):
751 name = object.__name__
Thomas Wouters89f507f2006-12-13 04:49:30 +0000752 pat = re.compile(r'^(\s*)class\s*' + name + r'\b')
753 # make some effort to find the best matching class definition:
754 # use the one with the least indentation, which is the one
755 # that's most probably not inside a function definition.
756 candidates = []
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000757 for i in range(len(lines)):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000758 match = pat.match(lines[i])
759 if match:
760 # if it's at toplevel, it's already the best one
761 if lines[i][0] == 'c':
762 return lines, i
763 # else add whitespace to candidate list
764 candidates.append((match.group(1), i))
765 if candidates:
766 # this will sort by whitespace, and by line number,
767 # less whitespace first
768 candidates.sort()
769 return lines, candidates[0][1]
Jeremy Hyltonab919022003-06-27 18:41:20 +0000770 else:
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200771 raise OSError('could not find class definition')
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000772
773 if ismethod(object):
Christian Heimesff737952007-11-27 10:40:20 +0000774 object = object.__func__
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000775 if isfunction(object):
Neal Norwitz221085d2007-02-25 20:55:47 +0000776 object = object.__code__
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000777 if istraceback(object):
778 object = object.tb_frame
779 if isframe(object):
780 object = object.f_code
781 if iscode(object):
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000782 if not hasattr(object, 'co_firstlineno'):
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200783 raise OSError('could not find function definition')
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000784 lnum = object.co_firstlineno - 1
Yury Selivanove4e811d2015-07-21 19:01:52 +0300785 pat = re.compile(r'^(\s*def\s)|(\s*async\s+def\s)|(.*(?<!\w)lambda(:|\s))|^(\s*@)')
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000786 while lnum > 0:
Ka-Ping Yeea6e59712001-03-10 09:31:55 +0000787 if pat.match(lines[lnum]): break
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000788 lnum = lnum - 1
789 return lines, lnum
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200790 raise OSError('could not find code object')
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000791
792def getcomments(object):
Jeremy Hyltonb4c17c82002-03-28 23:01:56 +0000793 """Get lines of comments immediately preceding an object's source code.
794
795 Returns None when source can't be found.
796 """
797 try:
798 lines, lnum = findsource(object)
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200799 except (OSError, TypeError):
Jeremy Hyltonb4c17c82002-03-28 23:01:56 +0000800 return None
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000801
802 if ismodule(object):
803 # Look for a comment block at the top of the file.
804 start = 0
Ka-Ping Yeeb910efe2001-04-12 13:17:17 +0000805 if lines and lines[0][:2] == '#!': start = 1
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000806 while start < len(lines) and lines[start].strip() in ('', '#'):
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000807 start = start + 1
Ka-Ping Yeeb910efe2001-04-12 13:17:17 +0000808 if start < len(lines) and lines[start][:1] == '#':
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000809 comments = []
810 end = start
811 while end < len(lines) and lines[end][:1] == '#':
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000812 comments.append(lines[end].expandtabs())
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000813 end = end + 1
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000814 return ''.join(comments)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000815
816 # Look for a preceding block of comments at the same indentation.
817 elif lnum > 0:
818 indent = indentsize(lines[lnum])
819 end = lnum - 1
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000820 if end >= 0 and lines[end].lstrip()[:1] == '#' and \
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000821 indentsize(lines[end]) == indent:
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000822 comments = [lines[end].expandtabs().lstrip()]
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000823 if end > 0:
824 end = end - 1
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000825 comment = lines[end].expandtabs().lstrip()
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000826 while comment[:1] == '#' and indentsize(lines[end]) == indent:
827 comments[:0] = [comment]
828 end = end - 1
829 if end < 0: break
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000830 comment = lines[end].expandtabs().lstrip()
831 while comments and comments[0].strip() == '#':
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000832 comments[:1] = []
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000833 while comments and comments[-1].strip() == '#':
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000834 comments[-1:] = []
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000835 return ''.join(comments)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000836
Tim Peters4efb6e92001-06-29 23:51:08 +0000837class EndOfBlock(Exception): pass
838
839class BlockFinder:
840 """Provide a tokeneater() method to detect the end of a code block."""
841 def __init__(self):
842 self.indent = 0
Johannes Gijsbersa5855d52005-03-12 16:37:11 +0000843 self.islambda = False
Johannes Gijsbers1542f342004-12-12 16:46:28 +0000844 self.started = False
845 self.passline = False
Meador Inge5b718d72015-07-23 22:49:37 -0500846 self.indecorator = False
847 self.decoratorhasargs = False
Armin Rigodd5c0232005-09-25 11:45:45 +0000848 self.last = 1
Tim Peters4efb6e92001-06-29 23:51:08 +0000849
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000850 def tokeneater(self, type, token, srowcol, erowcol, line):
Meador Inge5b718d72015-07-23 22:49:37 -0500851 if not self.started and not self.indecorator:
852 # skip any decorators
853 if token == "@":
854 self.indecorator = True
Armin Rigodd5c0232005-09-25 11:45:45 +0000855 # look for the first "def", "class" or "lambda"
Meador Inge5b718d72015-07-23 22:49:37 -0500856 elif token in ("def", "class", "lambda"):
Johannes Gijsbersa5855d52005-03-12 16:37:11 +0000857 if token == "lambda":
858 self.islambda = True
Johannes Gijsbers1542f342004-12-12 16:46:28 +0000859 self.started = True
Armin Rigodd5c0232005-09-25 11:45:45 +0000860 self.passline = True # skip to the end of the line
Meador Inge5b718d72015-07-23 22:49:37 -0500861 elif token == "(":
862 if self.indecorator:
863 self.decoratorhasargs = True
864 elif token == ")":
865 if self.indecorator:
866 self.indecorator = False
867 self.decoratorhasargs = False
Tim Peters4efb6e92001-06-29 23:51:08 +0000868 elif type == tokenize.NEWLINE:
Armin Rigodd5c0232005-09-25 11:45:45 +0000869 self.passline = False # stop skipping when a NEWLINE is seen
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000870 self.last = srowcol[0]
Armin Rigodd5c0232005-09-25 11:45:45 +0000871 if self.islambda: # lambdas always end at the first NEWLINE
872 raise EndOfBlock
Meador Inge5b718d72015-07-23 22:49:37 -0500873 # hitting a NEWLINE when in a decorator without args
874 # ends the decorator
875 if self.indecorator and not self.decoratorhasargs:
876 self.indecorator = False
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
905def getsourcelines(object):
906 """Return a list of source lines and starting line number for an object.
907
908 The argument may be a module, class, method, function, traceback, frame,
909 or code object. The source code is returned as a list of the lines
910 corresponding to the object and the line number indicates where in the
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200911 original source file the first line of code was found. An OSError is
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000912 raised if the source code cannot be retrieved."""
Yury Selivanov081bbf62014-09-26 17:34:54 -0400913 object = unwrap(object)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000914 lines, lnum = findsource(object)
915
Meador Inge5b718d72015-07-23 22:49:37 -0500916 if ismodule(object):
917 return lines, 0
918 else:
919 return getblock(lines[lnum:]), lnum + 1
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000920
921def getsource(object):
922 """Return the text of the source code for an object.
923
924 The argument may be a module, class, method, function, traceback, frame,
925 or code object. The source code is returned as a single string. An
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200926 OSError is raised if the source code cannot be retrieved."""
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000927 lines, lnum = getsourcelines(object)
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000928 return ''.join(lines)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000929
930# --------------------------------------------------- class tree extraction
931def walktree(classes, children, parent):
932 """Recursive helper function for getclasstree()."""
933 results = []
Raymond Hettingera1a992c2005-03-11 06:46:45 +0000934 classes.sort(key=attrgetter('__module__', '__name__'))
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000935 for c in classes:
936 results.append((c, c.__bases__))
Raymond Hettinger54f02222002-06-01 14:18:47 +0000937 if c in children:
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000938 results.append(walktree(children[c], children, c))
939 return results
940
Georg Brandl5ce83a02009-06-01 17:23:51 +0000941def getclasstree(classes, unique=False):
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000942 """Arrange the given list of classes into a hierarchy of nested lists.
943
944 Where a nested list appears, it contains classes derived from the class
945 whose entry immediately precedes the list. Each entry is a 2-tuple
946 containing a class and a tuple of its base classes. If the 'unique'
947 argument is true, exactly one entry appears in the returned structure
948 for each class in the given list. Otherwise, classes using multiple
949 inheritance and their descendants will appear multiple times."""
950 children = {}
951 roots = []
952 for c in classes:
953 if c.__bases__:
954 for parent in c.__bases__:
Raymond Hettinger54f02222002-06-01 14:18:47 +0000955 if not parent in children:
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000956 children[parent] = []
Serhiy Storchaka362c1b52013-09-05 17:14:32 +0300957 if c not in children[parent]:
958 children[parent].append(c)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000959 if unique and parent in classes: break
960 elif c not in roots:
961 roots.append(c)
Raymond Hettingere0d49722002-06-02 18:55:56 +0000962 for parent in children:
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000963 if parent not in classes:
964 roots.append(parent)
965 return walktree(roots, children, None)
966
967# ------------------------------------------------ argument list extraction
Christian Heimes25bb7832008-01-11 16:17:00 +0000968Arguments = namedtuple('Arguments', 'args, varargs, varkw')
969
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000970def getargs(co):
971 """Get information about the arguments accepted by a code object.
972
Guido van Rossum2e65f892007-02-28 22:03:49 +0000973 Three things are returned: (args, varargs, varkw), where
Georg Brandlc1c4bf82010-10-15 16:07:41 +0000974 'args' is the list of argument names. Keyword-only arguments are
975 appended. 'varargs' and 'varkw' are the names of the * and **
976 arguments or None."""
Guido van Rossum2e65f892007-02-28 22:03:49 +0000977 args, varargs, kwonlyargs, varkw = _getfullargs(co)
Christian Heimes25bb7832008-01-11 16:17:00 +0000978 return Arguments(args + kwonlyargs, varargs, varkw)
Guido van Rossum2e65f892007-02-28 22:03:49 +0000979
980def _getfullargs(co):
981 """Get information about the arguments accepted by a code object.
982
983 Four things are returned: (args, varargs, kwonlyargs, varkw), where
Georg Brandlc1c4bf82010-10-15 16:07:41 +0000984 'args' and 'kwonlyargs' are lists of argument names, and 'varargs'
985 and 'varkw' are the names of the * and ** arguments or None."""
Jeremy Hylton64967882003-06-27 18:14:39 +0000986
987 if not iscode(co):
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +0000988 raise TypeError('{!r} is not a code object'.format(co))
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000989
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000990 nargs = co.co_argcount
991 names = co.co_varnames
Guido van Rossum2e65f892007-02-28 22:03:49 +0000992 nkwargs = co.co_kwonlyargcount
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000993 args = list(names[:nargs])
Guido van Rossum2e65f892007-02-28 22:03:49 +0000994 kwonlyargs = list(names[nargs:nargs+nkwargs])
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000995 step = 0
996
Guido van Rossum2e65f892007-02-28 22:03:49 +0000997 nargs += nkwargs
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000998 varargs = None
999 if co.co_flags & CO_VARARGS:
1000 varargs = co.co_varnames[nargs]
1001 nargs = nargs + 1
1002 varkw = None
1003 if co.co_flags & CO_VARKEYWORDS:
1004 varkw = co.co_varnames[nargs]
Guido van Rossum2e65f892007-02-28 22:03:49 +00001005 return args, varargs, kwonlyargs, varkw
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001006
Yury Selivanov37dc2b22016-01-11 15:15:01 -05001007
1008ArgSpec = namedtuple('ArgSpec', 'args varargs keywords defaults')
1009
1010def getargspec(func):
1011 """Get the names and default values of a function's arguments.
1012
1013 A tuple of four things is returned: (args, varargs, keywords, defaults).
1014 'args' is a list of the argument names, including keyword-only argument names.
1015 'varargs' and 'keywords' are the names of the * and ** arguments or None.
1016 'defaults' is an n-tuple of the default values of the last n arguments.
1017
1018 Use the getfullargspec() API for Python 3 code, as annotations
1019 and keyword arguments are supported. getargspec() will raise ValueError
1020 if the func has either annotations or keyword arguments.
1021 """
1022 warnings.warn("inspect.getargspec() is deprecated, "
1023 "use inspect.signature() instead", DeprecationWarning,
1024 stacklevel=2)
1025 args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults, ann = \
1026 getfullargspec(func)
1027 if kwonlyargs or ann:
1028 raise ValueError("Function has keyword-only arguments or annotations"
1029 ", use getfullargspec() API which can support them")
1030 return ArgSpec(args, varargs, varkw, defaults)
1031
Christian Heimes25bb7832008-01-11 16:17:00 +00001032FullArgSpec = namedtuple('FullArgSpec',
Benjamin Peterson3d4ca742008-11-12 21:39:01 +00001033 'args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults, annotations')
Guido van Rossum2e65f892007-02-28 22:03:49 +00001034
1035def getfullargspec(func):
Yury Selivanovd82eddc2014-01-29 11:24:39 -05001036 """Get the names and default values of a callable object's arguments.
Guido van Rossum2e65f892007-02-28 22:03:49 +00001037
Brett Cannon504d8852007-09-07 02:12:14 +00001038 A tuple of seven things is returned:
1039 (args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults annotations).
Georg Brandlc1c4bf82010-10-15 16:07:41 +00001040 'args' is a list of the argument names.
Guido van Rossum2e65f892007-02-28 22:03:49 +00001041 'varargs' and 'varkw' are the names of the * and ** arguments or None.
1042 'defaults' is an n-tuple of the default values of the last n arguments.
1043 'kwonlyargs' is a list of keyword-only argument names.
1044 'kwonlydefaults' is a dictionary mapping names from kwonlyargs to defaults.
1045 'annotations' is a dictionary mapping argument names to annotations.
Guido van Rossuma8add0e2007-05-14 22:03:55 +00001046
Yury Selivanov3cfec2e2015-05-22 11:38:38 -04001047 This function is deprecated, use inspect.signature() instead.
Jeremy Hylton64967882003-06-27 18:14:39 +00001048 """
1049
Yury Selivanov57d240e2014-02-19 16:27:23 -05001050 try:
1051 # Re: `skip_bound_arg=False`
1052 #
Yury Selivanovd82eddc2014-01-29 11:24:39 -05001053 # There is a notable difference in behaviour between getfullargspec
1054 # and Signature: the former always returns 'self' parameter for bound
1055 # methods, whereas the Signature always shows the actual calling
1056 # signature of the passed object.
1057 #
1058 # To simulate this behaviour, we "unbind" bound methods, to trick
1059 # inspect.signature to always return their first parameter ("self",
1060 # usually)
Yury Selivanovd82eddc2014-01-29 11:24:39 -05001061
Yury Selivanov57d240e2014-02-19 16:27:23 -05001062 # Re: `follow_wrapper_chains=False`
1063 #
1064 # getfullargspec() historically ignored __wrapped__ attributes,
1065 # so we ensure that remains the case in 3.3+
Yury Selivanovd82eddc2014-01-29 11:24:39 -05001066
Yury Selivanov5a23bd02014-03-29 13:47:11 -04001067 sig = _signature_from_callable(func,
1068 follow_wrapper_chains=False,
1069 skip_bound_arg=False,
1070 sigcls=Signature)
Yury Selivanovd82eddc2014-01-29 11:24:39 -05001071 except Exception as ex:
1072 # Most of the times 'signature' will raise ValueError.
1073 # But, it can also raise AttributeError, and, maybe something
1074 # else. So to be fully backwards compatible, we catch all
1075 # possible exceptions here, and reraise a TypeError.
1076 raise TypeError('unsupported callable') from ex
1077
1078 args = []
1079 varargs = None
1080 varkw = None
1081 kwonlyargs = []
1082 defaults = ()
1083 annotations = {}
1084 defaults = ()
1085 kwdefaults = {}
1086
1087 if sig.return_annotation is not sig.empty:
1088 annotations['return'] = sig.return_annotation
1089
1090 for param in sig.parameters.values():
1091 kind = param.kind
1092 name = param.name
1093
1094 if kind is _POSITIONAL_ONLY:
1095 args.append(name)
1096 elif kind is _POSITIONAL_OR_KEYWORD:
1097 args.append(name)
1098 if param.default is not param.empty:
1099 defaults += (param.default,)
1100 elif kind is _VAR_POSITIONAL:
1101 varargs = name
1102 elif kind is _KEYWORD_ONLY:
1103 kwonlyargs.append(name)
1104 if param.default is not param.empty:
1105 kwdefaults[name] = param.default
1106 elif kind is _VAR_KEYWORD:
1107 varkw = name
1108
1109 if param.annotation is not param.empty:
1110 annotations[name] = param.annotation
1111
1112 if not kwdefaults:
1113 # compatibility with 'func.__kwdefaults__'
1114 kwdefaults = None
1115
1116 if not defaults:
1117 # compatibility with 'func.__defaults__'
1118 defaults = None
1119
Yury Selivanovd82eddc2014-01-29 11:24:39 -05001120 return FullArgSpec(args, varargs, varkw, defaults,
1121 kwonlyargs, kwdefaults, annotations)
1122
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001123
Christian Heimes25bb7832008-01-11 16:17:00 +00001124ArgInfo = namedtuple('ArgInfo', 'args varargs keywords locals')
1125
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001126def getargvalues(frame):
1127 """Get information about arguments passed into a particular frame.
1128
1129 A tuple of four things is returned: (args, varargs, varkw, locals).
Georg Brandlc1c4bf82010-10-15 16:07:41 +00001130 'args' is a list of the argument names.
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001131 'varargs' and 'varkw' are the names of the * and ** arguments or None.
1132 'locals' is the locals dictionary of the given frame."""
1133 args, varargs, varkw = getargs(frame.f_code)
Benjamin Peterson1a6e0d02008-10-25 15:49:17 +00001134 return ArgInfo(args, varargs, varkw, frame.f_locals)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001135
Guido van Rossum2e65f892007-02-28 22:03:49 +00001136def formatannotation(annotation, base_module=None):
1137 if isinstance(annotation, type):
Georg Brandl1a3284e2007-12-02 09:40:06 +00001138 if annotation.__module__ in ('builtins', base_module):
Serhiy Storchaka521e5862014-07-22 15:00:37 +03001139 return annotation.__qualname__
1140 return annotation.__module__+'.'+annotation.__qualname__
Guido van Rossum2e65f892007-02-28 22:03:49 +00001141 return repr(annotation)
Guido van Rossuma8add0e2007-05-14 22:03:55 +00001142
Guido van Rossum2e65f892007-02-28 22:03:49 +00001143def formatannotationrelativeto(object):
Guido van Rossuma8add0e2007-05-14 22:03:55 +00001144 module = getattr(object, '__module__', None)
1145 def _formatannotation(annotation):
1146 return formatannotation(annotation, module)
1147 return _formatannotation
Guido van Rossum2e65f892007-02-28 22:03:49 +00001148
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001149def formatargspec(args, varargs=None, varkw=None, defaults=None,
Guido van Rossum2e65f892007-02-28 22:03:49 +00001150 kwonlyargs=(), kwonlydefaults={}, annotations={},
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001151 formatarg=str,
1152 formatvarargs=lambda name: '*' + name,
1153 formatvarkw=lambda name: '**' + name,
1154 formatvalue=lambda value: '=' + repr(value),
Guido van Rossum2e65f892007-02-28 22:03:49 +00001155 formatreturns=lambda text: ' -> ' + text,
Georg Brandlc1c4bf82010-10-15 16:07:41 +00001156 formatannotation=formatannotation):
Berker Peksagfa3922c2015-07-31 04:11:29 +03001157 """Format an argument spec from the values returned by getfullargspec.
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001158
Guido van Rossum2e65f892007-02-28 22:03:49 +00001159 The first seven arguments are (args, varargs, varkw, defaults,
1160 kwonlyargs, kwonlydefaults, annotations). The other five arguments
1161 are the corresponding optional formatting functions that are called to
1162 turn names and values into strings. The last argument is an optional
1163 function to format the sequence of arguments."""
1164 def formatargandannotation(arg):
1165 result = formatarg(arg)
1166 if arg in annotations:
1167 result += ': ' + formatannotation(annotations[arg])
1168 return result
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001169 specs = []
1170 if defaults:
1171 firstdefault = len(args) - len(defaults)
Benjamin Petersonb58dda72009-01-18 22:27:04 +00001172 for i, arg in enumerate(args):
Georg Brandlc1c4bf82010-10-15 16:07:41 +00001173 spec = formatargandannotation(arg)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001174 if defaults and i >= firstdefault:
1175 spec = spec + formatvalue(defaults[i - firstdefault])
1176 specs.append(spec)
Raymond Hettinger936654b2002-06-01 03:06:31 +00001177 if varargs is not None:
Guido van Rossum2e65f892007-02-28 22:03:49 +00001178 specs.append(formatvarargs(formatargandannotation(varargs)))
1179 else:
1180 if kwonlyargs:
1181 specs.append('*')
1182 if kwonlyargs:
1183 for kwonlyarg in kwonlyargs:
1184 spec = formatargandannotation(kwonlyarg)
Benjamin Peterson9953a8d2009-01-17 04:15:01 +00001185 if kwonlydefaults and kwonlyarg in kwonlydefaults:
Guido van Rossum2e65f892007-02-28 22:03:49 +00001186 spec += formatvalue(kwonlydefaults[kwonlyarg])
1187 specs.append(spec)
Raymond Hettinger936654b2002-06-01 03:06:31 +00001188 if varkw is not None:
Guido van Rossum2e65f892007-02-28 22:03:49 +00001189 specs.append(formatvarkw(formatargandannotation(varkw)))
Neal Norwitz9d72bb42007-04-17 08:48:32 +00001190 result = '(' + ', '.join(specs) + ')'
Guido van Rossum2e65f892007-02-28 22:03:49 +00001191 if 'return' in annotations:
1192 result += formatreturns(formatannotation(annotations['return']))
1193 return result
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001194
1195def formatargvalues(args, varargs, varkw, locals,
1196 formatarg=str,
1197 formatvarargs=lambda name: '*' + name,
1198 formatvarkw=lambda name: '**' + name,
Georg Brandlc1c4bf82010-10-15 16:07:41 +00001199 formatvalue=lambda value: '=' + repr(value)):
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001200 """Format an argument spec from the 4 values returned by getargvalues.
1201
1202 The first four arguments are (args, varargs, varkw, locals). The
1203 next four arguments are the corresponding optional formatting functions
1204 that are called to turn names and values into strings. The ninth
1205 argument is an optional function to format the sequence of arguments."""
1206 def convert(name, locals=locals,
1207 formatarg=formatarg, formatvalue=formatvalue):
1208 return formatarg(name) + formatvalue(locals[name])
1209 specs = []
1210 for i in range(len(args)):
Georg Brandlc1c4bf82010-10-15 16:07:41 +00001211 specs.append(convert(args[i]))
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001212 if varargs:
1213 specs.append(formatvarargs(varargs) + formatvalue(locals[varargs]))
1214 if varkw:
1215 specs.append(formatvarkw(varkw) + formatvalue(locals[varkw]))
Neal Norwitz9d72bb42007-04-17 08:48:32 +00001216 return '(' + ', '.join(specs) + ')'
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001217
Benjamin Petersone109c702011-06-24 09:37:26 -05001218def _missing_arguments(f_name, argnames, pos, values):
1219 names = [repr(name) for name in argnames if name not in values]
1220 missing = len(names)
1221 if missing == 1:
1222 s = names[0]
1223 elif missing == 2:
1224 s = "{} and {}".format(*names)
1225 else:
Yury Selivanovdccfa132014-03-27 18:42:52 -04001226 tail = ", {} and {}".format(*names[-2:])
Benjamin Petersone109c702011-06-24 09:37:26 -05001227 del names[-2:]
1228 s = ", ".join(names) + tail
1229 raise TypeError("%s() missing %i required %s argument%s: %s" %
1230 (f_name, missing,
1231 "positional" if pos else "keyword-only",
1232 "" if missing == 1 else "s", s))
1233
1234def _too_many(f_name, args, kwonly, varargs, defcount, given, values):
Benjamin Petersonb204a422011-06-05 22:04:07 -05001235 atleast = len(args) - defcount
Benjamin Petersonb204a422011-06-05 22:04:07 -05001236 kwonly_given = len([arg for arg in kwonly if arg in values])
1237 if varargs:
1238 plural = atleast != 1
1239 sig = "at least %d" % (atleast,)
1240 elif defcount:
1241 plural = True
1242 sig = "from %d to %d" % (atleast, len(args))
1243 else:
1244 plural = len(args) != 1
1245 sig = str(len(args))
1246 kwonly_sig = ""
1247 if kwonly_given:
1248 msg = " positional argument%s (and %d keyword-only argument%s)"
1249 kwonly_sig = (msg % ("s" if given != 1 else "", kwonly_given,
1250 "s" if kwonly_given != 1 else ""))
1251 raise TypeError("%s() takes %s positional argument%s but %d%s %s given" %
1252 (f_name, sig, "s" if plural else "", given, kwonly_sig,
1253 "was" if given == 1 and not kwonly_given else "were"))
1254
Benjamin Peterson3e6ab172014-01-02 12:24:08 -06001255def getcallargs(*func_and_positional, **named):
Benjamin Peterson25cd7eb2010-03-30 18:42:32 +00001256 """Get the mapping of arguments to values.
1257
1258 A dict is returned, with keys the function argument names (including the
1259 names of the * and ** arguments, if any), and values the respective bound
1260 values from 'positional' and 'named'."""
Benjamin Peterson3e6ab172014-01-02 12:24:08 -06001261 func = func_and_positional[0]
1262 positional = func_and_positional[1:]
Benjamin Peterson25cd7eb2010-03-30 18:42:32 +00001263 spec = getfullargspec(func)
1264 args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults, ann = spec
1265 f_name = func.__name__
1266 arg2value = {}
1267
Benjamin Petersonb204a422011-06-05 22:04:07 -05001268
Benjamin Peterson25cd7eb2010-03-30 18:42:32 +00001269 if ismethod(func) and func.__self__ is not None:
1270 # implicit 'self' (or 'cls' for classmethods) argument
1271 positional = (func.__self__,) + positional
1272 num_pos = len(positional)
Benjamin Peterson25cd7eb2010-03-30 18:42:32 +00001273 num_args = len(args)
1274 num_defaults = len(defaults) if defaults else 0
Benjamin Peterson25cd7eb2010-03-30 18:42:32 +00001275
Benjamin Petersonb204a422011-06-05 22:04:07 -05001276 n = min(num_pos, num_args)
1277 for i in range(n):
1278 arg2value[args[i]] = positional[i]
1279 if varargs:
1280 arg2value[varargs] = tuple(positional[n:])
1281 possible_kwargs = set(args + kwonlyargs)
Benjamin Peterson25cd7eb2010-03-30 18:42:32 +00001282 if varkw:
Benjamin Petersonb204a422011-06-05 22:04:07 -05001283 arg2value[varkw] = {}
1284 for kw, value in named.items():
1285 if kw not in possible_kwargs:
1286 if not varkw:
1287 raise TypeError("%s() got an unexpected keyword argument %r" %
1288 (f_name, kw))
1289 arg2value[varkw][kw] = value
1290 continue
1291 if kw in arg2value:
1292 raise TypeError("%s() got multiple values for argument %r" %
1293 (f_name, kw))
1294 arg2value[kw] = value
1295 if num_pos > num_args and not varargs:
Benjamin Petersone109c702011-06-24 09:37:26 -05001296 _too_many(f_name, args, kwonlyargs, varargs, num_defaults,
1297 num_pos, arg2value)
Benjamin Petersonb204a422011-06-05 22:04:07 -05001298 if num_pos < num_args:
Benjamin Petersone109c702011-06-24 09:37:26 -05001299 req = args[:num_args - num_defaults]
1300 for arg in req:
Benjamin Petersonb204a422011-06-05 22:04:07 -05001301 if arg not in arg2value:
Benjamin Petersone109c702011-06-24 09:37:26 -05001302 _missing_arguments(f_name, req, True, arg2value)
Benjamin Petersonb204a422011-06-05 22:04:07 -05001303 for i, arg in enumerate(args[num_args - num_defaults:]):
1304 if arg not in arg2value:
1305 arg2value[arg] = defaults[i]
Benjamin Petersone109c702011-06-24 09:37:26 -05001306 missing = 0
Benjamin Petersonb204a422011-06-05 22:04:07 -05001307 for kwarg in kwonlyargs:
1308 if kwarg not in arg2value:
Yury Selivanov875df202014-03-27 18:23:03 -04001309 if kwonlydefaults and kwarg in kwonlydefaults:
Benjamin Petersone109c702011-06-24 09:37:26 -05001310 arg2value[kwarg] = kwonlydefaults[kwarg]
1311 else:
1312 missing += 1
1313 if missing:
1314 _missing_arguments(f_name, kwonlyargs, False, arg2value)
Benjamin Peterson25cd7eb2010-03-30 18:42:32 +00001315 return arg2value
1316
Nick Coghlan2f92e542012-06-23 19:39:55 +10001317ClosureVars = namedtuple('ClosureVars', 'nonlocals globals builtins unbound')
1318
1319def getclosurevars(func):
1320 """
1321 Get the mapping of free variables to their current values.
1322
Meador Inge8fda3592012-07-19 21:33:21 -05001323 Returns a named tuple of dicts mapping the current nonlocal, global
Nick Coghlan2f92e542012-06-23 19:39:55 +10001324 and builtin references as seen by the body of the function. A final
1325 set of unbound names that could not be resolved is also provided.
1326 """
1327
1328 if ismethod(func):
1329 func = func.__func__
1330
1331 if not isfunction(func):
1332 raise TypeError("'{!r}' is not a Python function".format(func))
1333
1334 code = func.__code__
1335 # Nonlocal references are named in co_freevars and resolved
1336 # by looking them up in __closure__ by positional index
1337 if func.__closure__ is None:
1338 nonlocal_vars = {}
1339 else:
1340 nonlocal_vars = {
1341 var : cell.cell_contents
1342 for var, cell in zip(code.co_freevars, func.__closure__)
1343 }
1344
1345 # Global and builtin references are named in co_names and resolved
1346 # by looking them up in __globals__ or __builtins__
1347 global_ns = func.__globals__
1348 builtin_ns = global_ns.get("__builtins__", builtins.__dict__)
1349 if ismodule(builtin_ns):
1350 builtin_ns = builtin_ns.__dict__
1351 global_vars = {}
1352 builtin_vars = {}
1353 unbound_names = set()
1354 for name in code.co_names:
1355 if name in ("None", "True", "False"):
1356 # Because these used to be builtins instead of keywords, they
1357 # may still show up as name references. We ignore them.
1358 continue
1359 try:
1360 global_vars[name] = global_ns[name]
1361 except KeyError:
1362 try:
1363 builtin_vars[name] = builtin_ns[name]
1364 except KeyError:
1365 unbound_names.add(name)
1366
1367 return ClosureVars(nonlocal_vars, global_vars,
1368 builtin_vars, unbound_names)
1369
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001370# -------------------------------------------------- stack frame extraction
Christian Heimes25bb7832008-01-11 16:17:00 +00001371
1372Traceback = namedtuple('Traceback', 'filename lineno function code_context index')
1373
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001374def getframeinfo(frame, context=1):
1375 """Get information about a frame or traceback object.
1376
1377 A tuple of five things is returned: the filename, the line number of
1378 the current line, the function name, a list of lines of context from
1379 the source code, and the index of the current line within that list.
1380 The optional second argument specifies the number of lines of context
1381 to return, which are centered around the current line."""
1382 if istraceback(frame):
Andrew M. Kuchlingba8b6bc2004-06-05 14:11:59 +00001383 lineno = frame.tb_lineno
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001384 frame = frame.tb_frame
Andrew M. Kuchlingba8b6bc2004-06-05 14:11:59 +00001385 else:
1386 lineno = frame.f_lineno
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001387 if not isframe(frame):
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00001388 raise TypeError('{!r} is not a frame or traceback object'.format(frame))
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001389
Neil Schemenauerf06f8532002-03-23 23:51:04 +00001390 filename = getsourcefile(frame) or getfile(frame)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001391 if context > 0:
Guido van Rossum54e54c62001-09-04 19:14:14 +00001392 start = lineno - 1 - context//2
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001393 try:
1394 lines, lnum = findsource(frame)
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02001395 except OSError:
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +00001396 lines = index = None
1397 else:
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001398 start = max(start, 1)
Raymond Hettingera0501712004-06-15 11:22:53 +00001399 start = max(0, min(start, len(lines) - context))
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001400 lines = lines[start:start+context]
Ka-Ping Yee59ade082001-03-01 03:55:35 +00001401 index = lineno - 1 - start
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001402 else:
1403 lines = index = None
1404
Christian Heimes25bb7832008-01-11 16:17:00 +00001405 return Traceback(filename, lineno, frame.f_code.co_name, lines, index)
Ka-Ping Yee59ade082001-03-01 03:55:35 +00001406
1407def getlineno(frame):
1408 """Get the line number from a frame object, allowing for optimization."""
Michael W. Hudsondd32a912002-08-15 14:59:02 +00001409 # FrameType.f_lineno is now a descriptor that grovels co_lnotab
1410 return frame.f_lineno
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001411
Antoine Pitroucdcafb72014-08-24 10:50:28 -04001412FrameInfo = namedtuple('FrameInfo', ('frame',) + Traceback._fields)
1413
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001414def getouterframes(frame, context=1):
1415 """Get a list of records for a frame and all higher (calling) frames.
1416
1417 Each record contains a frame object, filename, line number, function
1418 name, a list of lines of context, and index within the context."""
1419 framelist = []
1420 while frame:
Antoine Pitroucdcafb72014-08-24 10:50:28 -04001421 frameinfo = (frame,) + getframeinfo(frame, context)
1422 framelist.append(FrameInfo(*frameinfo))
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001423 frame = frame.f_back
1424 return framelist
1425
1426def getinnerframes(tb, context=1):
1427 """Get a list of records for a traceback's frame and all lower frames.
1428
1429 Each record contains a frame object, filename, line number, function
1430 name, a list of lines of context, and index within the context."""
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001431 framelist = []
1432 while tb:
Antoine Pitroucdcafb72014-08-24 10:50:28 -04001433 frameinfo = (tb.tb_frame,) + getframeinfo(tb, context)
1434 framelist.append(FrameInfo(*frameinfo))
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001435 tb = tb.tb_next
1436 return framelist
1437
Benjamin Peterson42ac4752010-08-09 13:05:35 +00001438def currentframe():
Benjamin Petersona3a3fc62010-08-09 15:49:56 +00001439 """Return the frame of the caller or None if this is not possible."""
Benjamin Peterson42ac4752010-08-09 13:05:35 +00001440 return sys._getframe(1) if hasattr(sys, "_getframe") else None
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001441
1442def stack(context=1):
1443 """Return a list of records for the stack above the caller's frame."""
Jeremy Hyltonab919022003-06-27 18:41:20 +00001444 return getouterframes(sys._getframe(1), context)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001445
1446def trace(context=1):
Tim Peters85ba6732001-02-28 08:26:44 +00001447 """Return a list of records for the stack below the current exception."""
Fred Draked451ec12002-04-26 02:29:55 +00001448 return getinnerframes(sys.exc_info()[2], context)
Michael Foord95fc51d2010-11-20 15:07:30 +00001449
1450
1451# ------------------------------------------------ static version of getattr
1452
1453_sentinel = object()
1454
Michael Foorde5162652010-11-20 16:40:44 +00001455def _static_getmro(klass):
1456 return type.__dict__['__mro__'].__get__(klass)
1457
Michael Foord95fc51d2010-11-20 15:07:30 +00001458def _check_instance(obj, attr):
1459 instance_dict = {}
1460 try:
1461 instance_dict = object.__getattribute__(obj, "__dict__")
1462 except AttributeError:
1463 pass
Michael Foorddcebe0f2011-03-15 19:20:44 -04001464 return dict.get(instance_dict, attr, _sentinel)
Michael Foord95fc51d2010-11-20 15:07:30 +00001465
1466
1467def _check_class(klass, attr):
Michael Foorde5162652010-11-20 16:40:44 +00001468 for entry in _static_getmro(klass):
Michael Foorda51623b2011-12-18 22:01:40 +00001469 if _shadowed_dict(type(entry)) is _sentinel:
Michael Foorddcebe0f2011-03-15 19:20:44 -04001470 try:
1471 return entry.__dict__[attr]
1472 except KeyError:
1473 pass
Michael Foord95fc51d2010-11-20 15:07:30 +00001474 return _sentinel
1475
Michael Foord35184ed2010-11-20 16:58:30 +00001476def _is_type(obj):
1477 try:
1478 _static_getmro(obj)
1479 except TypeError:
1480 return False
1481 return True
1482
Michael Foorddcebe0f2011-03-15 19:20:44 -04001483def _shadowed_dict(klass):
1484 dict_attr = type.__dict__["__dict__"]
1485 for entry in _static_getmro(klass):
1486 try:
1487 class_dict = dict_attr.__get__(entry)["__dict__"]
1488 except KeyError:
1489 pass
1490 else:
1491 if not (type(class_dict) is types.GetSetDescriptorType and
1492 class_dict.__name__ == "__dict__" and
1493 class_dict.__objclass__ is entry):
Michael Foorda51623b2011-12-18 22:01:40 +00001494 return class_dict
1495 return _sentinel
Michael Foord95fc51d2010-11-20 15:07:30 +00001496
1497def getattr_static(obj, attr, default=_sentinel):
1498 """Retrieve attributes without triggering dynamic lookup via the
1499 descriptor protocol, __getattr__ or __getattribute__.
1500
1501 Note: this function may not be able to retrieve all attributes
1502 that getattr can fetch (like dynamically created attributes)
1503 and may find attributes that getattr can't (like descriptors
1504 that raise AttributeError). It can also return descriptor objects
1505 instead of instance members in some cases. See the
1506 documentation for details.
1507 """
1508 instance_result = _sentinel
Michael Foord35184ed2010-11-20 16:58:30 +00001509 if not _is_type(obj):
Michael Foordcc7ebb82010-11-20 16:20:16 +00001510 klass = type(obj)
Michael Foorda51623b2011-12-18 22:01:40 +00001511 dict_attr = _shadowed_dict(klass)
1512 if (dict_attr is _sentinel or
1513 type(dict_attr) is types.MemberDescriptorType):
Michael Foorddcebe0f2011-03-15 19:20:44 -04001514 instance_result = _check_instance(obj, attr)
Michael Foord95fc51d2010-11-20 15:07:30 +00001515 else:
1516 klass = obj
1517
1518 klass_result = _check_class(klass, attr)
1519
1520 if instance_result is not _sentinel and klass_result is not _sentinel:
1521 if (_check_class(type(klass_result), '__get__') is not _sentinel and
1522 _check_class(type(klass_result), '__set__') is not _sentinel):
1523 return klass_result
1524
1525 if instance_result is not _sentinel:
1526 return instance_result
1527 if klass_result is not _sentinel:
1528 return klass_result
1529
1530 if obj is klass:
1531 # for types we check the metaclass too
Michael Foorde5162652010-11-20 16:40:44 +00001532 for entry in _static_getmro(type(klass)):
Michael Foord3ba95f82011-12-22 01:13:37 +00001533 if _shadowed_dict(type(entry)) is _sentinel:
1534 try:
1535 return entry.__dict__[attr]
1536 except KeyError:
1537 pass
Michael Foord95fc51d2010-11-20 15:07:30 +00001538 if default is not _sentinel:
1539 return default
1540 raise AttributeError(attr)
Nick Coghlane0f04652010-11-21 03:44:04 +00001541
1542
Nick Coghlan04e2e3f2012-06-23 19:52:05 +10001543# ------------------------------------------------ generator introspection
1544
Nick Coghlan7921b9f2010-11-30 06:36:04 +00001545GEN_CREATED = 'GEN_CREATED'
1546GEN_RUNNING = 'GEN_RUNNING'
1547GEN_SUSPENDED = 'GEN_SUSPENDED'
1548GEN_CLOSED = 'GEN_CLOSED'
Nick Coghlane0f04652010-11-21 03:44:04 +00001549
1550def getgeneratorstate(generator):
1551 """Get current state of a generator-iterator.
1552
1553 Possible states are:
1554 GEN_CREATED: Waiting to start execution.
1555 GEN_RUNNING: Currently being executed by the interpreter.
1556 GEN_SUSPENDED: Currently suspended at a yield expression.
1557 GEN_CLOSED: Execution has completed.
1558 """
1559 if generator.gi_running:
1560 return GEN_RUNNING
1561 if generator.gi_frame is None:
1562 return GEN_CLOSED
1563 if generator.gi_frame.f_lasti == -1:
1564 return GEN_CREATED
1565 return GEN_SUSPENDED
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07001566
1567
Nick Coghlan04e2e3f2012-06-23 19:52:05 +10001568def getgeneratorlocals(generator):
1569 """
1570 Get the mapping of generator local variables to their current values.
1571
1572 A dict is returned, with the keys the local variable names and values the
1573 bound values."""
1574
1575 if not isgenerator(generator):
1576 raise TypeError("'{!r}' is not a Python generator".format(generator))
1577
1578 frame = getattr(generator, "gi_frame", None)
1579 if frame is not None:
1580 return generator.gi_frame.f_locals
1581 else:
1582 return {}
1583
Yury Selivanov5376ba92015-06-22 12:19:30 -04001584
1585# ------------------------------------------------ coroutine introspection
1586
1587CORO_CREATED = 'CORO_CREATED'
1588CORO_RUNNING = 'CORO_RUNNING'
1589CORO_SUSPENDED = 'CORO_SUSPENDED'
1590CORO_CLOSED = 'CORO_CLOSED'
1591
1592def getcoroutinestate(coroutine):
1593 """Get current state of a coroutine object.
1594
1595 Possible states are:
1596 CORO_CREATED: Waiting to start execution.
1597 CORO_RUNNING: Currently being executed by the interpreter.
1598 CORO_SUSPENDED: Currently suspended at an await expression.
1599 CORO_CLOSED: Execution has completed.
1600 """
1601 if coroutine.cr_running:
1602 return CORO_RUNNING
1603 if coroutine.cr_frame is None:
1604 return CORO_CLOSED
1605 if coroutine.cr_frame.f_lasti == -1:
1606 return CORO_CREATED
1607 return CORO_SUSPENDED
1608
1609
1610def getcoroutinelocals(coroutine):
1611 """
1612 Get the mapping of coroutine local variables to their current values.
1613
1614 A dict is returned, with the keys the local variable names and values the
1615 bound values."""
1616 frame = getattr(coroutine, "cr_frame", None)
1617 if frame is not None:
1618 return frame.f_locals
1619 else:
1620 return {}
1621
1622
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07001623###############################################################################
1624### Function Signature Object (PEP 362)
1625###############################################################################
1626
1627
1628_WrapperDescriptor = type(type.__call__)
1629_MethodWrapper = type(all.__call__)
Larry Hastings5c661892014-01-24 06:17:25 -08001630_ClassMethodWrapper = type(int.__dict__['from_bytes'])
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07001631
1632_NonUserDefinedCallables = (_WrapperDescriptor,
1633 _MethodWrapper,
Larry Hastings5c661892014-01-24 06:17:25 -08001634 _ClassMethodWrapper,
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07001635 types.BuiltinFunctionType)
1636
1637
Yury Selivanov421f0c72014-01-29 12:05:40 -05001638def _signature_get_user_defined_method(cls, method_name):
Yury Selivanov5a23bd02014-03-29 13:47:11 -04001639 """Private helper. Checks if ``cls`` has an attribute
1640 named ``method_name`` and returns it only if it is a
1641 pure python function.
1642 """
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07001643 try:
1644 meth = getattr(cls, method_name)
1645 except AttributeError:
1646 return
1647 else:
1648 if not isinstance(meth, _NonUserDefinedCallables):
1649 # Once '__signature__' will be added to 'C'-level
1650 # callables, this check won't be necessary
1651 return meth
1652
1653
Yury Selivanov62560fb2014-01-28 12:26:24 -05001654def _signature_get_partial(wrapped_sig, partial, extra_args=()):
Yury Selivanov5a23bd02014-03-29 13:47:11 -04001655 """Private helper to calculate how 'wrapped_sig' signature will
1656 look like after applying a 'functools.partial' object (or alike)
1657 on it.
1658 """
Yury Selivanov62560fb2014-01-28 12:26:24 -05001659
Yury Selivanov3f73ca22014-04-08 11:30:45 -04001660 old_params = wrapped_sig.parameters
1661 new_params = OrderedDict(old_params.items())
Yury Selivanovda5fe4f2014-01-27 17:28:37 -05001662
1663 partial_args = partial.args or ()
1664 partial_keywords = partial.keywords or {}
1665
1666 if extra_args:
1667 partial_args = extra_args + partial_args
1668
1669 try:
1670 ba = wrapped_sig.bind_partial(*partial_args, **partial_keywords)
1671 except TypeError as ex:
1672 msg = 'partial object {!r} has incorrect arguments'.format(partial)
1673 raise ValueError(msg) from ex
1674
Yury Selivanovda5fe4f2014-01-27 17:28:37 -05001675
Yury Selivanov3f73ca22014-04-08 11:30:45 -04001676 transform_to_kwonly = False
1677 for param_name, param in old_params.items():
1678 try:
1679 arg_value = ba.arguments[param_name]
1680 except KeyError:
1681 pass
1682 else:
1683 if param.kind is _POSITIONAL_ONLY:
1684 # If positional-only parameter is bound by partial,
1685 # it effectively disappears from the signature
1686 new_params.pop(param_name)
1687 continue
1688
1689 if param.kind is _POSITIONAL_OR_KEYWORD:
1690 if param_name in partial_keywords:
1691 # This means that this parameter, and all parameters
1692 # after it should be keyword-only (and var-positional
1693 # should be removed). Here's why. Consider the following
1694 # function:
1695 # foo(a, b, *args, c):
1696 # pass
1697 #
1698 # "partial(foo, a='spam')" will have the following
1699 # signature: "(*, a='spam', b, c)". Because attempting
1700 # to call that partial with "(10, 20)" arguments will
1701 # raise a TypeError, saying that "a" argument received
1702 # multiple values.
1703 transform_to_kwonly = True
1704 # Set the new default value
1705 new_params[param_name] = param.replace(default=arg_value)
1706 else:
1707 # was passed as a positional argument
1708 new_params.pop(param.name)
1709 continue
1710
1711 if param.kind is _KEYWORD_ONLY:
1712 # Set the new default value
1713 new_params[param_name] = param.replace(default=arg_value)
1714
1715 if transform_to_kwonly:
1716 assert param.kind is not _POSITIONAL_ONLY
1717
1718 if param.kind is _POSITIONAL_OR_KEYWORD:
1719 new_param = new_params[param_name].replace(kind=_KEYWORD_ONLY)
1720 new_params[param_name] = new_param
1721 new_params.move_to_end(param_name)
1722 elif param.kind in (_KEYWORD_ONLY, _VAR_KEYWORD):
1723 new_params.move_to_end(param_name)
1724 elif param.kind is _VAR_POSITIONAL:
1725 new_params.pop(param.name)
Yury Selivanovda5fe4f2014-01-27 17:28:37 -05001726
1727 return wrapped_sig.replace(parameters=new_params.values())
1728
1729
Yury Selivanov62560fb2014-01-28 12:26:24 -05001730def _signature_bound_method(sig):
Yury Selivanov5a23bd02014-03-29 13:47:11 -04001731 """Private helper to transform signatures for unbound
1732 functions to bound methods.
1733 """
Yury Selivanov62560fb2014-01-28 12:26:24 -05001734
1735 params = tuple(sig.parameters.values())
1736
1737 if not params or params[0].kind in (_VAR_KEYWORD, _KEYWORD_ONLY):
1738 raise ValueError('invalid method signature')
1739
1740 kind = params[0].kind
1741 if kind in (_POSITIONAL_OR_KEYWORD, _POSITIONAL_ONLY):
1742 # Drop first parameter:
1743 # '(p1, p2[, ...])' -> '(p2[, ...])'
1744 params = params[1:]
1745 else:
1746 if kind is not _VAR_POSITIONAL:
1747 # Unless we add a new parameter type we never
1748 # get here
1749 raise ValueError('invalid argument type')
1750 # It's a var-positional parameter.
1751 # Do nothing. '(*args[, ...])' -> '(*args[, ...])'
1752
1753 return sig.replace(parameters=params)
1754
1755
Yury Selivanovb77511d2014-01-29 10:46:14 -05001756def _signature_is_builtin(obj):
Yury Selivanov5a23bd02014-03-29 13:47:11 -04001757 """Private helper to test if `obj` is a callable that might
1758 support Argument Clinic's __text_signature__ protocol.
1759 """
Yury Selivanov1d241832014-02-02 12:51:20 -05001760 return (isbuiltin(obj) or
Yury Selivanovb77511d2014-01-29 10:46:14 -05001761 ismethoddescriptor(obj) or
Yury Selivanov1d241832014-02-02 12:51:20 -05001762 isinstance(obj, _NonUserDefinedCallables) or
Yury Selivanovb77511d2014-01-29 10:46:14 -05001763 # Can't test 'isinstance(type)' here, as it would
1764 # also be True for regular python classes
1765 obj in (type, object))
1766
1767
Yury Selivanov63da7c72014-01-31 14:48:37 -05001768def _signature_is_functionlike(obj):
Yury Selivanov5a23bd02014-03-29 13:47:11 -04001769 """Private helper to test if `obj` is a duck type of FunctionType.
1770 A good example of such objects are functions compiled with
1771 Cython, which have all attributes that a pure Python function
1772 would have, but have their code statically compiled.
1773 """
Yury Selivanov63da7c72014-01-31 14:48:37 -05001774
1775 if not callable(obj) or isclass(obj):
1776 # All function-like objects are obviously callables,
1777 # and not classes.
1778 return False
1779
1780 name = getattr(obj, '__name__', None)
1781 code = getattr(obj, '__code__', None)
1782 defaults = getattr(obj, '__defaults__', _void) # Important to use _void ...
1783 kwdefaults = getattr(obj, '__kwdefaults__', _void) # ... and not None here
1784 annotations = getattr(obj, '__annotations__', None)
1785
1786 return (isinstance(code, types.CodeType) and
1787 isinstance(name, str) and
1788 (defaults is None or isinstance(defaults, tuple)) and
1789 (kwdefaults is None or isinstance(kwdefaults, dict)) and
1790 isinstance(annotations, dict))
1791
1792
Yury Selivanovd82eddc2014-01-29 11:24:39 -05001793def _signature_get_bound_param(spec):
Yury Selivanov5a23bd02014-03-29 13:47:11 -04001794 """ Private helper to get first parameter name from a
1795 __text_signature__ of a builtin method, which should
1796 be in the following format: '($param1, ...)'.
1797 Assumptions are that the first argument won't have
1798 a default value or an annotation.
1799 """
Yury Selivanovd82eddc2014-01-29 11:24:39 -05001800
1801 assert spec.startswith('($')
1802
1803 pos = spec.find(',')
1804 if pos == -1:
1805 pos = spec.find(')')
1806
1807 cpos = spec.find(':')
1808 assert cpos == -1 or cpos > pos
1809
1810 cpos = spec.find('=')
1811 assert cpos == -1 or cpos > pos
1812
1813 return spec[2:pos]
1814
1815
Larry Hastings2623c8c2014-02-08 22:15:29 -08001816def _signature_strip_non_python_syntax(signature):
1817 """
Yury Selivanov5a23bd02014-03-29 13:47:11 -04001818 Private helper function. Takes a signature in Argument Clinic's
1819 extended signature format.
1820
Larry Hastings2623c8c2014-02-08 22:15:29 -08001821 Returns a tuple of three things:
1822 * that signature re-rendered in standard Python syntax,
1823 * the index of the "self" parameter (generally 0), or None if
1824 the function does not have a "self" parameter, and
1825 * the index of the last "positional only" parameter,
1826 or None if the signature has no positional-only parameters.
1827 """
1828
1829 if not signature:
1830 return signature, None, None
1831
1832 self_parameter = None
1833 last_positional_only = None
1834
1835 lines = [l.encode('ascii') for l in signature.split('\n')]
1836 generator = iter(lines).__next__
1837 token_stream = tokenize.tokenize(generator)
1838
1839 delayed_comma = False
1840 skip_next_comma = False
1841 text = []
1842 add = text.append
1843
1844 current_parameter = 0
1845 OP = token.OP
1846 ERRORTOKEN = token.ERRORTOKEN
1847
1848 # token stream always starts with ENCODING token, skip it
1849 t = next(token_stream)
1850 assert t.type == tokenize.ENCODING
1851
1852 for t in token_stream:
1853 type, string = t.type, t.string
1854
1855 if type == OP:
1856 if string == ',':
1857 if skip_next_comma:
1858 skip_next_comma = False
1859 else:
1860 assert not delayed_comma
1861 delayed_comma = True
1862 current_parameter += 1
1863 continue
1864
1865 if string == '/':
1866 assert not skip_next_comma
1867 assert last_positional_only is None
1868 skip_next_comma = True
1869 last_positional_only = current_parameter - 1
1870 continue
1871
1872 if (type == ERRORTOKEN) and (string == '$'):
1873 assert self_parameter is None
1874 self_parameter = current_parameter
1875 continue
1876
1877 if delayed_comma:
1878 delayed_comma = False
1879 if not ((type == OP) and (string == ')')):
1880 add(', ')
1881 add(string)
1882 if (string == ','):
1883 add(' ')
1884 clean_signature = ''.join(text)
1885 return clean_signature, self_parameter, last_positional_only
1886
1887
Yury Selivanov57d240e2014-02-19 16:27:23 -05001888def _signature_fromstr(cls, obj, s, skip_bound_arg=True):
Yury Selivanov5a23bd02014-03-29 13:47:11 -04001889 """Private helper to parse content of '__text_signature__'
1890 and return a Signature based on it.
1891 """
1892
Yury Selivanov7d2bfed2014-02-03 02:46:07 -05001893 Parameter = cls._parameter_cls
1894
Larry Hastings2623c8c2014-02-08 22:15:29 -08001895 clean_signature, self_parameter, last_positional_only = \
1896 _signature_strip_non_python_syntax(s)
Yury Selivanov7d2bfed2014-02-03 02:46:07 -05001897
Larry Hastings2623c8c2014-02-08 22:15:29 -08001898 program = "def foo" + clean_signature + ": pass"
Yury Selivanov7d2bfed2014-02-03 02:46:07 -05001899
1900 try:
Larry Hastings2623c8c2014-02-08 22:15:29 -08001901 module = ast.parse(program)
Yury Selivanov7d2bfed2014-02-03 02:46:07 -05001902 except SyntaxError:
1903 module = None
1904
1905 if not isinstance(module, ast.Module):
1906 raise ValueError("{!r} builtin has invalid signature".format(obj))
1907
1908 f = module.body[0]
1909
1910 parameters = []
1911 empty = Parameter.empty
1912 invalid = object()
1913
1914 module = None
1915 module_dict = {}
1916 module_name = getattr(obj, '__module__', None)
1917 if module_name:
1918 module = sys.modules.get(module_name, None)
1919 if module:
1920 module_dict = module.__dict__
1921 sys_module_dict = sys.modules
1922
1923 def parse_name(node):
1924 assert isinstance(node, ast.arg)
1925 if node.annotation != None:
1926 raise ValueError("Annotations are not currently supported")
1927 return node.arg
1928
1929 def wrap_value(s):
1930 try:
1931 value = eval(s, module_dict)
1932 except NameError:
1933 try:
1934 value = eval(s, sys_module_dict)
1935 except NameError:
1936 raise RuntimeError()
1937
1938 if isinstance(value, str):
1939 return ast.Str(value)
1940 if isinstance(value, (int, float)):
1941 return ast.Num(value)
1942 if isinstance(value, bytes):
1943 return ast.Bytes(value)
1944 if value in (True, False, None):
1945 return ast.NameConstant(value)
1946 raise RuntimeError()
1947
1948 class RewriteSymbolics(ast.NodeTransformer):
1949 def visit_Attribute(self, node):
1950 a = []
1951 n = node
1952 while isinstance(n, ast.Attribute):
1953 a.append(n.attr)
1954 n = n.value
1955 if not isinstance(n, ast.Name):
1956 raise RuntimeError()
1957 a.append(n.id)
1958 value = ".".join(reversed(a))
1959 return wrap_value(value)
1960
1961 def visit_Name(self, node):
1962 if not isinstance(node.ctx, ast.Load):
1963 raise ValueError()
1964 return wrap_value(node.id)
1965
1966 def p(name_node, default_node, default=empty):
1967 name = parse_name(name_node)
1968 if name is invalid:
1969 return None
1970 if default_node and default_node is not _empty:
1971 try:
1972 default_node = RewriteSymbolics().visit(default_node)
1973 o = ast.literal_eval(default_node)
1974 except ValueError:
1975 o = invalid
1976 if o is invalid:
1977 return None
1978 default = o if o is not invalid else default
1979 parameters.append(Parameter(name, kind, default=default, annotation=empty))
1980
1981 # non-keyword-only parameters
1982 args = reversed(f.args.args)
1983 defaults = reversed(f.args.defaults)
1984 iter = itertools.zip_longest(args, defaults, fillvalue=None)
Larry Hastings2623c8c2014-02-08 22:15:29 -08001985 if last_positional_only is not None:
1986 kind = Parameter.POSITIONAL_ONLY
1987 else:
1988 kind = Parameter.POSITIONAL_OR_KEYWORD
1989 for i, (name, default) in enumerate(reversed(list(iter))):
Yury Selivanov7d2bfed2014-02-03 02:46:07 -05001990 p(name, default)
Larry Hastings2623c8c2014-02-08 22:15:29 -08001991 if i == last_positional_only:
1992 kind = Parameter.POSITIONAL_OR_KEYWORD
Yury Selivanov7d2bfed2014-02-03 02:46:07 -05001993
1994 # *args
1995 if f.args.vararg:
1996 kind = Parameter.VAR_POSITIONAL
1997 p(f.args.vararg, empty)
1998
1999 # keyword-only arguments
2000 kind = Parameter.KEYWORD_ONLY
2001 for name, default in zip(f.args.kwonlyargs, f.args.kw_defaults):
2002 p(name, default)
2003
2004 # **kwargs
2005 if f.args.kwarg:
2006 kind = Parameter.VAR_KEYWORD
2007 p(f.args.kwarg, empty)
2008
Larry Hastings2623c8c2014-02-08 22:15:29 -08002009 if self_parameter is not None:
Yury Selivanov8c185ee2014-02-21 01:32:42 -05002010 # Possibly strip the bound argument:
2011 # - We *always* strip first bound argument if
2012 # it is a module.
2013 # - We don't strip first bound argument if
2014 # skip_bound_arg is False.
Yury Selivanov7d2bfed2014-02-03 02:46:07 -05002015 assert parameters
Yury Selivanov8c185ee2014-02-21 01:32:42 -05002016 _self = getattr(obj, '__self__', None)
2017 self_isbound = _self is not None
2018 self_ismodule = ismodule(_self)
2019 if self_isbound and (self_ismodule or skip_bound_arg):
Yury Selivanov7d2bfed2014-02-03 02:46:07 -05002020 parameters.pop(0)
2021 else:
2022 # for builtins, self parameter is always positional-only!
2023 p = parameters[0].replace(kind=Parameter.POSITIONAL_ONLY)
2024 parameters[0] = p
2025
2026 return cls(parameters, return_annotation=cls.empty)
2027
2028
Yury Selivanov57d240e2014-02-19 16:27:23 -05002029def _signature_from_builtin(cls, func, skip_bound_arg=True):
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002030 """Private helper function to get signature for
2031 builtin callables.
2032 """
2033
Yury Selivanov57d240e2014-02-19 16:27:23 -05002034 if not _signature_is_builtin(func):
2035 raise TypeError("{!r} is not a Python builtin "
2036 "function".format(func))
2037
2038 s = getattr(func, "__text_signature__", None)
2039 if not s:
2040 raise ValueError("no signature found for builtin {!r}".format(func))
2041
2042 return _signature_fromstr(cls, func, s, skip_bound_arg)
2043
2044
Yury Selivanovcf45f022015-05-20 14:38:50 -04002045def _signature_from_function(cls, func):
2046 """Private helper: constructs Signature for the given python function."""
2047
2048 is_duck_function = False
2049 if not isfunction(func):
2050 if _signature_is_functionlike(func):
2051 is_duck_function = True
2052 else:
2053 # If it's not a pure Python function, and not a duck type
2054 # of pure function:
2055 raise TypeError('{!r} is not a Python function'.format(func))
2056
2057 Parameter = cls._parameter_cls
2058
2059 # Parameter information.
2060 func_code = func.__code__
2061 pos_count = func_code.co_argcount
2062 arg_names = func_code.co_varnames
2063 positional = tuple(arg_names[:pos_count])
2064 keyword_only_count = func_code.co_kwonlyargcount
2065 keyword_only = arg_names[pos_count:(pos_count + keyword_only_count)]
2066 annotations = func.__annotations__
2067 defaults = func.__defaults__
2068 kwdefaults = func.__kwdefaults__
2069
2070 if defaults:
2071 pos_default_count = len(defaults)
2072 else:
2073 pos_default_count = 0
2074
2075 parameters = []
2076
2077 # Non-keyword-only parameters w/o defaults.
2078 non_default_count = pos_count - pos_default_count
2079 for name in positional[:non_default_count]:
2080 annotation = annotations.get(name, _empty)
2081 parameters.append(Parameter(name, annotation=annotation,
2082 kind=_POSITIONAL_OR_KEYWORD))
2083
2084 # ... w/ defaults.
2085 for offset, name in enumerate(positional[non_default_count:]):
2086 annotation = annotations.get(name, _empty)
2087 parameters.append(Parameter(name, annotation=annotation,
2088 kind=_POSITIONAL_OR_KEYWORD,
2089 default=defaults[offset]))
2090
2091 # *args
2092 if func_code.co_flags & CO_VARARGS:
2093 name = arg_names[pos_count + keyword_only_count]
2094 annotation = annotations.get(name, _empty)
2095 parameters.append(Parameter(name, annotation=annotation,
2096 kind=_VAR_POSITIONAL))
2097
2098 # Keyword-only parameters.
2099 for name in keyword_only:
2100 default = _empty
2101 if kwdefaults is not None:
2102 default = kwdefaults.get(name, _empty)
2103
2104 annotation = annotations.get(name, _empty)
2105 parameters.append(Parameter(name, annotation=annotation,
2106 kind=_KEYWORD_ONLY,
2107 default=default))
2108 # **kwargs
2109 if func_code.co_flags & CO_VARKEYWORDS:
2110 index = pos_count + keyword_only_count
2111 if func_code.co_flags & CO_VARARGS:
2112 index += 1
2113
2114 name = arg_names[index]
2115 annotation = annotations.get(name, _empty)
2116 parameters.append(Parameter(name, annotation=annotation,
2117 kind=_VAR_KEYWORD))
2118
2119 # Is 'func' is a pure Python function - don't validate the
2120 # parameters list (for correct order and defaults), it should be OK.
2121 return cls(parameters,
2122 return_annotation=annotations.get('return', _empty),
2123 __validate_parameters__=is_duck_function)
2124
2125
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002126def _signature_from_callable(obj, *,
2127 follow_wrapper_chains=True,
2128 skip_bound_arg=True,
2129 sigcls):
2130
2131 """Private helper function to get signature for arbitrary
2132 callable objects.
2133 """
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002134
2135 if not callable(obj):
2136 raise TypeError('{!r} is not a callable object'.format(obj))
2137
2138 if isinstance(obj, types.MethodType):
2139 # In this case we skip the first parameter of the underlying
2140 # function (usually `self` or `cls`).
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002141 sig = _signature_from_callable(
Yury Selivanovda396452014-03-27 12:09:24 -04002142 obj.__func__,
2143 follow_wrapper_chains=follow_wrapper_chains,
2144 skip_bound_arg=skip_bound_arg,
2145 sigcls=sigcls)
2146
Yury Selivanov57d240e2014-02-19 16:27:23 -05002147 if skip_bound_arg:
2148 return _signature_bound_method(sig)
2149 else:
2150 return sig
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002151
Nick Coghlane8c45d62013-07-28 20:00:01 +10002152 # Was this function wrapped by a decorator?
Yury Selivanov57d240e2014-02-19 16:27:23 -05002153 if follow_wrapper_chains:
2154 obj = unwrap(obj, stop=(lambda f: hasattr(f, "__signature__")))
Yury Selivanov46c759d2015-05-27 21:56:53 -04002155 if isinstance(obj, types.MethodType):
2156 # If the unwrapped object is a *method*, we might want to
2157 # skip its first parameter (self).
2158 # See test_signature_wrapped_bound_method for details.
Yury Selivanov507cd3c2015-05-27 21:59:03 -04002159 return _signature_from_callable(
Yury Selivanov46c759d2015-05-27 21:56:53 -04002160 obj,
2161 follow_wrapper_chains=follow_wrapper_chains,
Yury Selivanov507cd3c2015-05-27 21:59:03 -04002162 skip_bound_arg=skip_bound_arg,
2163 sigcls=sigcls)
Nick Coghlane8c45d62013-07-28 20:00:01 +10002164
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002165 try:
2166 sig = obj.__signature__
2167 except AttributeError:
2168 pass
2169 else:
2170 if sig is not None:
Yury Selivanov42407ab2014-06-23 10:23:50 -07002171 if not isinstance(sig, Signature):
2172 raise TypeError(
2173 'unexpected object {!r} in __signature__ '
2174 'attribute'.format(sig))
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002175 return sig
2176
Yury Selivanovda5fe4f2014-01-27 17:28:37 -05002177 try:
2178 partialmethod = obj._partialmethod
2179 except AttributeError:
2180 pass
2181 else:
Yury Selivanov0486f812014-01-29 12:18:59 -05002182 if isinstance(partialmethod, functools.partialmethod):
2183 # Unbound partialmethod (see functools.partialmethod)
2184 # This means, that we need to calculate the signature
2185 # as if it's a regular partial object, but taking into
2186 # account that the first positional argument
2187 # (usually `self`, or `cls`) will not be passed
2188 # automatically (as for boundmethods)
Yury Selivanovda5fe4f2014-01-27 17:28:37 -05002189
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002190 wrapped_sig = _signature_from_callable(
Yury Selivanovda396452014-03-27 12:09:24 -04002191 partialmethod.func,
2192 follow_wrapper_chains=follow_wrapper_chains,
2193 skip_bound_arg=skip_bound_arg,
2194 sigcls=sigcls)
2195
Yury Selivanov0486f812014-01-29 12:18:59 -05002196 sig = _signature_get_partial(wrapped_sig, partialmethod, (None,))
Yury Selivanovda5fe4f2014-01-27 17:28:37 -05002197
Yury Selivanov0486f812014-01-29 12:18:59 -05002198 first_wrapped_param = tuple(wrapped_sig.parameters.values())[0]
2199 new_params = (first_wrapped_param,) + tuple(sig.parameters.values())
Yury Selivanovda5fe4f2014-01-27 17:28:37 -05002200
Yury Selivanov0486f812014-01-29 12:18:59 -05002201 return sig.replace(parameters=new_params)
Yury Selivanovda5fe4f2014-01-27 17:28:37 -05002202
Yury Selivanov63da7c72014-01-31 14:48:37 -05002203 if isfunction(obj) or _signature_is_functionlike(obj):
2204 # If it's a pure Python function, or an object that is duck type
2205 # of a Python function (Cython functions, for instance), then:
Yury Selivanovcf45f022015-05-20 14:38:50 -04002206 return _signature_from_function(sigcls, obj)
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002207
Yury Selivanova773de02014-02-21 18:30:53 -05002208 if _signature_is_builtin(obj):
Yury Selivanovda396452014-03-27 12:09:24 -04002209 return _signature_from_builtin(sigcls, obj,
Yury Selivanova773de02014-02-21 18:30:53 -05002210 skip_bound_arg=skip_bound_arg)
2211
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002212 if isinstance(obj, functools.partial):
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002213 wrapped_sig = _signature_from_callable(
Yury Selivanovda396452014-03-27 12:09:24 -04002214 obj.func,
2215 follow_wrapper_chains=follow_wrapper_chains,
2216 skip_bound_arg=skip_bound_arg,
2217 sigcls=sigcls)
Yury Selivanov62560fb2014-01-28 12:26:24 -05002218 return _signature_get_partial(wrapped_sig, obj)
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002219
2220 sig = None
2221 if isinstance(obj, type):
2222 # obj is a class or a metaclass
2223
2224 # First, let's see if it has an overloaded __call__ defined
2225 # in its metaclass
Yury Selivanov421f0c72014-01-29 12:05:40 -05002226 call = _signature_get_user_defined_method(type(obj), '__call__')
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002227 if call is not None:
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002228 sig = _signature_from_callable(
Yury Selivanovda396452014-03-27 12:09:24 -04002229 call,
2230 follow_wrapper_chains=follow_wrapper_chains,
2231 skip_bound_arg=skip_bound_arg,
2232 sigcls=sigcls)
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002233 else:
2234 # Now we check if the 'obj' class has a '__new__' method
Yury Selivanov421f0c72014-01-29 12:05:40 -05002235 new = _signature_get_user_defined_method(obj, '__new__')
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002236 if new is not None:
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002237 sig = _signature_from_callable(
Yury Selivanovda396452014-03-27 12:09:24 -04002238 new,
2239 follow_wrapper_chains=follow_wrapper_chains,
2240 skip_bound_arg=skip_bound_arg,
2241 sigcls=sigcls)
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002242 else:
2243 # Finally, we should have at least __init__ implemented
Yury Selivanov421f0c72014-01-29 12:05:40 -05002244 init = _signature_get_user_defined_method(obj, '__init__')
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002245 if init is not None:
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002246 sig = _signature_from_callable(
Yury Selivanovda396452014-03-27 12:09:24 -04002247 init,
2248 follow_wrapper_chains=follow_wrapper_chains,
2249 skip_bound_arg=skip_bound_arg,
2250 sigcls=sigcls)
Yury Selivanove7dcc5e2014-01-27 19:29:45 -05002251
2252 if sig is None:
Yury Selivanov7d2bfed2014-02-03 02:46:07 -05002253 # At this point we know, that `obj` is a class, with no user-
2254 # defined '__init__', '__new__', or class-level '__call__'
2255
Larry Hastings2623c8c2014-02-08 22:15:29 -08002256 for base in obj.__mro__[:-1]:
Yury Selivanov7d2bfed2014-02-03 02:46:07 -05002257 # Since '__text_signature__' is implemented as a
2258 # descriptor that extracts text signature from the
2259 # class docstring, if 'obj' is derived from a builtin
2260 # class, its own '__text_signature__' may be 'None'.
Larry Hastings2623c8c2014-02-08 22:15:29 -08002261 # Therefore, we go through the MRO (except the last
2262 # class in there, which is 'object') to find the first
Yury Selivanov7d2bfed2014-02-03 02:46:07 -05002263 # class with non-empty text signature.
2264 try:
2265 text_sig = base.__text_signature__
2266 except AttributeError:
2267 pass
2268 else:
2269 if text_sig:
2270 # If 'obj' class has a __text_signature__ attribute:
2271 # return a signature based on it
Yury Selivanovda396452014-03-27 12:09:24 -04002272 return _signature_fromstr(sigcls, obj, text_sig)
Yury Selivanov7d2bfed2014-02-03 02:46:07 -05002273
2274 # No '__text_signature__' was found for the 'obj' class.
2275 # Last option is to check if its '__init__' is
2276 # object.__init__ or type.__init__.
Larry Hastings2623c8c2014-02-08 22:15:29 -08002277 if type not in obj.__mro__:
Yury Selivanove7dcc5e2014-01-27 19:29:45 -05002278 # We have a class (not metaclass), but no user-defined
2279 # __init__ or __new__ for it
Yury Selivanovbf304fc2015-05-30 17:08:36 -04002280 if (obj.__init__ is object.__init__ and
2281 obj.__new__ is object.__new__):
Yury Selivanov7d2bfed2014-02-03 02:46:07 -05002282 # Return a signature of 'object' builtin.
2283 return signature(object)
Yury Selivanovbf304fc2015-05-30 17:08:36 -04002284 else:
2285 raise ValueError(
2286 'no signature found for builtin type {!r}'.format(obj))
Yury Selivanove7dcc5e2014-01-27 19:29:45 -05002287
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002288 elif not isinstance(obj, _NonUserDefinedCallables):
2289 # An object with __call__
2290 # We also check that the 'obj' is not an instance of
2291 # _WrapperDescriptor or _MethodWrapper to avoid
2292 # infinite recursion (and even potential segfault)
Yury Selivanov421f0c72014-01-29 12:05:40 -05002293 call = _signature_get_user_defined_method(type(obj), '__call__')
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002294 if call is not None:
Larry Hastings2623c8c2014-02-08 22:15:29 -08002295 try:
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002296 sig = _signature_from_callable(
Yury Selivanovda396452014-03-27 12:09:24 -04002297 call,
2298 follow_wrapper_chains=follow_wrapper_chains,
2299 skip_bound_arg=skip_bound_arg,
2300 sigcls=sigcls)
Larry Hastings2623c8c2014-02-08 22:15:29 -08002301 except ValueError as ex:
2302 msg = 'no signature found for {!r}'.format(obj)
2303 raise ValueError(msg) from ex
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002304
2305 if sig is not None:
2306 # For classes and objects we skip the first parameter of their
2307 # __call__, __new__, or __init__ methods
Yury Selivanov57d240e2014-02-19 16:27:23 -05002308 if skip_bound_arg:
2309 return _signature_bound_method(sig)
2310 else:
2311 return sig
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002312
2313 if isinstance(obj, types.BuiltinFunctionType):
2314 # Raise a nicer error message for builtins
2315 msg = 'no signature found for builtin function {!r}'.format(obj)
2316 raise ValueError(msg)
2317
2318 raise ValueError('callable {!r} is not supported by signature'.format(obj))
2319
2320
2321class _void:
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002322 """A private marker - used in Parameter & Signature."""
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002323
2324
2325class _empty:
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002326 """Marker object for Signature.empty and Parameter.empty."""
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002327
2328
Yury Selivanov21e83a52014-03-27 11:23:13 -04002329class _ParameterKind(enum.IntEnum):
2330 POSITIONAL_ONLY = 0
2331 POSITIONAL_OR_KEYWORD = 1
2332 VAR_POSITIONAL = 2
2333 KEYWORD_ONLY = 3
2334 VAR_KEYWORD = 4
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002335
2336 def __str__(self):
Yury Selivanov21e83a52014-03-27 11:23:13 -04002337 return self._name_
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002338
2339
Yury Selivanov21e83a52014-03-27 11:23:13 -04002340_POSITIONAL_ONLY = _ParameterKind.POSITIONAL_ONLY
2341_POSITIONAL_OR_KEYWORD = _ParameterKind.POSITIONAL_OR_KEYWORD
2342_VAR_POSITIONAL = _ParameterKind.VAR_POSITIONAL
2343_KEYWORD_ONLY = _ParameterKind.KEYWORD_ONLY
2344_VAR_KEYWORD = _ParameterKind.VAR_KEYWORD
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002345
2346
2347class Parameter:
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002348 """Represents a parameter in a function signature.
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002349
2350 Has the following public attributes:
2351
2352 * name : str
2353 The name of the parameter as a string.
2354 * default : object
2355 The default value for the parameter if specified. If the
Yury Selivanov8757ead2014-01-28 16:39:25 -05002356 parameter has no default value, this attribute is set to
2357 `Parameter.empty`.
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002358 * annotation
2359 The annotation for the parameter if specified. If the
Yury Selivanov8757ead2014-01-28 16:39:25 -05002360 parameter has no annotation, this attribute is set to
2361 `Parameter.empty`.
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002362 * kind : str
2363 Describes how argument values are bound to the parameter.
2364 Possible values: `Parameter.POSITIONAL_ONLY`,
2365 `Parameter.POSITIONAL_OR_KEYWORD`, `Parameter.VAR_POSITIONAL`,
2366 `Parameter.KEYWORD_ONLY`, `Parameter.VAR_KEYWORD`.
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002367 """
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002368
Yury Selivanov3f73ca22014-04-08 11:30:45 -04002369 __slots__ = ('_name', '_kind', '_default', '_annotation')
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002370
2371 POSITIONAL_ONLY = _POSITIONAL_ONLY
2372 POSITIONAL_OR_KEYWORD = _POSITIONAL_OR_KEYWORD
2373 VAR_POSITIONAL = _VAR_POSITIONAL
2374 KEYWORD_ONLY = _KEYWORD_ONLY
2375 VAR_KEYWORD = _VAR_KEYWORD
2376
2377 empty = _empty
2378
Yury Selivanov3f73ca22014-04-08 11:30:45 -04002379 def __init__(self, name, kind, *, default=_empty, annotation=_empty):
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002380
2381 if kind not in (_POSITIONAL_ONLY, _POSITIONAL_OR_KEYWORD,
2382 _VAR_POSITIONAL, _KEYWORD_ONLY, _VAR_KEYWORD):
2383 raise ValueError("invalid value for 'Parameter.kind' attribute")
2384 self._kind = kind
2385
2386 if default is not _empty:
2387 if kind in (_VAR_POSITIONAL, _VAR_KEYWORD):
2388 msg = '{} parameters cannot have default values'.format(kind)
2389 raise ValueError(msg)
2390 self._default = default
2391 self._annotation = annotation
2392
Yury Selivanov2393dca2014-01-27 15:07:58 -05002393 if name is _empty:
2394 raise ValueError('name is a required attribute for Parameter')
2395
2396 if not isinstance(name, str):
2397 raise TypeError("name must be a str, not a {!r}".format(name))
2398
2399 if not name.isidentifier():
2400 raise ValueError('{!r} is not a valid parameter name'.format(name))
2401
2402 self._name = name
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002403
Yury Selivanova5d63dd2014-03-27 11:31:43 -04002404 def __reduce__(self):
2405 return (type(self),
2406 (self._name, self._kind),
Yury Selivanov3f73ca22014-04-08 11:30:45 -04002407 {'_default': self._default,
Yury Selivanova5d63dd2014-03-27 11:31:43 -04002408 '_annotation': self._annotation})
2409
2410 def __setstate__(self, state):
Yury Selivanova5d63dd2014-03-27 11:31:43 -04002411 self._default = state['_default']
2412 self._annotation = state['_annotation']
2413
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002414 @property
2415 def name(self):
2416 return self._name
2417
2418 @property
2419 def default(self):
2420 return self._default
2421
2422 @property
2423 def annotation(self):
2424 return self._annotation
2425
2426 @property
2427 def kind(self):
2428 return self._kind
2429
Yury Selivanov3f73ca22014-04-08 11:30:45 -04002430 def replace(self, *, name=_void, kind=_void,
2431 annotation=_void, default=_void):
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002432 """Creates a customized copy of the Parameter."""
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002433
2434 if name is _void:
2435 name = self._name
2436
2437 if kind is _void:
2438 kind = self._kind
2439
2440 if annotation is _void:
2441 annotation = self._annotation
2442
2443 if default is _void:
2444 default = self._default
2445
Yury Selivanov3f73ca22014-04-08 11:30:45 -04002446 return type(self)(name, kind, default=default, annotation=annotation)
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002447
2448 def __str__(self):
2449 kind = self.kind
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002450 formatted = self._name
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002451
2452 # Add annotation and default value
2453 if self._annotation is not _empty:
2454 formatted = '{}:{}'.format(formatted,
2455 formatannotation(self._annotation))
2456
2457 if self._default is not _empty:
2458 formatted = '{}={}'.format(formatted, repr(self._default))
2459
2460 if kind == _VAR_POSITIONAL:
2461 formatted = '*' + formatted
2462 elif kind == _VAR_KEYWORD:
2463 formatted = '**' + formatted
2464
2465 return formatted
2466
2467 def __repr__(self):
Yury Selivanovf229bc52015-05-15 12:53:56 -04002468 return '<{} "{}">'.format(self.__class__.__name__, self)
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002469
Yury Selivanov67ae50e2014-04-08 11:46:50 -04002470 def __hash__(self):
Yury Selivanov08d4a4f2014-09-12 15:48:02 -04002471 return hash((self.name, self.kind, self.annotation, self.default))
Yury Selivanov67ae50e2014-04-08 11:46:50 -04002472
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002473 def __eq__(self, other):
Serhiy Storchaka2489bd52015-07-18 23:20:50 +03002474 if self is other:
2475 return True
Serhiy Storchaka3018cc42015-07-18 23:19:05 +03002476 if not isinstance(other, Parameter):
2477 return NotImplemented
2478 return (self._name == other._name and
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002479 self._kind == other._kind and
2480 self._default == other._default and
2481 self._annotation == other._annotation)
2482
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002483
2484class BoundArguments:
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002485 """Result of `Signature.bind` call. Holds the mapping of arguments
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002486 to the function's parameters.
2487
2488 Has the following public attributes:
2489
2490 * arguments : OrderedDict
2491 An ordered mutable mapping of parameters' names to arguments' values.
2492 Does not contain arguments' default values.
2493 * signature : Signature
2494 The Signature object that created this instance.
2495 * args : tuple
2496 Tuple of positional arguments values.
2497 * kwargs : dict
2498 Dict of keyword arguments values.
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002499 """
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002500
Yury Selivanov6abe0322015-05-13 17:18:41 -04002501 __slots__ = ('arguments', '_signature', '__weakref__')
2502
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002503 def __init__(self, signature, arguments):
2504 self.arguments = arguments
2505 self._signature = signature
2506
2507 @property
2508 def signature(self):
2509 return self._signature
2510
2511 @property
2512 def args(self):
2513 args = []
2514 for param_name, param in self._signature.parameters.items():
Yury Selivanov3f73ca22014-04-08 11:30:45 -04002515 if param.kind in (_VAR_KEYWORD, _KEYWORD_ONLY):
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002516 break
2517
2518 try:
2519 arg = self.arguments[param_name]
2520 except KeyError:
2521 # We're done here. Other arguments
2522 # will be mapped in 'BoundArguments.kwargs'
2523 break
2524 else:
2525 if param.kind == _VAR_POSITIONAL:
2526 # *args
2527 args.extend(arg)
2528 else:
2529 # plain argument
2530 args.append(arg)
2531
2532 return tuple(args)
2533
2534 @property
2535 def kwargs(self):
2536 kwargs = {}
2537 kwargs_started = False
2538 for param_name, param in self._signature.parameters.items():
2539 if not kwargs_started:
Yury Selivanov3f73ca22014-04-08 11:30:45 -04002540 if param.kind in (_VAR_KEYWORD, _KEYWORD_ONLY):
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002541 kwargs_started = True
2542 else:
2543 if param_name not in self.arguments:
2544 kwargs_started = True
2545 continue
2546
2547 if not kwargs_started:
2548 continue
2549
2550 try:
2551 arg = self.arguments[param_name]
2552 except KeyError:
2553 pass
2554 else:
2555 if param.kind == _VAR_KEYWORD:
2556 # **kwargs
2557 kwargs.update(arg)
2558 else:
2559 # plain keyword argument
2560 kwargs[param_name] = arg
2561
2562 return kwargs
2563
Yury Selivanovb907a512015-05-16 13:45:09 -04002564 def apply_defaults(self):
2565 """Set default values for missing arguments.
2566
2567 For variable-positional arguments (*args) the default is an
2568 empty tuple.
2569
2570 For variable-keyword arguments (**kwargs) the default is an
2571 empty dict.
2572 """
2573 arguments = self.arguments
2574 if not arguments:
2575 return
2576 new_arguments = []
2577 for name, param in self._signature.parameters.items():
2578 try:
2579 new_arguments.append((name, arguments[name]))
2580 except KeyError:
2581 if param.default is not _empty:
2582 val = param.default
2583 elif param.kind is _VAR_POSITIONAL:
2584 val = ()
2585 elif param.kind is _VAR_KEYWORD:
2586 val = {}
2587 else:
2588 # This BoundArguments was likely produced by
2589 # Signature.bind_partial().
2590 continue
2591 new_arguments.append((name, val))
2592 self.arguments = OrderedDict(new_arguments)
2593
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002594 def __eq__(self, other):
Serhiy Storchaka2489bd52015-07-18 23:20:50 +03002595 if self is other:
2596 return True
Serhiy Storchaka3018cc42015-07-18 23:19:05 +03002597 if not isinstance(other, BoundArguments):
2598 return NotImplemented
2599 return (self.signature == other.signature and
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002600 self.arguments == other.arguments)
2601
Yury Selivanov6abe0322015-05-13 17:18:41 -04002602 def __setstate__(self, state):
2603 self._signature = state['_signature']
2604 self.arguments = state['arguments']
2605
2606 def __getstate__(self):
2607 return {'_signature': self._signature, 'arguments': self.arguments}
2608
Yury Selivanov3f6538f2015-05-14 18:47:17 -04002609 def __repr__(self):
2610 args = []
2611 for arg, value in self.arguments.items():
2612 args.append('{}={!r}'.format(arg, value))
Yury Selivanovf229bc52015-05-15 12:53:56 -04002613 return '<{} ({})>'.format(self.__class__.__name__, ', '.join(args))
Yury Selivanov3f6538f2015-05-14 18:47:17 -04002614
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002615
2616class Signature:
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002617 """A Signature object represents the overall signature of a function.
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002618 It stores a Parameter object for each parameter accepted by the
2619 function, as well as information specific to the function itself.
2620
2621 A Signature object has the following public attributes and methods:
2622
2623 * parameters : OrderedDict
2624 An ordered mapping of parameters' names to the corresponding
2625 Parameter objects (keyword-only arguments are in the same order
2626 as listed in `code.co_varnames`).
2627 * return_annotation : object
2628 The annotation for the return type of the function if specified.
2629 If the function has no annotation for its return type, this
Yury Selivanov8757ead2014-01-28 16:39:25 -05002630 attribute is set to `Signature.empty`.
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002631 * bind(*args, **kwargs) -> BoundArguments
2632 Creates a mapping from positional and keyword arguments to
2633 parameters.
2634 * bind_partial(*args, **kwargs) -> BoundArguments
2635 Creates a partial mapping from positional and keyword arguments
2636 to parameters (simulating 'functools.partial' behavior.)
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002637 """
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002638
2639 __slots__ = ('_return_annotation', '_parameters')
2640
2641 _parameter_cls = Parameter
2642 _bound_arguments_cls = BoundArguments
2643
2644 empty = _empty
2645
2646 def __init__(self, parameters=None, *, return_annotation=_empty,
2647 __validate_parameters__=True):
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002648 """Constructs Signature from the given list of Parameter
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002649 objects and 'return_annotation'. All arguments are optional.
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002650 """
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002651
2652 if parameters is None:
2653 params = OrderedDict()
2654 else:
2655 if __validate_parameters__:
2656 params = OrderedDict()
2657 top_kind = _POSITIONAL_ONLY
Yury Selivanov07a9e452014-01-29 10:58:16 -05002658 kind_defaults = False
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002659
2660 for idx, param in enumerate(parameters):
2661 kind = param.kind
Yury Selivanov2393dca2014-01-27 15:07:58 -05002662 name = param.name
2663
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002664 if kind < top_kind:
Yury Selivanov3f73ca22014-04-08 11:30:45 -04002665 msg = 'wrong parameter order: {!r} before {!r}'
Yury Selivanov2393dca2014-01-27 15:07:58 -05002666 msg = msg.format(top_kind, kind)
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002667 raise ValueError(msg)
Yury Selivanov07a9e452014-01-29 10:58:16 -05002668 elif kind > top_kind:
2669 kind_defaults = False
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002670 top_kind = kind
2671
Yury Selivanov3f73ca22014-04-08 11:30:45 -04002672 if kind in (_POSITIONAL_ONLY, _POSITIONAL_OR_KEYWORD):
Yury Selivanov07a9e452014-01-29 10:58:16 -05002673 if param.default is _empty:
2674 if kind_defaults:
2675 # No default for this parameter, but the
2676 # previous parameter of the same kind had
2677 # a default
2678 msg = 'non-default argument follows default ' \
2679 'argument'
2680 raise ValueError(msg)
2681 else:
2682 # There is a default for this parameter.
2683 kind_defaults = True
2684
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002685 if name in params:
2686 msg = 'duplicate parameter name: {!r}'.format(name)
2687 raise ValueError(msg)
Yury Selivanov2393dca2014-01-27 15:07:58 -05002688
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002689 params[name] = param
2690 else:
2691 params = OrderedDict(((param.name, param)
2692 for param in parameters))
2693
2694 self._parameters = types.MappingProxyType(params)
2695 self._return_annotation = return_annotation
2696
2697 @classmethod
2698 def from_function(cls, func):
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002699 """Constructs Signature for the given python function."""
Yury Selivanov57c74fc2015-05-20 23:07:02 -04002700
2701 warnings.warn("inspect.Signature.from_function() is deprecated, "
Berker Peksagb5601582015-05-21 23:40:54 +03002702 "use Signature.from_callable()",
2703 DeprecationWarning, stacklevel=2)
Yury Selivanovcf45f022015-05-20 14:38:50 -04002704 return _signature_from_function(cls, func)
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002705
Larry Hastings44e2eaa2013-11-23 15:37:55 -08002706 @classmethod
2707 def from_builtin(cls, func):
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002708 """Constructs Signature for the given builtin function."""
Yury Selivanov57c74fc2015-05-20 23:07:02 -04002709
2710 warnings.warn("inspect.Signature.from_builtin() is deprecated, "
Berker Peksagb5601582015-05-21 23:40:54 +03002711 "use Signature.from_callable()",
2712 DeprecationWarning, stacklevel=2)
Yury Selivanov57d240e2014-02-19 16:27:23 -05002713 return _signature_from_builtin(cls, func)
Larry Hastings44e2eaa2013-11-23 15:37:55 -08002714
Yury Selivanovda396452014-03-27 12:09:24 -04002715 @classmethod
Yury Selivanovbcd4fc12015-05-20 14:30:08 -04002716 def from_callable(cls, obj, *, follow_wrapped=True):
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002717 """Constructs Signature for the given callable object."""
Yury Selivanovbcd4fc12015-05-20 14:30:08 -04002718 return _signature_from_callable(obj, sigcls=cls,
2719 follow_wrapper_chains=follow_wrapped)
Yury Selivanovda396452014-03-27 12:09:24 -04002720
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002721 @property
2722 def parameters(self):
2723 return self._parameters
2724
2725 @property
2726 def return_annotation(self):
2727 return self._return_annotation
2728
2729 def replace(self, *, parameters=_void, return_annotation=_void):
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002730 """Creates a customized copy of the Signature.
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002731 Pass 'parameters' and/or 'return_annotation' arguments
2732 to override them in the new copy.
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002733 """
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002734
2735 if parameters is _void:
2736 parameters = self.parameters.values()
2737
2738 if return_annotation is _void:
2739 return_annotation = self._return_annotation
2740
2741 return type(self)(parameters,
2742 return_annotation=return_annotation)
2743
Yury Selivanov08d4a4f2014-09-12 15:48:02 -04002744 def _hash_basis(self):
2745 params = tuple(param for param in self.parameters.values()
2746 if param.kind != _KEYWORD_ONLY)
2747
2748 kwo_params = {param.name: param for param in self.parameters.values()
2749 if param.kind == _KEYWORD_ONLY}
2750
2751 return params, kwo_params, self.return_annotation
2752
Yury Selivanov67ae50e2014-04-08 11:46:50 -04002753 def __hash__(self):
Yury Selivanov08d4a4f2014-09-12 15:48:02 -04002754 params, kwo_params, return_annotation = self._hash_basis()
2755 kwo_params = frozenset(kwo_params.values())
2756 return hash((params, kwo_params, return_annotation))
Yury Selivanov67ae50e2014-04-08 11:46:50 -04002757
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002758 def __eq__(self, other):
Serhiy Storchaka2489bd52015-07-18 23:20:50 +03002759 if self is other:
2760 return True
Serhiy Storchaka3018cc42015-07-18 23:19:05 +03002761 if not isinstance(other, Signature):
2762 return NotImplemented
Serhiy Storchaka2489bd52015-07-18 23:20:50 +03002763 return self._hash_basis() == other._hash_basis()
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002764
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002765 def _bind(self, args, kwargs, *, partial=False):
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002766 """Private method. Don't use directly."""
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002767
2768 arguments = OrderedDict()
2769
2770 parameters = iter(self.parameters.values())
2771 parameters_ex = ()
2772 arg_vals = iter(args)
2773
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002774 while True:
2775 # Let's iterate through the positional arguments and corresponding
2776 # parameters
2777 try:
2778 arg_val = next(arg_vals)
2779 except StopIteration:
2780 # No more positional arguments
2781 try:
2782 param = next(parameters)
2783 except StopIteration:
2784 # No more parameters. That's it. Just need to check that
2785 # we have no `kwargs` after this while loop
2786 break
2787 else:
2788 if param.kind == _VAR_POSITIONAL:
2789 # That's OK, just empty *args. Let's start parsing
2790 # kwargs
2791 break
2792 elif param.name in kwargs:
2793 if param.kind == _POSITIONAL_ONLY:
2794 msg = '{arg!r} parameter is positional only, ' \
2795 'but was passed as a keyword'
2796 msg = msg.format(arg=param.name)
2797 raise TypeError(msg) from None
2798 parameters_ex = (param,)
2799 break
2800 elif (param.kind == _VAR_KEYWORD or
2801 param.default is not _empty):
2802 # That's fine too - we have a default value for this
2803 # parameter. So, lets start parsing `kwargs`, starting
2804 # with the current parameter
2805 parameters_ex = (param,)
2806 break
2807 else:
Yury Selivanov38b0d5a2014-01-28 17:27:39 -05002808 # No default, not VAR_KEYWORD, not VAR_POSITIONAL,
2809 # not in `kwargs`
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002810 if partial:
2811 parameters_ex = (param,)
2812 break
2813 else:
Yury Selivanov86872752015-05-19 00:27:49 -04002814 msg = 'missing a required argument: {arg!r}'
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002815 msg = msg.format(arg=param.name)
2816 raise TypeError(msg) from None
2817 else:
2818 # We have a positional argument to process
2819 try:
2820 param = next(parameters)
2821 except StopIteration:
2822 raise TypeError('too many positional arguments') from None
2823 else:
2824 if param.kind in (_VAR_KEYWORD, _KEYWORD_ONLY):
2825 # Looks like we have no parameter for this positional
2826 # argument
Yury Selivanov86872752015-05-19 00:27:49 -04002827 raise TypeError(
2828 'too many positional arguments') from None
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002829
2830 if param.kind == _VAR_POSITIONAL:
2831 # We have an '*args'-like argument, let's fill it with
2832 # all positional arguments we have left and move on to
2833 # the next phase
2834 values = [arg_val]
2835 values.extend(arg_vals)
2836 arguments[param.name] = tuple(values)
2837 break
2838
2839 if param.name in kwargs:
Yury Selivanov86872752015-05-19 00:27:49 -04002840 raise TypeError(
2841 'multiple values for argument {arg!r}'.format(
2842 arg=param.name)) from None
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002843
2844 arguments[param.name] = arg_val
2845
2846 # Now, we iterate through the remaining parameters to process
2847 # keyword arguments
2848 kwargs_param = None
2849 for param in itertools.chain(parameters_ex, parameters):
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002850 if param.kind == _VAR_KEYWORD:
2851 # Memorize that we have a '**kwargs'-like parameter
2852 kwargs_param = param
2853 continue
2854
Yury Selivanov38b0d5a2014-01-28 17:27:39 -05002855 if param.kind == _VAR_POSITIONAL:
2856 # Named arguments don't refer to '*args'-like parameters.
2857 # We only arrive here if the positional arguments ended
2858 # before reaching the last parameter before *args.
2859 continue
2860
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002861 param_name = param.name
2862 try:
2863 arg_val = kwargs.pop(param_name)
2864 except KeyError:
2865 # We have no value for this parameter. It's fine though,
2866 # if it has a default value, or it is an '*args'-like
2867 # parameter, left alone by the processing of positional
2868 # arguments.
2869 if (not partial and param.kind != _VAR_POSITIONAL and
2870 param.default is _empty):
Yury Selivanov86872752015-05-19 00:27:49 -04002871 raise TypeError('missing a required argument: {arg!r}'. \
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002872 format(arg=param_name)) from None
2873
2874 else:
Yury Selivanov9b9ac952014-01-28 20:54:28 -05002875 if param.kind == _POSITIONAL_ONLY:
2876 # This should never happen in case of a properly built
2877 # Signature object (but let's have this check here
2878 # to ensure correct behaviour just in case)
2879 raise TypeError('{arg!r} parameter is positional only, '
2880 'but was passed as a keyword'. \
2881 format(arg=param.name))
2882
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002883 arguments[param_name] = arg_val
2884
2885 if kwargs:
2886 if kwargs_param is not None:
2887 # Process our '**kwargs'-like parameter
2888 arguments[kwargs_param.name] = kwargs
2889 else:
Yury Selivanov86872752015-05-19 00:27:49 -04002890 raise TypeError(
2891 'got an unexpected keyword argument {arg!r}'.format(
2892 arg=next(iter(kwargs))))
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002893
2894 return self._bound_arguments_cls(self, arguments)
2895
Yury Selivanovc45873e2014-01-29 12:10:27 -05002896 def bind(*args, **kwargs):
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002897 """Get a BoundArguments object, that maps the passed `args`
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002898 and `kwargs` to the function's signature. Raises `TypeError`
2899 if the passed arguments can not be bound.
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002900 """
Yury Selivanovc45873e2014-01-29 12:10:27 -05002901 return args[0]._bind(args[1:], kwargs)
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002902
Yury Selivanovc45873e2014-01-29 12:10:27 -05002903 def bind_partial(*args, **kwargs):
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002904 """Get a BoundArguments object, that partially maps the
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002905 passed `args` and `kwargs` to the function's signature.
2906 Raises `TypeError` if the passed arguments can not be bound.
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002907 """
Yury Selivanovc45873e2014-01-29 12:10:27 -05002908 return args[0]._bind(args[1:], kwargs, partial=True)
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002909
Yury Selivanova5d63dd2014-03-27 11:31:43 -04002910 def __reduce__(self):
2911 return (type(self),
2912 (tuple(self._parameters.values()),),
2913 {'_return_annotation': self._return_annotation})
2914
2915 def __setstate__(self, state):
2916 self._return_annotation = state['_return_annotation']
2917
Yury Selivanov374375d2014-03-27 12:41:53 -04002918 def __repr__(self):
Yury Selivanovf229bc52015-05-15 12:53:56 -04002919 return '<{} {}>'.format(self.__class__.__name__, self)
Yury Selivanov374375d2014-03-27 12:41:53 -04002920
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002921 def __str__(self):
2922 result = []
Yury Selivanov2393dca2014-01-27 15:07:58 -05002923 render_pos_only_separator = False
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002924 render_kw_only_separator = True
Yury Selivanov2393dca2014-01-27 15:07:58 -05002925 for param in self.parameters.values():
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002926 formatted = str(param)
2927
2928 kind = param.kind
Yury Selivanov2393dca2014-01-27 15:07:58 -05002929
2930 if kind == _POSITIONAL_ONLY:
2931 render_pos_only_separator = True
2932 elif render_pos_only_separator:
2933 # It's not a positional-only parameter, and the flag
2934 # is set to 'True' (there were pos-only params before.)
2935 result.append('/')
2936 render_pos_only_separator = False
2937
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002938 if kind == _VAR_POSITIONAL:
2939 # OK, we have an '*args'-like parameter, so we won't need
2940 # a '*' to separate keyword-only arguments
2941 render_kw_only_separator = False
2942 elif kind == _KEYWORD_ONLY and render_kw_only_separator:
2943 # We have a keyword-only parameter to render and we haven't
2944 # rendered an '*args'-like parameter before, so add a '*'
2945 # separator to the parameters list ("foo(arg1, *, arg2)" case)
2946 result.append('*')
2947 # This condition should be only triggered once, so
2948 # reset the flag
2949 render_kw_only_separator = False
2950
2951 result.append(formatted)
2952
Yury Selivanov2393dca2014-01-27 15:07:58 -05002953 if render_pos_only_separator:
2954 # There were only positional-only parameters, hence the
2955 # flag was not reset to 'False'
2956 result.append('/')
2957
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002958 rendered = '({})'.format(', '.join(result))
2959
2960 if self.return_annotation is not _empty:
2961 anno = formatannotation(self.return_annotation)
2962 rendered += ' -> {}'.format(anno)
2963
2964 return rendered
Nick Coghlanf94a16b2013-09-22 22:46:49 +10002965
Yury Selivanovda396452014-03-27 12:09:24 -04002966
Yury Selivanovbcd4fc12015-05-20 14:30:08 -04002967def signature(obj, *, follow_wrapped=True):
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002968 """Get a signature object for the passed callable."""
Yury Selivanovbcd4fc12015-05-20 14:30:08 -04002969 return Signature.from_callable(obj, follow_wrapped=follow_wrapped)
Yury Selivanovda396452014-03-27 12:09:24 -04002970
2971
Nick Coghlanf94a16b2013-09-22 22:46:49 +10002972def _main():
2973 """ Logic for inspecting an object given at command line """
2974 import argparse
2975 import importlib
2976
2977 parser = argparse.ArgumentParser()
2978 parser.add_argument(
2979 'object',
2980 help="The object to be analysed. "
2981 "It supports the 'module:qualname' syntax")
2982 parser.add_argument(
2983 '-d', '--details', action='store_true',
2984 help='Display info about the module rather than its source code')
2985
2986 args = parser.parse_args()
2987
2988 target = args.object
2989 mod_name, has_attrs, attrs = target.partition(":")
2990 try:
2991 obj = module = importlib.import_module(mod_name)
2992 except Exception as exc:
2993 msg = "Failed to import {} ({}: {})".format(mod_name,
2994 type(exc).__name__,
2995 exc)
2996 print(msg, file=sys.stderr)
2997 exit(2)
2998
2999 if has_attrs:
3000 parts = attrs.split(".")
3001 obj = module
3002 for part in parts:
3003 obj = getattr(obj, part)
3004
3005 if module.__name__ in sys.builtin_module_names:
3006 print("Can't get info for builtin modules.", file=sys.stderr)
3007 exit(1)
3008
3009 if args.details:
3010 print('Target: {}'.format(target))
3011 print('Origin: {}'.format(getsourcefile(module)))
3012 print('Cached: {}'.format(module.__cached__))
3013 if obj is module:
3014 print('Loader: {}'.format(repr(module.__loader__)))
3015 if hasattr(module, '__path__'):
3016 print('Submodule search path: {}'.format(module.__path__))
3017 else:
3018 try:
3019 __, lineno = findsource(obj)
3020 except Exception:
3021 pass
3022 else:
3023 print('Line: {}'.format(lineno))
3024
3025 print('\n')
3026 else:
3027 print(getsource(obj))
3028
3029
3030if __name__ == "__main__":
3031 _main()