blob: 72c1691b38eda1b2c704b44d83dac5a16f24254f [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
Martin Panter0f0eac42016-09-07 11:04:41 +0000174 Generator function objects provide the same attributes as functions.
175 See help(isfunction) for a list of attributes."""
Georg Brandlb1441c72009-01-03 22:33:39 +0000176 return bool((isfunction(object) or ismethod(object)) and
Yury Selivanov5376ba92015-06-22 12:19:30 -0400177 object.__code__.co_flags & CO_GENERATOR)
Yury Selivanov75445082015-05-11 22:57:16 -0400178
179def iscoroutinefunction(object):
180 """Return true if the object is a coroutine function.
181
182 Coroutine functions are defined with "async def" syntax,
183 or generators decorated with "types.coroutine".
184 """
185 return bool((isfunction(object) or ismethod(object)) and
Yury Selivanov5376ba92015-06-22 12:19:30 -0400186 object.__code__.co_flags & CO_COROUTINE)
Yury Selivanov75445082015-05-11 22:57:16 -0400187
Christian Heimes7131fd92008-02-19 14:21:46 +0000188def isgenerator(object):
189 """Return true if the object is a generator.
190
191 Generator objects provide these attributes:
Ezio Melotti30b9d5d2013-08-17 15:50:46 +0300192 __iter__ defined to support iteration over container
Christian Heimes7131fd92008-02-19 14:21:46 +0000193 close raises a new GeneratorExit exception inside the
194 generator to terminate the iteration
195 gi_code code object
196 gi_frame frame object or possibly None once the generator has
197 been exhausted
198 gi_running set to 1 when generator is executing, 0 otherwise
199 next return the next item from the container
200 send resumes the generator and "sends" a value that becomes
201 the result of the current yield-expression
202 throw used to raise an exception inside the generator"""
Yury Selivanov5376ba92015-06-22 12:19:30 -0400203 return isinstance(object, types.GeneratorType)
Yury Selivanov75445082015-05-11 22:57:16 -0400204
205def iscoroutine(object):
206 """Return true if the object is a coroutine."""
Yury Selivanov5376ba92015-06-22 12:19:30 -0400207 return isinstance(object, types.CoroutineType)
Christian Heimes7131fd92008-02-19 14:21:46 +0000208
Yury Selivanovfdbeb2b2015-07-03 13:11:35 -0400209def isawaitable(object):
210 """Return true is object can be passed to an ``await`` expression."""
211 return (isinstance(object, types.CoroutineType) or
212 isinstance(object, types.GeneratorType) and
213 object.gi_code.co_flags & CO_ITERABLE_COROUTINE or
214 isinstance(object, collections.abc.Awaitable))
215
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000216def istraceback(object):
217 """Return true if the object is a traceback.
218
219 Traceback objects provide these attributes:
220 tb_frame frame object at this level
221 tb_lasti index of last attempted instruction in bytecode
222 tb_lineno current line number in Python source code
223 tb_next next inner traceback object (called by this level)"""
Tim Peters28bc59f2001-09-16 08:40:16 +0000224 return isinstance(object, types.TracebackType)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000225
226def isframe(object):
227 """Return true if the object is a frame object.
228
229 Frame objects provide these attributes:
230 f_back next outer frame object (this frame's caller)
231 f_builtins built-in namespace seen by this frame
232 f_code code object being executed in this frame
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000233 f_globals global namespace seen by this frame
234 f_lasti index of last attempted instruction in bytecode
235 f_lineno current line number in Python source code
236 f_locals local namespace seen by this frame
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000237 f_trace tracing function for this frame, or None"""
Tim Peters28bc59f2001-09-16 08:40:16 +0000238 return isinstance(object, types.FrameType)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000239
240def iscode(object):
241 """Return true if the object is a code object.
242
243 Code objects provide these attributes:
244 co_argcount number of arguments (not including * or ** args)
245 co_code string of raw compiled bytecode
246 co_consts tuple of constants used in the bytecode
247 co_filename name of file in which this code object was created
248 co_firstlineno number of first line in Python source code
249 co_flags bitmap: 1=optimized | 2=newlocals | 4=*arg | 8=**arg
250 co_lnotab encoded mapping of line numbers to bytecode indices
251 co_name name with which this code object was defined
252 co_names tuple of names of local variables
253 co_nlocals number of local variables
254 co_stacksize virtual machine stack space required
255 co_varnames tuple of names of arguments and local variables"""
Tim Peters28bc59f2001-09-16 08:40:16 +0000256 return isinstance(object, types.CodeType)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000257
258def isbuiltin(object):
259 """Return true if the object is a built-in function or method.
260
261 Built-in functions and methods provide these attributes:
262 __doc__ documentation string
263 __name__ original name of this function or method
264 __self__ instance to which a method is bound, or None"""
Tim Peters28bc59f2001-09-16 08:40:16 +0000265 return isinstance(object, types.BuiltinFunctionType)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000266
267def isroutine(object):
268 """Return true if the object is any kind of function or method."""
Tim Peters536d2262001-09-20 05:13:38 +0000269 return (isbuiltin(object)
270 or isfunction(object)
271 or ismethod(object)
272 or ismethoddescriptor(object))
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000273
Christian Heimesbe5b30b2008-03-03 19:18:51 +0000274def isabstract(object):
275 """Return true if the object is an abstract base class (ABC)."""
Benjamin Petersona0dfa822009-11-13 02:25:08 +0000276 return bool(isinstance(object, type) and object.__flags__ & TPFLAGS_IS_ABSTRACT)
Christian Heimesbe5b30b2008-03-03 19:18:51 +0000277
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000278def getmembers(object, predicate=None):
279 """Return all members of an object as (name, value) pairs sorted by name.
280 Optionally, only return members that satisfy a given predicate."""
Antoine Pitrou86a8a9a2011-12-21 09:57:40 +0100281 if isclass(object):
282 mro = (object,) + getmro(object)
283 else:
284 mro = ()
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000285 results = []
Ethan Furmane03ea372013-09-25 07:14:41 -0700286 processed = set()
287 names = dir(object)
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700288 # :dd any DynamicClassAttributes to the list of names if object is a class;
Ethan Furmane03ea372013-09-25 07:14:41 -0700289 # this may result in duplicate entries if, for example, a virtual
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700290 # attribute with the same name as a DynamicClassAttribute exists
Ethan Furmane03ea372013-09-25 07:14:41 -0700291 try:
292 for base in object.__bases__:
293 for k, v in base.__dict__.items():
294 if isinstance(v, types.DynamicClassAttribute):
295 names.append(k)
296 except AttributeError:
297 pass
298 for key in names:
Ethan Furman63c141c2013-10-18 00:27:39 -0700299 # First try to get the value via getattr. Some descriptors don't
300 # like calling their __get__ (see bug #1785), so fall back to
301 # looking in the __dict__.
302 try:
303 value = getattr(object, key)
304 # handle the duplicate key
305 if key in processed:
306 raise AttributeError
307 except AttributeError:
308 for base in mro:
309 if key in base.__dict__:
310 value = base.__dict__[key]
311 break
312 else:
313 # could be a (currently) missing slot member, or a buggy
314 # __dir__; discard and move on
Antoine Pitrou86a8a9a2011-12-21 09:57:40 +0100315 continue
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000316 if not predicate or predicate(value):
317 results.append((key, value))
Ethan Furmane03ea372013-09-25 07:14:41 -0700318 processed.add(key)
319 results.sort(key=lambda pair: pair[0])
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000320 return results
321
Christian Heimes25bb7832008-01-11 16:17:00 +0000322Attribute = namedtuple('Attribute', 'name kind defining_class object')
323
Tim Peters13b49d32001-09-23 02:00:29 +0000324def classify_class_attrs(cls):
325 """Return list of attribute-descriptor tuples.
326
327 For each name in dir(cls), the return list contains a 4-tuple
328 with these elements:
329
330 0. The name (a string).
331
332 1. The kind of attribute this is, one of these strings:
333 'class method' created via classmethod()
334 'static method' created via staticmethod()
335 'property' created via property()
Ethan Furmane03ea372013-09-25 07:14:41 -0700336 'method' any other flavor of method or descriptor
Tim Peters13b49d32001-09-23 02:00:29 +0000337 'data' not a method
338
339 2. The class which defined this attribute (a class).
340
Ethan Furmane03ea372013-09-25 07:14:41 -0700341 3. The object as obtained by calling getattr; if this fails, or if the
342 resulting object does not live anywhere in the class' mro (including
343 metaclasses) then the object is looked up in the defining class's
344 dict (found by walking the mro).
Ethan Furman668dede2013-09-14 18:53:26 -0700345
346 If one of the items in dir(cls) is stored in the metaclass it will now
347 be discovered and not have None be listed as the class in which it was
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700348 defined. Any items whose home class cannot be discovered are skipped.
Tim Peters13b49d32001-09-23 02:00:29 +0000349 """
350
351 mro = getmro(cls)
Ethan Furman668dede2013-09-14 18:53:26 -0700352 metamro = getmro(type(cls)) # for attributes stored in the metaclass
Ethan Furmane03ea372013-09-25 07:14:41 -0700353 metamro = tuple([cls for cls in metamro if cls not in (type, object)])
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700354 class_bases = (cls,) + mro
355 all_bases = class_bases + metamro
Tim Peters13b49d32001-09-23 02:00:29 +0000356 names = dir(cls)
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700357 # :dd any DynamicClassAttributes to the list of names;
Ethan Furmane03ea372013-09-25 07:14:41 -0700358 # this may result in duplicate entries if, for example, a virtual
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700359 # attribute with the same name as a DynamicClassAttribute exists.
Ethan Furman63c141c2013-10-18 00:27:39 -0700360 for base in mro:
Ethan Furmane03ea372013-09-25 07:14:41 -0700361 for k, v in base.__dict__.items():
362 if isinstance(v, types.DynamicClassAttribute):
363 names.append(k)
Tim Peters13b49d32001-09-23 02:00:29 +0000364 result = []
Ethan Furmane03ea372013-09-25 07:14:41 -0700365 processed = set()
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700366
Tim Peters13b49d32001-09-23 02:00:29 +0000367 for name in names:
Antoine Pitrou86a8a9a2011-12-21 09:57:40 +0100368 # Get the object associated with the name, and where it was defined.
Ethan Furmane03ea372013-09-25 07:14:41 -0700369 # Normal objects will be looked up with both getattr and directly in
370 # its class' dict (in case getattr fails [bug #1785], and also to look
371 # for a docstring).
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700372 # For DynamicClassAttributes on the second pass we only look in the
Ethan Furmane03ea372013-09-25 07:14:41 -0700373 # class's dict.
374 #
Tim Peters13b49d32001-09-23 02:00:29 +0000375 # Getting an obj from the __dict__ sometimes reveals more than
376 # using getattr. Static and class methods are dramatic examples.
Antoine Pitrou86a8a9a2011-12-21 09:57:40 +0100377 homecls = None
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700378 get_obj = None
379 dict_obj = None
Ethan Furmane03ea372013-09-25 07:14:41 -0700380 if name not in processed:
381 try:
Ethan Furmana8b07072013-10-18 01:22:08 -0700382 if name == '__dict__':
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700383 raise Exception("__dict__ is special, don't want the proxy")
Ethan Furmane03ea372013-09-25 07:14:41 -0700384 get_obj = getattr(cls, name)
385 except Exception as exc:
386 pass
387 else:
Ethan Furmane03ea372013-09-25 07:14:41 -0700388 homecls = getattr(get_obj, "__objclass__", homecls)
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700389 if homecls not in class_bases:
Ethan Furmane03ea372013-09-25 07:14:41 -0700390 # if the resulting object does not live somewhere in the
Ethan Furman63c141c2013-10-18 00:27:39 -0700391 # mro, drop it and search the mro manually
Ethan Furmane03ea372013-09-25 07:14:41 -0700392 homecls = None
Ethan Furman63c141c2013-10-18 00:27:39 -0700393 last_cls = None
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700394 # first look in the classes
395 for srch_cls in class_bases:
Ethan Furman63c141c2013-10-18 00:27:39 -0700396 srch_obj = getattr(srch_cls, name, None)
Yury Selivanovbf341fb2015-05-21 15:41:57 -0400397 if srch_obj is get_obj:
Ethan Furman63c141c2013-10-18 00:27:39 -0700398 last_cls = srch_cls
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700399 # then check the metaclasses
400 for srch_cls in metamro:
401 try:
402 srch_obj = srch_cls.__getattr__(cls, name)
403 except AttributeError:
404 continue
Yury Selivanovbf341fb2015-05-21 15:41:57 -0400405 if srch_obj is get_obj:
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700406 last_cls = srch_cls
Ethan Furman63c141c2013-10-18 00:27:39 -0700407 if last_cls is not None:
408 homecls = last_cls
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700409 for base in all_bases:
Ethan Furmane03ea372013-09-25 07:14:41 -0700410 if name in base.__dict__:
411 dict_obj = base.__dict__[name]
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700412 if homecls not in metamro:
413 homecls = base
Ethan Furmane03ea372013-09-25 07:14:41 -0700414 break
Ethan Furman63c141c2013-10-18 00:27:39 -0700415 if homecls is None:
416 # unable to locate the attribute anywhere, most likely due to
417 # buggy custom __dir__; discard and move on
418 continue
Yury Selivanovbf341fb2015-05-21 15:41:57 -0400419 obj = get_obj if get_obj is not None else dict_obj
Ethan Furmane03ea372013-09-25 07:14:41 -0700420 # Classify the object or its descriptor.
Ethan Furman63c141c2013-10-18 00:27:39 -0700421 if isinstance(dict_obj, staticmethod):
Tim Peters13b49d32001-09-23 02:00:29 +0000422 kind = "static method"
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700423 obj = dict_obj
Ethan Furman63c141c2013-10-18 00:27:39 -0700424 elif isinstance(dict_obj, classmethod):
Tim Peters13b49d32001-09-23 02:00:29 +0000425 kind = "class method"
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700426 obj = dict_obj
427 elif isinstance(dict_obj, property):
Tim Peters13b49d32001-09-23 02:00:29 +0000428 kind = "property"
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700429 obj = dict_obj
Yury Selivanov0860a0b2014-01-31 14:28:44 -0500430 elif isroutine(obj):
Tim Peters13b49d32001-09-23 02:00:29 +0000431 kind = "method"
Antoine Pitrou86a8a9a2011-12-21 09:57:40 +0100432 else:
Ethan Furmane03ea372013-09-25 07:14:41 -0700433 kind = "data"
Christian Heimes25bb7832008-01-11 16:17:00 +0000434 result.append(Attribute(name, kind, homecls, obj))
Ethan Furmane03ea372013-09-25 07:14:41 -0700435 processed.add(name)
Tim Peters13b49d32001-09-23 02:00:29 +0000436 return result
437
Tim Peterse0b2d7a2001-09-22 06:10:55 +0000438# ----------------------------------------------------------- class helpers
Tim Peterse0b2d7a2001-09-22 06:10:55 +0000439
440def getmro(cls):
441 "Return tuple of base classes (including cls) in method resolution order."
Benjamin Petersonb82c8e52010-11-04 00:38:49 +0000442 return cls.__mro__
Tim Peterse0b2d7a2001-09-22 06:10:55 +0000443
Nick Coghlane8c45d62013-07-28 20:00:01 +1000444# -------------------------------------------------------- function helpers
445
446def unwrap(func, *, stop=None):
447 """Get the object wrapped by *func*.
448
449 Follows the chain of :attr:`__wrapped__` attributes returning the last
450 object in the chain.
451
452 *stop* is an optional callback accepting an object in the wrapper chain
453 as its sole argument that allows the unwrapping to be terminated early if
454 the callback returns a true value. If the callback never returns a true
455 value, the last object in the chain is returned as usual. For example,
456 :func:`signature` uses this to stop unwrapping if any object in the
457 chain has a ``__signature__`` attribute defined.
458
459 :exc:`ValueError` is raised if a cycle is encountered.
460
461 """
462 if stop is None:
463 def _is_wrapper(f):
464 return hasattr(f, '__wrapped__')
465 else:
466 def _is_wrapper(f):
467 return hasattr(f, '__wrapped__') and not stop(f)
468 f = func # remember the original func for error reporting
469 memo = {id(f)} # Memoise by id to tolerate non-hashable objects
470 while _is_wrapper(func):
471 func = func.__wrapped__
472 id_func = id(func)
473 if id_func in memo:
474 raise ValueError('wrapper loop when unwrapping {!r}'.format(f))
475 memo.add(id_func)
476 return func
477
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000478# -------------------------------------------------- source code extraction
479def indentsize(line):
480 """Return the indent size, in spaces, at the start of a line of text."""
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000481 expline = line.expandtabs()
482 return len(expline) - len(expline.lstrip())
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000483
Serhiy Storchaka5cf2b7252015-04-03 22:38:53 +0300484def _findclass(func):
485 cls = sys.modules.get(func.__module__)
486 if cls is None:
487 return None
488 for name in func.__qualname__.split('.')[:-1]:
489 cls = getattr(cls, name)
490 if not isclass(cls):
491 return None
492 return cls
493
494def _finddoc(obj):
495 if isclass(obj):
496 for base in obj.__mro__:
497 if base is not object:
498 try:
499 doc = base.__doc__
500 except AttributeError:
501 continue
502 if doc is not None:
503 return doc
504 return None
505
506 if ismethod(obj):
507 name = obj.__func__.__name__
508 self = obj.__self__
509 if (isclass(self) and
510 getattr(getattr(self, name, None), '__func__') is obj.__func__):
511 # classmethod
512 cls = self
513 else:
514 cls = self.__class__
515 elif isfunction(obj):
516 name = obj.__name__
517 cls = _findclass(obj)
518 if cls is None or getattr(cls, name) is not obj:
519 return None
520 elif isbuiltin(obj):
521 name = obj.__name__
522 self = obj.__self__
523 if (isclass(self) and
524 self.__qualname__ + '.' + name == obj.__qualname__):
525 # classmethod
526 cls = self
527 else:
528 cls = self.__class__
Serhiy Storchakaac4bdcc2015-10-29 08:15:50 +0200529 # Should be tested before isdatadescriptor().
530 elif isinstance(obj, property):
531 func = obj.fget
532 name = func.__name__
533 cls = _findclass(func)
534 if cls is None or getattr(cls, name) is not obj:
535 return None
Serhiy Storchaka5cf2b7252015-04-03 22:38:53 +0300536 elif ismethoddescriptor(obj) or isdatadescriptor(obj):
537 name = obj.__name__
538 cls = obj.__objclass__
539 if getattr(cls, name) is not obj:
540 return None
Serhiy Storchaka5cf2b7252015-04-03 22:38:53 +0300541 else:
542 return None
543
544 for base in cls.__mro__:
545 try:
546 doc = getattr(base, name).__doc__
547 except AttributeError:
548 continue
549 if doc is not None:
550 return doc
551 return None
552
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000553def getdoc(object):
554 """Get the documentation string for an object.
555
556 All tabs are expanded to spaces. To clean up docstrings that are
557 indented to line up with blocks of code, any whitespace than can be
558 uniformly removed from the second line onwards is removed."""
Tim Peters24008312002-03-17 18:56:20 +0000559 try:
560 doc = object.__doc__
561 except AttributeError:
562 return None
Serhiy Storchaka5cf2b7252015-04-03 22:38:53 +0300563 if doc is None:
564 try:
565 doc = _finddoc(object)
566 except (AttributeError, TypeError):
567 return None
Guido van Rossum3172c5d2007-10-16 18:12:55 +0000568 if not isinstance(doc, str):
Tim Peters24008312002-03-17 18:56:20 +0000569 return None
Georg Brandl0c77a822008-06-10 16:37:50 +0000570 return cleandoc(doc)
571
572def cleandoc(doc):
573 """Clean up indentation from docstrings.
574
575 Any whitespace that can be uniformly removed from the second line
576 onwards is removed."""
Tim Peters24008312002-03-17 18:56:20 +0000577 try:
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000578 lines = doc.expandtabs().split('\n')
Tim Peters24008312002-03-17 18:56:20 +0000579 except UnicodeError:
580 return None
581 else:
Ka-Ping Yeea59ef7b2002-11-30 03:53:15 +0000582 # Find minimum indentation of any non-blank lines after first line.
Christian Heimesa37d4c62007-12-04 23:02:19 +0000583 margin = sys.maxsize
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000584 for line in lines[1:]:
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000585 content = len(line.lstrip())
Ka-Ping Yeea59ef7b2002-11-30 03:53:15 +0000586 if content:
587 indent = len(line) - content
588 margin = min(margin, indent)
589 # Remove indentation.
590 if lines:
591 lines[0] = lines[0].lstrip()
Christian Heimesa37d4c62007-12-04 23:02:19 +0000592 if margin < sys.maxsize:
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000593 for i in range(1, len(lines)): lines[i] = lines[i][margin:]
Ka-Ping Yeea59ef7b2002-11-30 03:53:15 +0000594 # Remove any trailing or leading blank lines.
595 while lines and not lines[-1]:
596 lines.pop()
597 while lines and not lines[0]:
598 lines.pop(0)
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000599 return '\n'.join(lines)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000600
601def getfile(object):
Ka-Ping Yeec113c242001-03-02 02:08:53 +0000602 """Work out which source or compiled file an object was defined in."""
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000603 if ismodule(object):
604 if hasattr(object, '__file__'):
605 return object.__file__
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +0000606 raise TypeError('{!r} is a built-in module'.format(object))
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000607 if isclass(object):
Yury Selivanov2eed8b72014-01-27 13:24:56 -0500608 if hasattr(object, '__module__'):
609 object = sys.modules.get(object.__module__)
610 if hasattr(object, '__file__'):
611 return object.__file__
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +0000612 raise TypeError('{!r} is a built-in class'.format(object))
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000613 if ismethod(object):
Christian Heimesff737952007-11-27 10:40:20 +0000614 object = object.__func__
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000615 if isfunction(object):
Neal Norwitz221085d2007-02-25 20:55:47 +0000616 object = object.__code__
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000617 if istraceback(object):
618 object = object.tb_frame
619 if isframe(object):
620 object = object.f_code
621 if iscode(object):
622 return object.co_filename
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +0000623 raise TypeError('{!r} is not a module, class, method, '
624 'function, traceback, frame, or code object'.format(object))
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000625
Ka-Ping Yee4d6fc7f2001-04-10 11:43:00 +0000626def getmodulename(path):
627 """Return the module name for a given file, or None."""
Nick Coghlan76e07702012-07-18 23:14:57 +1000628 fname = os.path.basename(path)
629 # Check for paths that look like an actual module file
630 suffixes = [(-len(suffix), suffix)
631 for suffix in importlib.machinery.all_suffixes()]
632 suffixes.sort() # try longest suffixes first, in case they overlap
633 for neglen, suffix in suffixes:
634 if fname.endswith(suffix):
635 return fname[:neglen]
636 return None
Ka-Ping Yee4d6fc7f2001-04-10 11:43:00 +0000637
Ka-Ping Yeec113c242001-03-02 02:08:53 +0000638def getsourcefile(object):
R. David Murraya1b37402010-06-17 02:04:29 +0000639 """Return the filename that can be used to locate an object's source.
640 Return None if no way can be identified to get the source.
641 """
Ka-Ping Yeec113c242001-03-02 02:08:53 +0000642 filename = getfile(object)
Brett Cannoncb66eb02012-05-11 12:58:42 -0400643 all_bytecode_suffixes = importlib.machinery.DEBUG_BYTECODE_SUFFIXES[:]
644 all_bytecode_suffixes += importlib.machinery.OPTIMIZED_BYTECODE_SUFFIXES[:]
645 if any(filename.endswith(s) for s in all_bytecode_suffixes):
646 filename = (os.path.splitext(filename)[0] +
647 importlib.machinery.SOURCE_SUFFIXES[0])
648 elif any(filename.endswith(s) for s in
649 importlib.machinery.EXTENSION_SUFFIXES):
650 return None
Thomas Wouters477c8d52006-05-27 19:21:47 +0000651 if os.path.exists(filename):
652 return filename
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000653 # only return a non-existent filename if the module has a PEP 302 loader
Brett Cannon4c14b5d2013-05-04 13:56:58 -0400654 if getattr(getmodule(object, filename), '__loader__', None) is not None:
Ka-Ping Yeec113c242001-03-02 02:08:53 +0000655 return filename
R. David Murraya1b37402010-06-17 02:04:29 +0000656 # or it is in the linecache
657 if filename in linecache.cache:
658 return filename
Ka-Ping Yeec113c242001-03-02 02:08:53 +0000659
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000660def getabsfile(object, _filename=None):
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000661 """Return an absolute path to the source or compiled file for an object.
Ka-Ping Yeec113c242001-03-02 02:08:53 +0000662
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000663 The idea is for each object to have a unique origin, so this routine
664 normalizes the result as much as possible."""
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000665 if _filename is None:
666 _filename = getsourcefile(object) or getfile(object)
667 return os.path.normcase(os.path.abspath(_filename))
Ka-Ping Yeec113c242001-03-02 02:08:53 +0000668
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000669modulesbyfile = {}
Thomas Wouters89f507f2006-12-13 04:49:30 +0000670_filesbymodname = {}
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000671
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000672def getmodule(object, _filename=None):
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000673 """Return the module an object was defined in, or None if not found."""
Ka-Ping Yee202c99b2001-04-13 09:15:08 +0000674 if ismodule(object):
675 return object
Johannes Gijsbers93245262004-09-11 15:53:22 +0000676 if hasattr(object, '__module__'):
Ka-Ping Yee8b58b842001-03-01 13:56:16 +0000677 return sys.modules.get(object.__module__)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000678 # Try the filename to modulename cache
679 if _filename is not None and _filename in modulesbyfile:
680 return sys.modules.get(modulesbyfile[_filename])
681 # Try the cache again with the absolute file name
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000682 try:
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000683 file = getabsfile(object, _filename)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000684 except TypeError:
685 return None
Raymond Hettinger54f02222002-06-01 14:18:47 +0000686 if file in modulesbyfile:
Ka-Ping Yeeb38bbbd2003-03-28 16:29:50 +0000687 return sys.modules.get(modulesbyfile[file])
Thomas Wouters89f507f2006-12-13 04:49:30 +0000688 # Update the filename to module name cache and check yet again
689 # Copy sys.modules in order to cope with changes while iterating
Éric Araujoa74f8ef2011-11-29 16:58:53 +0100690 for modname, module in list(sys.modules.items()):
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000691 if ismodule(module) and hasattr(module, '__file__'):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000692 f = module.__file__
693 if f == _filesbymodname.get(modname, None):
694 # Have already mapped this module, so skip it
695 continue
696 _filesbymodname[modname] = f
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000697 f = getabsfile(module)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000698 # Always map to the name the module knows itself by
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000699 modulesbyfile[f] = modulesbyfile[
700 os.path.realpath(f)] = module.__name__
Raymond Hettinger54f02222002-06-01 14:18:47 +0000701 if file in modulesbyfile:
Ka-Ping Yeeb38bbbd2003-03-28 16:29:50 +0000702 return sys.modules.get(modulesbyfile[file])
Thomas Wouters89f507f2006-12-13 04:49:30 +0000703 # Check the main module
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000704 main = sys.modules['__main__']
Brett Cannon4a671fe2003-06-15 22:33:28 +0000705 if not hasattr(object, '__name__'):
706 return None
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000707 if hasattr(main, object.__name__):
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000708 mainobject = getattr(main, object.__name__)
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000709 if mainobject is object:
710 return main
Thomas Wouters89f507f2006-12-13 04:49:30 +0000711 # Check builtins
Georg Brandl1a3284e2007-12-02 09:40:06 +0000712 builtin = sys.modules['builtins']
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000713 if hasattr(builtin, object.__name__):
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000714 builtinobject = getattr(builtin, object.__name__)
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000715 if builtinobject is object:
716 return builtin
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000717
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000718def findsource(object):
719 """Return the entire source file and starting line number for an object.
720
721 The argument may be a module, class, method, function, traceback, frame,
722 or code object. The source code is returned as a list of all the lines
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200723 in the file and the line number indexes a line in that list. An OSError
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000724 is raised if the source code cannot be retrieved."""
Benjamin Peterson9620cc02011-06-11 15:53:11 -0500725
Yury Selivanovef1e7502014-12-08 16:05:34 -0500726 file = getsourcefile(object)
727 if file:
728 # Invalidate cache if needed.
729 linecache.checkcache(file)
730 else:
731 file = getfile(object)
732 # Allow filenames in form of "<something>" to pass through.
733 # `doctest` monkeypatches `linecache` module to enable
734 # inspection, so let `linecache.getlines` to be called.
735 if not (file.startswith('<') and file.endswith('>')):
736 raise OSError('source code not available')
Benjamin Peterson9620cc02011-06-11 15:53:11 -0500737
Thomas Wouters89f507f2006-12-13 04:49:30 +0000738 module = getmodule(object, file)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000739 if module:
740 lines = linecache.getlines(file, module.__dict__)
741 else:
742 lines = linecache.getlines(file)
Neil Schemenauerf06f8532002-03-23 23:51:04 +0000743 if not lines:
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200744 raise OSError('could not get source code')
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000745
746 if ismodule(object):
747 return lines, 0
748
749 if isclass(object):
750 name = object.__name__
Thomas Wouters89f507f2006-12-13 04:49:30 +0000751 pat = re.compile(r'^(\s*)class\s*' + name + r'\b')
752 # make some effort to find the best matching class definition:
753 # use the one with the least indentation, which is the one
754 # that's most probably not inside a function definition.
755 candidates = []
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000756 for i in range(len(lines)):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000757 match = pat.match(lines[i])
758 if match:
759 # if it's at toplevel, it's already the best one
760 if lines[i][0] == 'c':
761 return lines, i
762 # else add whitespace to candidate list
763 candidates.append((match.group(1), i))
764 if candidates:
765 # this will sort by whitespace, and by line number,
766 # less whitespace first
767 candidates.sort()
768 return lines, candidates[0][1]
Jeremy Hyltonab919022003-06-27 18:41:20 +0000769 else:
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200770 raise OSError('could not find class definition')
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000771
772 if ismethod(object):
Christian Heimesff737952007-11-27 10:40:20 +0000773 object = object.__func__
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000774 if isfunction(object):
Neal Norwitz221085d2007-02-25 20:55:47 +0000775 object = object.__code__
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000776 if istraceback(object):
777 object = object.tb_frame
778 if isframe(object):
779 object = object.f_code
780 if iscode(object):
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000781 if not hasattr(object, 'co_firstlineno'):
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200782 raise OSError('could not find function definition')
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000783 lnum = object.co_firstlineno - 1
Yury Selivanove4e811d2015-07-21 19:01:52 +0300784 pat = re.compile(r'^(\s*def\s)|(\s*async\s+def\s)|(.*(?<!\w)lambda(:|\s))|^(\s*@)')
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000785 while lnum > 0:
Ka-Ping Yeea6e59712001-03-10 09:31:55 +0000786 if pat.match(lines[lnum]): break
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000787 lnum = lnum - 1
788 return lines, lnum
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200789 raise OSError('could not find code object')
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000790
791def getcomments(object):
Jeremy Hyltonb4c17c82002-03-28 23:01:56 +0000792 """Get lines of comments immediately preceding an object's source code.
793
794 Returns None when source can't be found.
795 """
796 try:
797 lines, lnum = findsource(object)
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200798 except (OSError, TypeError):
Jeremy Hyltonb4c17c82002-03-28 23:01:56 +0000799 return None
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000800
801 if ismodule(object):
802 # Look for a comment block at the top of the file.
803 start = 0
Ka-Ping Yeeb910efe2001-04-12 13:17:17 +0000804 if lines and lines[0][:2] == '#!': start = 1
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000805 while start < len(lines) and lines[start].strip() in ('', '#'):
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000806 start = start + 1
Ka-Ping Yeeb910efe2001-04-12 13:17:17 +0000807 if start < len(lines) and lines[start][:1] == '#':
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000808 comments = []
809 end = start
810 while end < len(lines) and lines[end][:1] == '#':
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000811 comments.append(lines[end].expandtabs())
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000812 end = end + 1
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000813 return ''.join(comments)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000814
815 # Look for a preceding block of comments at the same indentation.
816 elif lnum > 0:
817 indent = indentsize(lines[lnum])
818 end = lnum - 1
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000819 if end >= 0 and lines[end].lstrip()[:1] == '#' and \
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000820 indentsize(lines[end]) == indent:
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000821 comments = [lines[end].expandtabs().lstrip()]
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000822 if end > 0:
823 end = end - 1
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000824 comment = lines[end].expandtabs().lstrip()
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000825 while comment[:1] == '#' and indentsize(lines[end]) == indent:
826 comments[:0] = [comment]
827 end = end - 1
828 if end < 0: break
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000829 comment = lines[end].expandtabs().lstrip()
830 while comments and comments[0].strip() == '#':
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000831 comments[:1] = []
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000832 while comments and comments[-1].strip() == '#':
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000833 comments[-1:] = []
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000834 return ''.join(comments)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000835
Tim Peters4efb6e92001-06-29 23:51:08 +0000836class EndOfBlock(Exception): pass
837
838class BlockFinder:
839 """Provide a tokeneater() method to detect the end of a code block."""
840 def __init__(self):
841 self.indent = 0
Johannes Gijsbersa5855d52005-03-12 16:37:11 +0000842 self.islambda = False
Johannes Gijsbers1542f342004-12-12 16:46:28 +0000843 self.started = False
844 self.passline = False
Meador Inge5b718d72015-07-23 22:49:37 -0500845 self.indecorator = False
846 self.decoratorhasargs = False
Armin Rigodd5c0232005-09-25 11:45:45 +0000847 self.last = 1
Tim Peters4efb6e92001-06-29 23:51:08 +0000848
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000849 def tokeneater(self, type, token, srowcol, erowcol, line):
Meador Inge5b718d72015-07-23 22:49:37 -0500850 if not self.started and not self.indecorator:
851 # skip any decorators
852 if token == "@":
853 self.indecorator = True
Armin Rigodd5c0232005-09-25 11:45:45 +0000854 # look for the first "def", "class" or "lambda"
Meador Inge5b718d72015-07-23 22:49:37 -0500855 elif token in ("def", "class", "lambda"):
Johannes Gijsbersa5855d52005-03-12 16:37:11 +0000856 if token == "lambda":
857 self.islambda = True
Johannes Gijsbers1542f342004-12-12 16:46:28 +0000858 self.started = True
Armin Rigodd5c0232005-09-25 11:45:45 +0000859 self.passline = True # skip to the end of the line
Meador Inge5b718d72015-07-23 22:49:37 -0500860 elif token == "(":
861 if self.indecorator:
862 self.decoratorhasargs = True
863 elif token == ")":
864 if self.indecorator:
865 self.indecorator = False
866 self.decoratorhasargs = False
Tim Peters4efb6e92001-06-29 23:51:08 +0000867 elif type == tokenize.NEWLINE:
Armin Rigodd5c0232005-09-25 11:45:45 +0000868 self.passline = False # stop skipping when a NEWLINE is seen
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000869 self.last = srowcol[0]
Armin Rigodd5c0232005-09-25 11:45:45 +0000870 if self.islambda: # lambdas always end at the first NEWLINE
871 raise EndOfBlock
Meador Inge5b718d72015-07-23 22:49:37 -0500872 # hitting a NEWLINE when in a decorator without args
873 # ends the decorator
874 if self.indecorator and not self.decoratorhasargs:
875 self.indecorator = False
Johannes Gijsbers1542f342004-12-12 16:46:28 +0000876 elif self.passline:
877 pass
Tim Peters4efb6e92001-06-29 23:51:08 +0000878 elif type == tokenize.INDENT:
879 self.indent = self.indent + 1
Johannes Gijsbers1542f342004-12-12 16:46:28 +0000880 self.passline = True
Tim Peters4efb6e92001-06-29 23:51:08 +0000881 elif type == tokenize.DEDENT:
882 self.indent = self.indent - 1
Armin Rigodd5c0232005-09-25 11:45:45 +0000883 # the end of matching indent/dedent pairs end a block
884 # (note that this only works for "def"/"class" blocks,
885 # not e.g. for "if: else:" or "try: finally:" blocks)
886 if self.indent <= 0:
887 raise EndOfBlock
888 elif self.indent == 0 and type not in (tokenize.COMMENT, tokenize.NL):
889 # any other token on the same indentation level end the previous
890 # block as well, except the pseudo-tokens COMMENT and NL.
891 raise EndOfBlock
Tim Peters4efb6e92001-06-29 23:51:08 +0000892
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000893def getblock(lines):
894 """Extract the block of code at the top of the given list of lines."""
Armin Rigodd5c0232005-09-25 11:45:45 +0000895 blockfinder = BlockFinder()
Tim Peters4efb6e92001-06-29 23:51:08 +0000896 try:
Trent Nelson428de652008-03-18 22:41:35 +0000897 tokens = tokenize.generate_tokens(iter(lines).__next__)
898 for _token in tokens:
899 blockfinder.tokeneater(*_token)
Armin Rigodd5c0232005-09-25 11:45:45 +0000900 except (EndOfBlock, IndentationError):
901 pass
902 return lines[:blockfinder.last]
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000903
904def getsourcelines(object):
905 """Return a list of source lines and starting line number for an object.
906
907 The argument may be a module, class, method, function, traceback, frame,
908 or code object. The source code is returned as a list of the lines
909 corresponding to the object and the line number indicates where in the
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200910 original source file the first line of code was found. An OSError is
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000911 raised if the source code cannot be retrieved."""
Yury Selivanov081bbf62014-09-26 17:34:54 -0400912 object = unwrap(object)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000913 lines, lnum = findsource(object)
914
Meador Inge5b718d72015-07-23 22:49:37 -0500915 if ismodule(object):
916 return lines, 0
917 else:
918 return getblock(lines[lnum:]), lnum + 1
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000919
920def getsource(object):
921 """Return the text of the source code for an object.
922
923 The argument may be a module, class, method, function, traceback, frame,
924 or code object. The source code is returned as a single string. An
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200925 OSError is raised if the source code cannot be retrieved."""
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000926 lines, lnum = getsourcelines(object)
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000927 return ''.join(lines)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000928
929# --------------------------------------------------- class tree extraction
930def walktree(classes, children, parent):
931 """Recursive helper function for getclasstree()."""
932 results = []
Raymond Hettingera1a992c2005-03-11 06:46:45 +0000933 classes.sort(key=attrgetter('__module__', '__name__'))
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000934 for c in classes:
935 results.append((c, c.__bases__))
Raymond Hettinger54f02222002-06-01 14:18:47 +0000936 if c in children:
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000937 results.append(walktree(children[c], children, c))
938 return results
939
Georg Brandl5ce83a02009-06-01 17:23:51 +0000940def getclasstree(classes, unique=False):
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000941 """Arrange the given list of classes into a hierarchy of nested lists.
942
943 Where a nested list appears, it contains classes derived from the class
944 whose entry immediately precedes the list. Each entry is a 2-tuple
945 containing a class and a tuple of its base classes. If the 'unique'
946 argument is true, exactly one entry appears in the returned structure
947 for each class in the given list. Otherwise, classes using multiple
948 inheritance and their descendants will appear multiple times."""
949 children = {}
950 roots = []
951 for c in classes:
952 if c.__bases__:
953 for parent in c.__bases__:
Raymond Hettinger54f02222002-06-01 14:18:47 +0000954 if not parent in children:
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000955 children[parent] = []
Serhiy Storchaka362c1b52013-09-05 17:14:32 +0300956 if c not in children[parent]:
957 children[parent].append(c)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000958 if unique and parent in classes: break
959 elif c not in roots:
960 roots.append(c)
Raymond Hettingere0d49722002-06-02 18:55:56 +0000961 for parent in children:
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000962 if parent not in classes:
963 roots.append(parent)
964 return walktree(roots, children, None)
965
966# ------------------------------------------------ argument list extraction
Christian Heimes25bb7832008-01-11 16:17:00 +0000967Arguments = namedtuple('Arguments', 'args, varargs, varkw')
968
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000969def getargs(co):
970 """Get information about the arguments accepted by a code object.
971
Guido van Rossum2e65f892007-02-28 22:03:49 +0000972 Three things are returned: (args, varargs, varkw), where
Georg Brandlc1c4bf82010-10-15 16:07:41 +0000973 'args' is the list of argument names. Keyword-only arguments are
974 appended. 'varargs' and 'varkw' are the names of the * and **
975 arguments or None."""
Guido van Rossum2e65f892007-02-28 22:03:49 +0000976 args, varargs, kwonlyargs, varkw = _getfullargs(co)
Christian Heimes25bb7832008-01-11 16:17:00 +0000977 return Arguments(args + kwonlyargs, varargs, varkw)
Guido van Rossum2e65f892007-02-28 22:03:49 +0000978
979def _getfullargs(co):
980 """Get information about the arguments accepted by a code object.
981
982 Four things are returned: (args, varargs, kwonlyargs, varkw), where
Georg Brandlc1c4bf82010-10-15 16:07:41 +0000983 'args' and 'kwonlyargs' are lists of argument names, and 'varargs'
984 and 'varkw' are the names of the * and ** arguments or None."""
Jeremy Hylton64967882003-06-27 18:14:39 +0000985
986 if not iscode(co):
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +0000987 raise TypeError('{!r} is not a code object'.format(co))
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000988
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000989 nargs = co.co_argcount
990 names = co.co_varnames
Guido van Rossum2e65f892007-02-28 22:03:49 +0000991 nkwargs = co.co_kwonlyargcount
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000992 args = list(names[:nargs])
Guido van Rossum2e65f892007-02-28 22:03:49 +0000993 kwonlyargs = list(names[nargs:nargs+nkwargs])
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000994 step = 0
995
Guido van Rossum2e65f892007-02-28 22:03:49 +0000996 nargs += nkwargs
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000997 varargs = None
998 if co.co_flags & CO_VARARGS:
999 varargs = co.co_varnames[nargs]
1000 nargs = nargs + 1
1001 varkw = None
1002 if co.co_flags & CO_VARKEYWORDS:
1003 varkw = co.co_varnames[nargs]
Guido van Rossum2e65f892007-02-28 22:03:49 +00001004 return args, varargs, kwonlyargs, varkw
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001005
Yury Selivanov37dc2b22016-01-11 15:15:01 -05001006
1007ArgSpec = namedtuple('ArgSpec', 'args varargs keywords defaults')
1008
1009def getargspec(func):
1010 """Get the names and default values of a function's arguments.
1011
1012 A tuple of four things is returned: (args, varargs, keywords, defaults).
1013 'args' is a list of the argument names, including keyword-only argument names.
1014 'varargs' and 'keywords' are the names of the * and ** arguments or None.
1015 'defaults' is an n-tuple of the default values of the last n arguments.
1016
1017 Use the getfullargspec() API for Python 3 code, as annotations
1018 and keyword arguments are supported. getargspec() will raise ValueError
1019 if the func has either annotations or keyword arguments.
1020 """
1021 warnings.warn("inspect.getargspec() is deprecated, "
1022 "use inspect.signature() instead", DeprecationWarning,
1023 stacklevel=2)
1024 args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults, ann = \
1025 getfullargspec(func)
1026 if kwonlyargs or ann:
1027 raise ValueError("Function has keyword-only arguments or annotations"
1028 ", use getfullargspec() API which can support them")
1029 return ArgSpec(args, varargs, varkw, defaults)
1030
Christian Heimes25bb7832008-01-11 16:17:00 +00001031FullArgSpec = namedtuple('FullArgSpec',
Benjamin Peterson3d4ca742008-11-12 21:39:01 +00001032 'args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults, annotations')
Guido van Rossum2e65f892007-02-28 22:03:49 +00001033
1034def getfullargspec(func):
Yury Selivanovd82eddc2014-01-29 11:24:39 -05001035 """Get the names and default values of a callable object's arguments.
Guido van Rossum2e65f892007-02-28 22:03:49 +00001036
Brett Cannon504d8852007-09-07 02:12:14 +00001037 A tuple of seven things is returned:
1038 (args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults annotations).
Georg Brandlc1c4bf82010-10-15 16:07:41 +00001039 'args' is a list of the argument names.
Guido van Rossum2e65f892007-02-28 22:03:49 +00001040 'varargs' and 'varkw' are the names of the * and ** arguments or None.
1041 'defaults' is an n-tuple of the default values of the last n arguments.
1042 'kwonlyargs' is a list of keyword-only argument names.
1043 'kwonlydefaults' is a dictionary mapping names from kwonlyargs to defaults.
1044 'annotations' is a dictionary mapping argument names to annotations.
Guido van Rossuma8add0e2007-05-14 22:03:55 +00001045
Yury Selivanov3cfec2e2015-05-22 11:38:38 -04001046 This function is deprecated, use inspect.signature() instead.
Jeremy Hylton64967882003-06-27 18:14:39 +00001047 """
1048
Yury Selivanov57d240e2014-02-19 16:27:23 -05001049 try:
1050 # Re: `skip_bound_arg=False`
1051 #
Yury Selivanovd82eddc2014-01-29 11:24:39 -05001052 # There is a notable difference in behaviour between getfullargspec
1053 # and Signature: the former always returns 'self' parameter for bound
1054 # methods, whereas the Signature always shows the actual calling
1055 # signature of the passed object.
1056 #
1057 # To simulate this behaviour, we "unbind" bound methods, to trick
1058 # inspect.signature to always return their first parameter ("self",
1059 # usually)
Yury Selivanovd82eddc2014-01-29 11:24:39 -05001060
Yury Selivanov57d240e2014-02-19 16:27:23 -05001061 # Re: `follow_wrapper_chains=False`
1062 #
1063 # getfullargspec() historically ignored __wrapped__ attributes,
1064 # so we ensure that remains the case in 3.3+
Yury Selivanovd82eddc2014-01-29 11:24:39 -05001065
Yury Selivanov5a23bd02014-03-29 13:47:11 -04001066 sig = _signature_from_callable(func,
1067 follow_wrapper_chains=False,
1068 skip_bound_arg=False,
1069 sigcls=Signature)
Yury Selivanovd82eddc2014-01-29 11:24:39 -05001070 except Exception as ex:
1071 # Most of the times 'signature' will raise ValueError.
1072 # But, it can also raise AttributeError, and, maybe something
1073 # else. So to be fully backwards compatible, we catch all
1074 # possible exceptions here, and reraise a TypeError.
1075 raise TypeError('unsupported callable') from ex
1076
1077 args = []
1078 varargs = None
1079 varkw = None
1080 kwonlyargs = []
1081 defaults = ()
1082 annotations = {}
1083 defaults = ()
1084 kwdefaults = {}
1085
1086 if sig.return_annotation is not sig.empty:
1087 annotations['return'] = sig.return_annotation
1088
1089 for param in sig.parameters.values():
1090 kind = param.kind
1091 name = param.name
1092
1093 if kind is _POSITIONAL_ONLY:
1094 args.append(name)
1095 elif kind is _POSITIONAL_OR_KEYWORD:
1096 args.append(name)
1097 if param.default is not param.empty:
1098 defaults += (param.default,)
1099 elif kind is _VAR_POSITIONAL:
1100 varargs = name
1101 elif kind is _KEYWORD_ONLY:
1102 kwonlyargs.append(name)
1103 if param.default is not param.empty:
1104 kwdefaults[name] = param.default
1105 elif kind is _VAR_KEYWORD:
1106 varkw = name
1107
1108 if param.annotation is not param.empty:
1109 annotations[name] = param.annotation
1110
1111 if not kwdefaults:
1112 # compatibility with 'func.__kwdefaults__'
1113 kwdefaults = None
1114
1115 if not defaults:
1116 # compatibility with 'func.__defaults__'
1117 defaults = None
1118
Yury Selivanovd82eddc2014-01-29 11:24:39 -05001119 return FullArgSpec(args, varargs, varkw, defaults,
1120 kwonlyargs, kwdefaults, annotations)
1121
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001122
Christian Heimes25bb7832008-01-11 16:17:00 +00001123ArgInfo = namedtuple('ArgInfo', 'args varargs keywords locals')
1124
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001125def getargvalues(frame):
1126 """Get information about arguments passed into a particular frame.
1127
1128 A tuple of four things is returned: (args, varargs, varkw, locals).
Georg Brandlc1c4bf82010-10-15 16:07:41 +00001129 'args' is a list of the argument names.
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001130 'varargs' and 'varkw' are the names of the * and ** arguments or None.
1131 'locals' is the locals dictionary of the given frame."""
1132 args, varargs, varkw = getargs(frame.f_code)
Benjamin Peterson1a6e0d02008-10-25 15:49:17 +00001133 return ArgInfo(args, varargs, varkw, frame.f_locals)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001134
Guido van Rossum2e65f892007-02-28 22:03:49 +00001135def formatannotation(annotation, base_module=None):
1136 if isinstance(annotation, type):
Georg Brandl1a3284e2007-12-02 09:40:06 +00001137 if annotation.__module__ in ('builtins', base_module):
Serhiy Storchaka521e5862014-07-22 15:00:37 +03001138 return annotation.__qualname__
1139 return annotation.__module__+'.'+annotation.__qualname__
Guido van Rossum2e65f892007-02-28 22:03:49 +00001140 return repr(annotation)
Guido van Rossuma8add0e2007-05-14 22:03:55 +00001141
Guido van Rossum2e65f892007-02-28 22:03:49 +00001142def formatannotationrelativeto(object):
Guido van Rossuma8add0e2007-05-14 22:03:55 +00001143 module = getattr(object, '__module__', None)
1144 def _formatannotation(annotation):
1145 return formatannotation(annotation, module)
1146 return _formatannotation
Guido van Rossum2e65f892007-02-28 22:03:49 +00001147
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001148def formatargspec(args, varargs=None, varkw=None, defaults=None,
Guido van Rossum2e65f892007-02-28 22:03:49 +00001149 kwonlyargs=(), kwonlydefaults={}, annotations={},
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001150 formatarg=str,
1151 formatvarargs=lambda name: '*' + name,
1152 formatvarkw=lambda name: '**' + name,
1153 formatvalue=lambda value: '=' + repr(value),
Guido van Rossum2e65f892007-02-28 22:03:49 +00001154 formatreturns=lambda text: ' -> ' + text,
Georg Brandlc1c4bf82010-10-15 16:07:41 +00001155 formatannotation=formatannotation):
Berker Peksagfa3922c2015-07-31 04:11:29 +03001156 """Format an argument spec from the values returned by getfullargspec.
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001157
Guido van Rossum2e65f892007-02-28 22:03:49 +00001158 The first seven arguments are (args, varargs, varkw, defaults,
1159 kwonlyargs, kwonlydefaults, annotations). The other five arguments
1160 are the corresponding optional formatting functions that are called to
1161 turn names and values into strings. The last argument is an optional
1162 function to format the sequence of arguments."""
1163 def formatargandannotation(arg):
1164 result = formatarg(arg)
1165 if arg in annotations:
1166 result += ': ' + formatannotation(annotations[arg])
1167 return result
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001168 specs = []
1169 if defaults:
1170 firstdefault = len(args) - len(defaults)
Benjamin Petersonb58dda72009-01-18 22:27:04 +00001171 for i, arg in enumerate(args):
Georg Brandlc1c4bf82010-10-15 16:07:41 +00001172 spec = formatargandannotation(arg)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001173 if defaults and i >= firstdefault:
1174 spec = spec + formatvalue(defaults[i - firstdefault])
1175 specs.append(spec)
Raymond Hettinger936654b2002-06-01 03:06:31 +00001176 if varargs is not None:
Guido van Rossum2e65f892007-02-28 22:03:49 +00001177 specs.append(formatvarargs(formatargandannotation(varargs)))
1178 else:
1179 if kwonlyargs:
1180 specs.append('*')
1181 if kwonlyargs:
1182 for kwonlyarg in kwonlyargs:
1183 spec = formatargandannotation(kwonlyarg)
Benjamin Peterson9953a8d2009-01-17 04:15:01 +00001184 if kwonlydefaults and kwonlyarg in kwonlydefaults:
Guido van Rossum2e65f892007-02-28 22:03:49 +00001185 spec += formatvalue(kwonlydefaults[kwonlyarg])
1186 specs.append(spec)
Raymond Hettinger936654b2002-06-01 03:06:31 +00001187 if varkw is not None:
Guido van Rossum2e65f892007-02-28 22:03:49 +00001188 specs.append(formatvarkw(formatargandannotation(varkw)))
Neal Norwitz9d72bb42007-04-17 08:48:32 +00001189 result = '(' + ', '.join(specs) + ')'
Guido van Rossum2e65f892007-02-28 22:03:49 +00001190 if 'return' in annotations:
1191 result += formatreturns(formatannotation(annotations['return']))
1192 return result
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001193
1194def formatargvalues(args, varargs, varkw, locals,
1195 formatarg=str,
1196 formatvarargs=lambda name: '*' + name,
1197 formatvarkw=lambda name: '**' + name,
Georg Brandlc1c4bf82010-10-15 16:07:41 +00001198 formatvalue=lambda value: '=' + repr(value)):
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001199 """Format an argument spec from the 4 values returned by getargvalues.
1200
1201 The first four arguments are (args, varargs, varkw, locals). The
1202 next four arguments are the corresponding optional formatting functions
1203 that are called to turn names and values into strings. The ninth
1204 argument is an optional function to format the sequence of arguments."""
1205 def convert(name, locals=locals,
1206 formatarg=formatarg, formatvalue=formatvalue):
1207 return formatarg(name) + formatvalue(locals[name])
1208 specs = []
1209 for i in range(len(args)):
Georg Brandlc1c4bf82010-10-15 16:07:41 +00001210 specs.append(convert(args[i]))
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001211 if varargs:
1212 specs.append(formatvarargs(varargs) + formatvalue(locals[varargs]))
1213 if varkw:
1214 specs.append(formatvarkw(varkw) + formatvalue(locals[varkw]))
Neal Norwitz9d72bb42007-04-17 08:48:32 +00001215 return '(' + ', '.join(specs) + ')'
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001216
Benjamin Petersone109c702011-06-24 09:37:26 -05001217def _missing_arguments(f_name, argnames, pos, values):
1218 names = [repr(name) for name in argnames if name not in values]
1219 missing = len(names)
1220 if missing == 1:
1221 s = names[0]
1222 elif missing == 2:
1223 s = "{} and {}".format(*names)
1224 else:
Yury Selivanovdccfa132014-03-27 18:42:52 -04001225 tail = ", {} and {}".format(*names[-2:])
Benjamin Petersone109c702011-06-24 09:37:26 -05001226 del names[-2:]
1227 s = ", ".join(names) + tail
1228 raise TypeError("%s() missing %i required %s argument%s: %s" %
1229 (f_name, missing,
1230 "positional" if pos else "keyword-only",
1231 "" if missing == 1 else "s", s))
1232
1233def _too_many(f_name, args, kwonly, varargs, defcount, given, values):
Benjamin Petersonb204a422011-06-05 22:04:07 -05001234 atleast = len(args) - defcount
Benjamin Petersonb204a422011-06-05 22:04:07 -05001235 kwonly_given = len([arg for arg in kwonly if arg in values])
1236 if varargs:
1237 plural = atleast != 1
1238 sig = "at least %d" % (atleast,)
1239 elif defcount:
1240 plural = True
1241 sig = "from %d to %d" % (atleast, len(args))
1242 else:
1243 plural = len(args) != 1
1244 sig = str(len(args))
1245 kwonly_sig = ""
1246 if kwonly_given:
1247 msg = " positional argument%s (and %d keyword-only argument%s)"
1248 kwonly_sig = (msg % ("s" if given != 1 else "", kwonly_given,
1249 "s" if kwonly_given != 1 else ""))
1250 raise TypeError("%s() takes %s positional argument%s but %d%s %s given" %
1251 (f_name, sig, "s" if plural else "", given, kwonly_sig,
1252 "was" if given == 1 and not kwonly_given else "were"))
1253
Benjamin Peterson3e6ab172014-01-02 12:24:08 -06001254def getcallargs(*func_and_positional, **named):
Benjamin Peterson25cd7eb2010-03-30 18:42:32 +00001255 """Get the mapping of arguments to values.
1256
1257 A dict is returned, with keys the function argument names (including the
1258 names of the * and ** arguments, if any), and values the respective bound
1259 values from 'positional' and 'named'."""
Benjamin Peterson3e6ab172014-01-02 12:24:08 -06001260 func = func_and_positional[0]
1261 positional = func_and_positional[1:]
Benjamin Peterson25cd7eb2010-03-30 18:42:32 +00001262 spec = getfullargspec(func)
1263 args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults, ann = spec
1264 f_name = func.__name__
1265 arg2value = {}
1266
Benjamin Petersonb204a422011-06-05 22:04:07 -05001267
Benjamin Peterson25cd7eb2010-03-30 18:42:32 +00001268 if ismethod(func) and func.__self__ is not None:
1269 # implicit 'self' (or 'cls' for classmethods) argument
1270 positional = (func.__self__,) + positional
1271 num_pos = len(positional)
Benjamin Peterson25cd7eb2010-03-30 18:42:32 +00001272 num_args = len(args)
1273 num_defaults = len(defaults) if defaults else 0
Benjamin Peterson25cd7eb2010-03-30 18:42:32 +00001274
Benjamin Petersonb204a422011-06-05 22:04:07 -05001275 n = min(num_pos, num_args)
1276 for i in range(n):
1277 arg2value[args[i]] = positional[i]
1278 if varargs:
1279 arg2value[varargs] = tuple(positional[n:])
1280 possible_kwargs = set(args + kwonlyargs)
Benjamin Peterson25cd7eb2010-03-30 18:42:32 +00001281 if varkw:
Benjamin Petersonb204a422011-06-05 22:04:07 -05001282 arg2value[varkw] = {}
1283 for kw, value in named.items():
1284 if kw not in possible_kwargs:
1285 if not varkw:
1286 raise TypeError("%s() got an unexpected keyword argument %r" %
1287 (f_name, kw))
1288 arg2value[varkw][kw] = value
1289 continue
1290 if kw in arg2value:
1291 raise TypeError("%s() got multiple values for argument %r" %
1292 (f_name, kw))
1293 arg2value[kw] = value
1294 if num_pos > num_args and not varargs:
Benjamin Petersone109c702011-06-24 09:37:26 -05001295 _too_many(f_name, args, kwonlyargs, varargs, num_defaults,
1296 num_pos, arg2value)
Benjamin Petersonb204a422011-06-05 22:04:07 -05001297 if num_pos < num_args:
Benjamin Petersone109c702011-06-24 09:37:26 -05001298 req = args[:num_args - num_defaults]
1299 for arg in req:
Benjamin Petersonb204a422011-06-05 22:04:07 -05001300 if arg not in arg2value:
Benjamin Petersone109c702011-06-24 09:37:26 -05001301 _missing_arguments(f_name, req, True, arg2value)
Benjamin Petersonb204a422011-06-05 22:04:07 -05001302 for i, arg in enumerate(args[num_args - num_defaults:]):
1303 if arg not in arg2value:
1304 arg2value[arg] = defaults[i]
Benjamin Petersone109c702011-06-24 09:37:26 -05001305 missing = 0
Benjamin Petersonb204a422011-06-05 22:04:07 -05001306 for kwarg in kwonlyargs:
1307 if kwarg not in arg2value:
Yury Selivanov875df202014-03-27 18:23:03 -04001308 if kwonlydefaults and kwarg in kwonlydefaults:
Benjamin Petersone109c702011-06-24 09:37:26 -05001309 arg2value[kwarg] = kwonlydefaults[kwarg]
1310 else:
1311 missing += 1
1312 if missing:
1313 _missing_arguments(f_name, kwonlyargs, False, arg2value)
Benjamin Peterson25cd7eb2010-03-30 18:42:32 +00001314 return arg2value
1315
Nick Coghlan2f92e542012-06-23 19:39:55 +10001316ClosureVars = namedtuple('ClosureVars', 'nonlocals globals builtins unbound')
1317
1318def getclosurevars(func):
1319 """
1320 Get the mapping of free variables to their current values.
1321
Meador Inge8fda3592012-07-19 21:33:21 -05001322 Returns a named tuple of dicts mapping the current nonlocal, global
Nick Coghlan2f92e542012-06-23 19:39:55 +10001323 and builtin references as seen by the body of the function. A final
1324 set of unbound names that could not be resolved is also provided.
1325 """
1326
1327 if ismethod(func):
1328 func = func.__func__
1329
1330 if not isfunction(func):
1331 raise TypeError("'{!r}' is not a Python function".format(func))
1332
1333 code = func.__code__
1334 # Nonlocal references are named in co_freevars and resolved
1335 # by looking them up in __closure__ by positional index
1336 if func.__closure__ is None:
1337 nonlocal_vars = {}
1338 else:
1339 nonlocal_vars = {
1340 var : cell.cell_contents
1341 for var, cell in zip(code.co_freevars, func.__closure__)
1342 }
1343
1344 # Global and builtin references are named in co_names and resolved
1345 # by looking them up in __globals__ or __builtins__
1346 global_ns = func.__globals__
1347 builtin_ns = global_ns.get("__builtins__", builtins.__dict__)
1348 if ismodule(builtin_ns):
1349 builtin_ns = builtin_ns.__dict__
1350 global_vars = {}
1351 builtin_vars = {}
1352 unbound_names = set()
1353 for name in code.co_names:
1354 if name in ("None", "True", "False"):
1355 # Because these used to be builtins instead of keywords, they
1356 # may still show up as name references. We ignore them.
1357 continue
1358 try:
1359 global_vars[name] = global_ns[name]
1360 except KeyError:
1361 try:
1362 builtin_vars[name] = builtin_ns[name]
1363 except KeyError:
1364 unbound_names.add(name)
1365
1366 return ClosureVars(nonlocal_vars, global_vars,
1367 builtin_vars, unbound_names)
1368
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001369# -------------------------------------------------- stack frame extraction
Christian Heimes25bb7832008-01-11 16:17:00 +00001370
1371Traceback = namedtuple('Traceback', 'filename lineno function code_context index')
1372
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001373def getframeinfo(frame, context=1):
1374 """Get information about a frame or traceback object.
1375
1376 A tuple of five things is returned: the filename, the line number of
1377 the current line, the function name, a list of lines of context from
1378 the source code, and the index of the current line within that list.
1379 The optional second argument specifies the number of lines of context
1380 to return, which are centered around the current line."""
1381 if istraceback(frame):
Andrew M. Kuchlingba8b6bc2004-06-05 14:11:59 +00001382 lineno = frame.tb_lineno
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001383 frame = frame.tb_frame
Andrew M. Kuchlingba8b6bc2004-06-05 14:11:59 +00001384 else:
1385 lineno = frame.f_lineno
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001386 if not isframe(frame):
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00001387 raise TypeError('{!r} is not a frame or traceback object'.format(frame))
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001388
Neil Schemenauerf06f8532002-03-23 23:51:04 +00001389 filename = getsourcefile(frame) or getfile(frame)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001390 if context > 0:
Guido van Rossum54e54c62001-09-04 19:14:14 +00001391 start = lineno - 1 - context//2
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001392 try:
1393 lines, lnum = findsource(frame)
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02001394 except OSError:
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +00001395 lines = index = None
1396 else:
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001397 start = max(start, 1)
Raymond Hettingera0501712004-06-15 11:22:53 +00001398 start = max(0, min(start, len(lines) - context))
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001399 lines = lines[start:start+context]
Ka-Ping Yee59ade082001-03-01 03:55:35 +00001400 index = lineno - 1 - start
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001401 else:
1402 lines = index = None
1403
Christian Heimes25bb7832008-01-11 16:17:00 +00001404 return Traceback(filename, lineno, frame.f_code.co_name, lines, index)
Ka-Ping Yee59ade082001-03-01 03:55:35 +00001405
1406def getlineno(frame):
1407 """Get the line number from a frame object, allowing for optimization."""
Michael W. Hudsondd32a912002-08-15 14:59:02 +00001408 # FrameType.f_lineno is now a descriptor that grovels co_lnotab
1409 return frame.f_lineno
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001410
Antoine Pitroucdcafb72014-08-24 10:50:28 -04001411FrameInfo = namedtuple('FrameInfo', ('frame',) + Traceback._fields)
1412
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001413def getouterframes(frame, context=1):
1414 """Get a list of records for a frame and all higher (calling) frames.
1415
1416 Each record contains a frame object, filename, line number, function
1417 name, a list of lines of context, and index within the context."""
1418 framelist = []
1419 while frame:
Antoine Pitroucdcafb72014-08-24 10:50:28 -04001420 frameinfo = (frame,) + getframeinfo(frame, context)
1421 framelist.append(FrameInfo(*frameinfo))
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001422 frame = frame.f_back
1423 return framelist
1424
1425def getinnerframes(tb, context=1):
1426 """Get a list of records for a traceback's frame and all lower frames.
1427
1428 Each record contains a frame object, filename, line number, function
1429 name, a list of lines of context, and index within the context."""
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001430 framelist = []
1431 while tb:
Antoine Pitroucdcafb72014-08-24 10:50:28 -04001432 frameinfo = (tb.tb_frame,) + getframeinfo(tb, context)
1433 framelist.append(FrameInfo(*frameinfo))
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001434 tb = tb.tb_next
1435 return framelist
1436
Benjamin Peterson42ac4752010-08-09 13:05:35 +00001437def currentframe():
Benjamin Petersona3a3fc62010-08-09 15:49:56 +00001438 """Return the frame of the caller or None if this is not possible."""
Benjamin Peterson42ac4752010-08-09 13:05:35 +00001439 return sys._getframe(1) if hasattr(sys, "_getframe") else None
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001440
1441def stack(context=1):
1442 """Return a list of records for the stack above the caller's frame."""
Jeremy Hyltonab919022003-06-27 18:41:20 +00001443 return getouterframes(sys._getframe(1), context)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001444
1445def trace(context=1):
Tim Peters85ba6732001-02-28 08:26:44 +00001446 """Return a list of records for the stack below the current exception."""
Fred Draked451ec12002-04-26 02:29:55 +00001447 return getinnerframes(sys.exc_info()[2], context)
Michael Foord95fc51d2010-11-20 15:07:30 +00001448
1449
1450# ------------------------------------------------ static version of getattr
1451
1452_sentinel = object()
1453
Michael Foorde5162652010-11-20 16:40:44 +00001454def _static_getmro(klass):
1455 return type.__dict__['__mro__'].__get__(klass)
1456
Michael Foord95fc51d2010-11-20 15:07:30 +00001457def _check_instance(obj, attr):
1458 instance_dict = {}
1459 try:
1460 instance_dict = object.__getattribute__(obj, "__dict__")
1461 except AttributeError:
1462 pass
Michael Foorddcebe0f2011-03-15 19:20:44 -04001463 return dict.get(instance_dict, attr, _sentinel)
Michael Foord95fc51d2010-11-20 15:07:30 +00001464
1465
1466def _check_class(klass, attr):
Michael Foorde5162652010-11-20 16:40:44 +00001467 for entry in _static_getmro(klass):
Michael Foorda51623b2011-12-18 22:01:40 +00001468 if _shadowed_dict(type(entry)) is _sentinel:
Michael Foorddcebe0f2011-03-15 19:20:44 -04001469 try:
1470 return entry.__dict__[attr]
1471 except KeyError:
1472 pass
Michael Foord95fc51d2010-11-20 15:07:30 +00001473 return _sentinel
1474
Michael Foord35184ed2010-11-20 16:58:30 +00001475def _is_type(obj):
1476 try:
1477 _static_getmro(obj)
1478 except TypeError:
1479 return False
1480 return True
1481
Michael Foorddcebe0f2011-03-15 19:20:44 -04001482def _shadowed_dict(klass):
1483 dict_attr = type.__dict__["__dict__"]
1484 for entry in _static_getmro(klass):
1485 try:
1486 class_dict = dict_attr.__get__(entry)["__dict__"]
1487 except KeyError:
1488 pass
1489 else:
1490 if not (type(class_dict) is types.GetSetDescriptorType and
1491 class_dict.__name__ == "__dict__" and
1492 class_dict.__objclass__ is entry):
Michael Foorda51623b2011-12-18 22:01:40 +00001493 return class_dict
1494 return _sentinel
Michael Foord95fc51d2010-11-20 15:07:30 +00001495
1496def getattr_static(obj, attr, default=_sentinel):
1497 """Retrieve attributes without triggering dynamic lookup via the
1498 descriptor protocol, __getattr__ or __getattribute__.
1499
1500 Note: this function may not be able to retrieve all attributes
1501 that getattr can fetch (like dynamically created attributes)
1502 and may find attributes that getattr can't (like descriptors
1503 that raise AttributeError). It can also return descriptor objects
1504 instead of instance members in some cases. See the
1505 documentation for details.
1506 """
1507 instance_result = _sentinel
Michael Foord35184ed2010-11-20 16:58:30 +00001508 if not _is_type(obj):
Michael Foordcc7ebb82010-11-20 16:20:16 +00001509 klass = type(obj)
Michael Foorda51623b2011-12-18 22:01:40 +00001510 dict_attr = _shadowed_dict(klass)
1511 if (dict_attr is _sentinel or
1512 type(dict_attr) is types.MemberDescriptorType):
Michael Foorddcebe0f2011-03-15 19:20:44 -04001513 instance_result = _check_instance(obj, attr)
Michael Foord95fc51d2010-11-20 15:07:30 +00001514 else:
1515 klass = obj
1516
1517 klass_result = _check_class(klass, attr)
1518
1519 if instance_result is not _sentinel and klass_result is not _sentinel:
1520 if (_check_class(type(klass_result), '__get__') is not _sentinel and
1521 _check_class(type(klass_result), '__set__') is not _sentinel):
1522 return klass_result
1523
1524 if instance_result is not _sentinel:
1525 return instance_result
1526 if klass_result is not _sentinel:
1527 return klass_result
1528
1529 if obj is klass:
1530 # for types we check the metaclass too
Michael Foorde5162652010-11-20 16:40:44 +00001531 for entry in _static_getmro(type(klass)):
Michael Foord3ba95f82011-12-22 01:13:37 +00001532 if _shadowed_dict(type(entry)) is _sentinel:
1533 try:
1534 return entry.__dict__[attr]
1535 except KeyError:
1536 pass
Michael Foord95fc51d2010-11-20 15:07:30 +00001537 if default is not _sentinel:
1538 return default
1539 raise AttributeError(attr)
Nick Coghlane0f04652010-11-21 03:44:04 +00001540
1541
Nick Coghlan04e2e3f2012-06-23 19:52:05 +10001542# ------------------------------------------------ generator introspection
1543
Nick Coghlan7921b9f2010-11-30 06:36:04 +00001544GEN_CREATED = 'GEN_CREATED'
1545GEN_RUNNING = 'GEN_RUNNING'
1546GEN_SUSPENDED = 'GEN_SUSPENDED'
1547GEN_CLOSED = 'GEN_CLOSED'
Nick Coghlane0f04652010-11-21 03:44:04 +00001548
1549def getgeneratorstate(generator):
1550 """Get current state of a generator-iterator.
1551
1552 Possible states are:
1553 GEN_CREATED: Waiting to start execution.
1554 GEN_RUNNING: Currently being executed by the interpreter.
1555 GEN_SUSPENDED: Currently suspended at a yield expression.
1556 GEN_CLOSED: Execution has completed.
1557 """
1558 if generator.gi_running:
1559 return GEN_RUNNING
1560 if generator.gi_frame is None:
1561 return GEN_CLOSED
1562 if generator.gi_frame.f_lasti == -1:
1563 return GEN_CREATED
1564 return GEN_SUSPENDED
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07001565
1566
Nick Coghlan04e2e3f2012-06-23 19:52:05 +10001567def getgeneratorlocals(generator):
1568 """
1569 Get the mapping of generator local variables to their current values.
1570
1571 A dict is returned, with the keys the local variable names and values the
1572 bound values."""
1573
1574 if not isgenerator(generator):
1575 raise TypeError("'{!r}' is not a Python generator".format(generator))
1576
1577 frame = getattr(generator, "gi_frame", None)
1578 if frame is not None:
1579 return generator.gi_frame.f_locals
1580 else:
1581 return {}
1582
Yury Selivanov5376ba92015-06-22 12:19:30 -04001583
1584# ------------------------------------------------ coroutine introspection
1585
1586CORO_CREATED = 'CORO_CREATED'
1587CORO_RUNNING = 'CORO_RUNNING'
1588CORO_SUSPENDED = 'CORO_SUSPENDED'
1589CORO_CLOSED = 'CORO_CLOSED'
1590
1591def getcoroutinestate(coroutine):
1592 """Get current state of a coroutine object.
1593
1594 Possible states are:
1595 CORO_CREATED: Waiting to start execution.
1596 CORO_RUNNING: Currently being executed by the interpreter.
1597 CORO_SUSPENDED: Currently suspended at an await expression.
1598 CORO_CLOSED: Execution has completed.
1599 """
1600 if coroutine.cr_running:
1601 return CORO_RUNNING
1602 if coroutine.cr_frame is None:
1603 return CORO_CLOSED
1604 if coroutine.cr_frame.f_lasti == -1:
1605 return CORO_CREATED
1606 return CORO_SUSPENDED
1607
1608
1609def getcoroutinelocals(coroutine):
1610 """
1611 Get the mapping of coroutine local variables to their current values.
1612
1613 A dict is returned, with the keys the local variable names and values the
1614 bound values."""
1615 frame = getattr(coroutine, "cr_frame", None)
1616 if frame is not None:
1617 return frame.f_locals
1618 else:
1619 return {}
1620
1621
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07001622###############################################################################
1623### Function Signature Object (PEP 362)
1624###############################################################################
1625
1626
1627_WrapperDescriptor = type(type.__call__)
1628_MethodWrapper = type(all.__call__)
Larry Hastings5c661892014-01-24 06:17:25 -08001629_ClassMethodWrapper = type(int.__dict__['from_bytes'])
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07001630
1631_NonUserDefinedCallables = (_WrapperDescriptor,
1632 _MethodWrapper,
Larry Hastings5c661892014-01-24 06:17:25 -08001633 _ClassMethodWrapper,
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07001634 types.BuiltinFunctionType)
1635
1636
Yury Selivanov421f0c72014-01-29 12:05:40 -05001637def _signature_get_user_defined_method(cls, method_name):
Yury Selivanov5a23bd02014-03-29 13:47:11 -04001638 """Private helper. Checks if ``cls`` has an attribute
1639 named ``method_name`` and returns it only if it is a
1640 pure python function.
1641 """
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07001642 try:
1643 meth = getattr(cls, method_name)
1644 except AttributeError:
1645 return
1646 else:
1647 if not isinstance(meth, _NonUserDefinedCallables):
1648 # Once '__signature__' will be added to 'C'-level
1649 # callables, this check won't be necessary
1650 return meth
1651
1652
Yury Selivanov62560fb2014-01-28 12:26:24 -05001653def _signature_get_partial(wrapped_sig, partial, extra_args=()):
Yury Selivanov5a23bd02014-03-29 13:47:11 -04001654 """Private helper to calculate how 'wrapped_sig' signature will
1655 look like after applying a 'functools.partial' object (or alike)
1656 on it.
1657 """
Yury Selivanov62560fb2014-01-28 12:26:24 -05001658
Yury Selivanov3f73ca22014-04-08 11:30:45 -04001659 old_params = wrapped_sig.parameters
1660 new_params = OrderedDict(old_params.items())
Yury Selivanovda5fe4f2014-01-27 17:28:37 -05001661
1662 partial_args = partial.args or ()
1663 partial_keywords = partial.keywords or {}
1664
1665 if extra_args:
1666 partial_args = extra_args + partial_args
1667
1668 try:
1669 ba = wrapped_sig.bind_partial(*partial_args, **partial_keywords)
1670 except TypeError as ex:
1671 msg = 'partial object {!r} has incorrect arguments'.format(partial)
1672 raise ValueError(msg) from ex
1673
Yury Selivanovda5fe4f2014-01-27 17:28:37 -05001674
Yury Selivanov3f73ca22014-04-08 11:30:45 -04001675 transform_to_kwonly = False
1676 for param_name, param in old_params.items():
1677 try:
1678 arg_value = ba.arguments[param_name]
1679 except KeyError:
1680 pass
1681 else:
1682 if param.kind is _POSITIONAL_ONLY:
1683 # If positional-only parameter is bound by partial,
1684 # it effectively disappears from the signature
1685 new_params.pop(param_name)
1686 continue
1687
1688 if param.kind is _POSITIONAL_OR_KEYWORD:
1689 if param_name in partial_keywords:
1690 # This means that this parameter, and all parameters
1691 # after it should be keyword-only (and var-positional
1692 # should be removed). Here's why. Consider the following
1693 # function:
1694 # foo(a, b, *args, c):
1695 # pass
1696 #
1697 # "partial(foo, a='spam')" will have the following
1698 # signature: "(*, a='spam', b, c)". Because attempting
1699 # to call that partial with "(10, 20)" arguments will
1700 # raise a TypeError, saying that "a" argument received
1701 # multiple values.
1702 transform_to_kwonly = True
1703 # Set the new default value
1704 new_params[param_name] = param.replace(default=arg_value)
1705 else:
1706 # was passed as a positional argument
1707 new_params.pop(param.name)
1708 continue
1709
1710 if param.kind is _KEYWORD_ONLY:
1711 # Set the new default value
1712 new_params[param_name] = param.replace(default=arg_value)
1713
1714 if transform_to_kwonly:
1715 assert param.kind is not _POSITIONAL_ONLY
1716
1717 if param.kind is _POSITIONAL_OR_KEYWORD:
1718 new_param = new_params[param_name].replace(kind=_KEYWORD_ONLY)
1719 new_params[param_name] = new_param
1720 new_params.move_to_end(param_name)
1721 elif param.kind in (_KEYWORD_ONLY, _VAR_KEYWORD):
1722 new_params.move_to_end(param_name)
1723 elif param.kind is _VAR_POSITIONAL:
1724 new_params.pop(param.name)
Yury Selivanovda5fe4f2014-01-27 17:28:37 -05001725
1726 return wrapped_sig.replace(parameters=new_params.values())
1727
1728
Yury Selivanov62560fb2014-01-28 12:26:24 -05001729def _signature_bound_method(sig):
Yury Selivanov5a23bd02014-03-29 13:47:11 -04001730 """Private helper to transform signatures for unbound
1731 functions to bound methods.
1732 """
Yury Selivanov62560fb2014-01-28 12:26:24 -05001733
1734 params = tuple(sig.parameters.values())
1735
1736 if not params or params[0].kind in (_VAR_KEYWORD, _KEYWORD_ONLY):
1737 raise ValueError('invalid method signature')
1738
1739 kind = params[0].kind
1740 if kind in (_POSITIONAL_OR_KEYWORD, _POSITIONAL_ONLY):
1741 # Drop first parameter:
1742 # '(p1, p2[, ...])' -> '(p2[, ...])'
1743 params = params[1:]
1744 else:
1745 if kind is not _VAR_POSITIONAL:
1746 # Unless we add a new parameter type we never
1747 # get here
1748 raise ValueError('invalid argument type')
1749 # It's a var-positional parameter.
1750 # Do nothing. '(*args[, ...])' -> '(*args[, ...])'
1751
1752 return sig.replace(parameters=params)
1753
1754
Yury Selivanovb77511d2014-01-29 10:46:14 -05001755def _signature_is_builtin(obj):
Yury Selivanov5a23bd02014-03-29 13:47:11 -04001756 """Private helper to test if `obj` is a callable that might
1757 support Argument Clinic's __text_signature__ protocol.
1758 """
Yury Selivanov1d241832014-02-02 12:51:20 -05001759 return (isbuiltin(obj) or
Yury Selivanovb77511d2014-01-29 10:46:14 -05001760 ismethoddescriptor(obj) or
Yury Selivanov1d241832014-02-02 12:51:20 -05001761 isinstance(obj, _NonUserDefinedCallables) or
Yury Selivanovb77511d2014-01-29 10:46:14 -05001762 # Can't test 'isinstance(type)' here, as it would
1763 # also be True for regular python classes
1764 obj in (type, object))
1765
1766
Yury Selivanov63da7c72014-01-31 14:48:37 -05001767def _signature_is_functionlike(obj):
Yury Selivanov5a23bd02014-03-29 13:47:11 -04001768 """Private helper to test if `obj` is a duck type of FunctionType.
1769 A good example of such objects are functions compiled with
1770 Cython, which have all attributes that a pure Python function
1771 would have, but have their code statically compiled.
1772 """
Yury Selivanov63da7c72014-01-31 14:48:37 -05001773
1774 if not callable(obj) or isclass(obj):
1775 # All function-like objects are obviously callables,
1776 # and not classes.
1777 return False
1778
1779 name = getattr(obj, '__name__', None)
1780 code = getattr(obj, '__code__', None)
1781 defaults = getattr(obj, '__defaults__', _void) # Important to use _void ...
1782 kwdefaults = getattr(obj, '__kwdefaults__', _void) # ... and not None here
1783 annotations = getattr(obj, '__annotations__', None)
1784
1785 return (isinstance(code, types.CodeType) and
1786 isinstance(name, str) and
1787 (defaults is None or isinstance(defaults, tuple)) and
1788 (kwdefaults is None or isinstance(kwdefaults, dict)) and
1789 isinstance(annotations, dict))
1790
1791
Yury Selivanovd82eddc2014-01-29 11:24:39 -05001792def _signature_get_bound_param(spec):
Yury Selivanov5a23bd02014-03-29 13:47:11 -04001793 """ Private helper to get first parameter name from a
1794 __text_signature__ of a builtin method, which should
1795 be in the following format: '($param1, ...)'.
1796 Assumptions are that the first argument won't have
1797 a default value or an annotation.
1798 """
Yury Selivanovd82eddc2014-01-29 11:24:39 -05001799
1800 assert spec.startswith('($')
1801
1802 pos = spec.find(',')
1803 if pos == -1:
1804 pos = spec.find(')')
1805
1806 cpos = spec.find(':')
1807 assert cpos == -1 or cpos > pos
1808
1809 cpos = spec.find('=')
1810 assert cpos == -1 or cpos > pos
1811
1812 return spec[2:pos]
1813
1814
Larry Hastings2623c8c2014-02-08 22:15:29 -08001815def _signature_strip_non_python_syntax(signature):
1816 """
Yury Selivanov5a23bd02014-03-29 13:47:11 -04001817 Private helper function. Takes a signature in Argument Clinic's
1818 extended signature format.
1819
Larry Hastings2623c8c2014-02-08 22:15:29 -08001820 Returns a tuple of three things:
1821 * that signature re-rendered in standard Python syntax,
1822 * the index of the "self" parameter (generally 0), or None if
1823 the function does not have a "self" parameter, and
1824 * the index of the last "positional only" parameter,
1825 or None if the signature has no positional-only parameters.
1826 """
1827
1828 if not signature:
1829 return signature, None, None
1830
1831 self_parameter = None
1832 last_positional_only = None
1833
1834 lines = [l.encode('ascii') for l in signature.split('\n')]
1835 generator = iter(lines).__next__
1836 token_stream = tokenize.tokenize(generator)
1837
1838 delayed_comma = False
1839 skip_next_comma = False
1840 text = []
1841 add = text.append
1842
1843 current_parameter = 0
1844 OP = token.OP
1845 ERRORTOKEN = token.ERRORTOKEN
1846
1847 # token stream always starts with ENCODING token, skip it
1848 t = next(token_stream)
1849 assert t.type == tokenize.ENCODING
1850
1851 for t in token_stream:
1852 type, string = t.type, t.string
1853
1854 if type == OP:
1855 if string == ',':
1856 if skip_next_comma:
1857 skip_next_comma = False
1858 else:
1859 assert not delayed_comma
1860 delayed_comma = True
1861 current_parameter += 1
1862 continue
1863
1864 if string == '/':
1865 assert not skip_next_comma
1866 assert last_positional_only is None
1867 skip_next_comma = True
1868 last_positional_only = current_parameter - 1
1869 continue
1870
1871 if (type == ERRORTOKEN) and (string == '$'):
1872 assert self_parameter is None
1873 self_parameter = current_parameter
1874 continue
1875
1876 if delayed_comma:
1877 delayed_comma = False
1878 if not ((type == OP) and (string == ')')):
1879 add(', ')
1880 add(string)
1881 if (string == ','):
1882 add(' ')
1883 clean_signature = ''.join(text)
1884 return clean_signature, self_parameter, last_positional_only
1885
1886
Yury Selivanov57d240e2014-02-19 16:27:23 -05001887def _signature_fromstr(cls, obj, s, skip_bound_arg=True):
Yury Selivanov5a23bd02014-03-29 13:47:11 -04001888 """Private helper to parse content of '__text_signature__'
1889 and return a Signature based on it.
1890 """
1891
Yury Selivanov7d2bfed2014-02-03 02:46:07 -05001892 Parameter = cls._parameter_cls
1893
Larry Hastings2623c8c2014-02-08 22:15:29 -08001894 clean_signature, self_parameter, last_positional_only = \
1895 _signature_strip_non_python_syntax(s)
Yury Selivanov7d2bfed2014-02-03 02:46:07 -05001896
Larry Hastings2623c8c2014-02-08 22:15:29 -08001897 program = "def foo" + clean_signature + ": pass"
Yury Selivanov7d2bfed2014-02-03 02:46:07 -05001898
1899 try:
Larry Hastings2623c8c2014-02-08 22:15:29 -08001900 module = ast.parse(program)
Yury Selivanov7d2bfed2014-02-03 02:46:07 -05001901 except SyntaxError:
1902 module = None
1903
1904 if not isinstance(module, ast.Module):
1905 raise ValueError("{!r} builtin has invalid signature".format(obj))
1906
1907 f = module.body[0]
1908
1909 parameters = []
1910 empty = Parameter.empty
1911 invalid = object()
1912
1913 module = None
1914 module_dict = {}
1915 module_name = getattr(obj, '__module__', None)
1916 if module_name:
1917 module = sys.modules.get(module_name, None)
1918 if module:
1919 module_dict = module.__dict__
1920 sys_module_dict = sys.modules
1921
1922 def parse_name(node):
1923 assert isinstance(node, ast.arg)
1924 if node.annotation != None:
1925 raise ValueError("Annotations are not currently supported")
1926 return node.arg
1927
1928 def wrap_value(s):
1929 try:
1930 value = eval(s, module_dict)
1931 except NameError:
1932 try:
1933 value = eval(s, sys_module_dict)
1934 except NameError:
1935 raise RuntimeError()
1936
1937 if isinstance(value, str):
1938 return ast.Str(value)
1939 if isinstance(value, (int, float)):
1940 return ast.Num(value)
1941 if isinstance(value, bytes):
1942 return ast.Bytes(value)
1943 if value in (True, False, None):
1944 return ast.NameConstant(value)
1945 raise RuntimeError()
1946
1947 class RewriteSymbolics(ast.NodeTransformer):
1948 def visit_Attribute(self, node):
1949 a = []
1950 n = node
1951 while isinstance(n, ast.Attribute):
1952 a.append(n.attr)
1953 n = n.value
1954 if not isinstance(n, ast.Name):
1955 raise RuntimeError()
1956 a.append(n.id)
1957 value = ".".join(reversed(a))
1958 return wrap_value(value)
1959
1960 def visit_Name(self, node):
1961 if not isinstance(node.ctx, ast.Load):
1962 raise ValueError()
1963 return wrap_value(node.id)
1964
1965 def p(name_node, default_node, default=empty):
1966 name = parse_name(name_node)
1967 if name is invalid:
1968 return None
1969 if default_node and default_node is not _empty:
1970 try:
1971 default_node = RewriteSymbolics().visit(default_node)
1972 o = ast.literal_eval(default_node)
1973 except ValueError:
1974 o = invalid
1975 if o is invalid:
1976 return None
1977 default = o if o is not invalid else default
1978 parameters.append(Parameter(name, kind, default=default, annotation=empty))
1979
1980 # non-keyword-only parameters
1981 args = reversed(f.args.args)
1982 defaults = reversed(f.args.defaults)
1983 iter = itertools.zip_longest(args, defaults, fillvalue=None)
Larry Hastings2623c8c2014-02-08 22:15:29 -08001984 if last_positional_only is not None:
1985 kind = Parameter.POSITIONAL_ONLY
1986 else:
1987 kind = Parameter.POSITIONAL_OR_KEYWORD
1988 for i, (name, default) in enumerate(reversed(list(iter))):
Yury Selivanov7d2bfed2014-02-03 02:46:07 -05001989 p(name, default)
Larry Hastings2623c8c2014-02-08 22:15:29 -08001990 if i == last_positional_only:
1991 kind = Parameter.POSITIONAL_OR_KEYWORD
Yury Selivanov7d2bfed2014-02-03 02:46:07 -05001992
1993 # *args
1994 if f.args.vararg:
1995 kind = Parameter.VAR_POSITIONAL
1996 p(f.args.vararg, empty)
1997
1998 # keyword-only arguments
1999 kind = Parameter.KEYWORD_ONLY
2000 for name, default in zip(f.args.kwonlyargs, f.args.kw_defaults):
2001 p(name, default)
2002
2003 # **kwargs
2004 if f.args.kwarg:
2005 kind = Parameter.VAR_KEYWORD
2006 p(f.args.kwarg, empty)
2007
Larry Hastings2623c8c2014-02-08 22:15:29 -08002008 if self_parameter is not None:
Yury Selivanov8c185ee2014-02-21 01:32:42 -05002009 # Possibly strip the bound argument:
2010 # - We *always* strip first bound argument if
2011 # it is a module.
2012 # - We don't strip first bound argument if
2013 # skip_bound_arg is False.
Yury Selivanov7d2bfed2014-02-03 02:46:07 -05002014 assert parameters
Yury Selivanov8c185ee2014-02-21 01:32:42 -05002015 _self = getattr(obj, '__self__', None)
2016 self_isbound = _self is not None
2017 self_ismodule = ismodule(_self)
2018 if self_isbound and (self_ismodule or skip_bound_arg):
Yury Selivanov7d2bfed2014-02-03 02:46:07 -05002019 parameters.pop(0)
2020 else:
2021 # for builtins, self parameter is always positional-only!
2022 p = parameters[0].replace(kind=Parameter.POSITIONAL_ONLY)
2023 parameters[0] = p
2024
2025 return cls(parameters, return_annotation=cls.empty)
2026
2027
Yury Selivanov57d240e2014-02-19 16:27:23 -05002028def _signature_from_builtin(cls, func, skip_bound_arg=True):
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002029 """Private helper function to get signature for
2030 builtin callables.
2031 """
2032
Yury Selivanov57d240e2014-02-19 16:27:23 -05002033 if not _signature_is_builtin(func):
2034 raise TypeError("{!r} is not a Python builtin "
2035 "function".format(func))
2036
2037 s = getattr(func, "__text_signature__", None)
2038 if not s:
2039 raise ValueError("no signature found for builtin {!r}".format(func))
2040
2041 return _signature_fromstr(cls, func, s, skip_bound_arg)
2042
2043
Yury Selivanovcf45f022015-05-20 14:38:50 -04002044def _signature_from_function(cls, func):
2045 """Private helper: constructs Signature for the given python function."""
2046
2047 is_duck_function = False
2048 if not isfunction(func):
2049 if _signature_is_functionlike(func):
2050 is_duck_function = True
2051 else:
2052 # If it's not a pure Python function, and not a duck type
2053 # of pure function:
2054 raise TypeError('{!r} is not a Python function'.format(func))
2055
2056 Parameter = cls._parameter_cls
2057
2058 # Parameter information.
2059 func_code = func.__code__
2060 pos_count = func_code.co_argcount
2061 arg_names = func_code.co_varnames
2062 positional = tuple(arg_names[:pos_count])
2063 keyword_only_count = func_code.co_kwonlyargcount
2064 keyword_only = arg_names[pos_count:(pos_count + keyword_only_count)]
2065 annotations = func.__annotations__
2066 defaults = func.__defaults__
2067 kwdefaults = func.__kwdefaults__
2068
2069 if defaults:
2070 pos_default_count = len(defaults)
2071 else:
2072 pos_default_count = 0
2073
2074 parameters = []
2075
2076 # Non-keyword-only parameters w/o defaults.
2077 non_default_count = pos_count - pos_default_count
2078 for name in positional[:non_default_count]:
2079 annotation = annotations.get(name, _empty)
2080 parameters.append(Parameter(name, annotation=annotation,
2081 kind=_POSITIONAL_OR_KEYWORD))
2082
2083 # ... w/ defaults.
2084 for offset, name in enumerate(positional[non_default_count:]):
2085 annotation = annotations.get(name, _empty)
2086 parameters.append(Parameter(name, annotation=annotation,
2087 kind=_POSITIONAL_OR_KEYWORD,
2088 default=defaults[offset]))
2089
2090 # *args
2091 if func_code.co_flags & CO_VARARGS:
2092 name = arg_names[pos_count + keyword_only_count]
2093 annotation = annotations.get(name, _empty)
2094 parameters.append(Parameter(name, annotation=annotation,
2095 kind=_VAR_POSITIONAL))
2096
2097 # Keyword-only parameters.
2098 for name in keyword_only:
2099 default = _empty
2100 if kwdefaults is not None:
2101 default = kwdefaults.get(name, _empty)
2102
2103 annotation = annotations.get(name, _empty)
2104 parameters.append(Parameter(name, annotation=annotation,
2105 kind=_KEYWORD_ONLY,
2106 default=default))
2107 # **kwargs
2108 if func_code.co_flags & CO_VARKEYWORDS:
2109 index = pos_count + keyword_only_count
2110 if func_code.co_flags & CO_VARARGS:
2111 index += 1
2112
2113 name = arg_names[index]
2114 annotation = annotations.get(name, _empty)
2115 parameters.append(Parameter(name, annotation=annotation,
2116 kind=_VAR_KEYWORD))
2117
2118 # Is 'func' is a pure Python function - don't validate the
2119 # parameters list (for correct order and defaults), it should be OK.
2120 return cls(parameters,
2121 return_annotation=annotations.get('return', _empty),
2122 __validate_parameters__=is_duck_function)
2123
2124
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002125def _signature_from_callable(obj, *,
2126 follow_wrapper_chains=True,
2127 skip_bound_arg=True,
2128 sigcls):
2129
2130 """Private helper function to get signature for arbitrary
2131 callable objects.
2132 """
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002133
2134 if not callable(obj):
2135 raise TypeError('{!r} is not a callable object'.format(obj))
2136
2137 if isinstance(obj, types.MethodType):
2138 # In this case we skip the first parameter of the underlying
2139 # function (usually `self` or `cls`).
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002140 sig = _signature_from_callable(
Yury Selivanovda396452014-03-27 12:09:24 -04002141 obj.__func__,
2142 follow_wrapper_chains=follow_wrapper_chains,
2143 skip_bound_arg=skip_bound_arg,
2144 sigcls=sigcls)
2145
Yury Selivanov57d240e2014-02-19 16:27:23 -05002146 if skip_bound_arg:
2147 return _signature_bound_method(sig)
2148 else:
2149 return sig
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002150
Nick Coghlane8c45d62013-07-28 20:00:01 +10002151 # Was this function wrapped by a decorator?
Yury Selivanov57d240e2014-02-19 16:27:23 -05002152 if follow_wrapper_chains:
2153 obj = unwrap(obj, stop=(lambda f: hasattr(f, "__signature__")))
Yury Selivanov46c759d2015-05-27 21:56:53 -04002154 if isinstance(obj, types.MethodType):
2155 # If the unwrapped object is a *method*, we might want to
2156 # skip its first parameter (self).
2157 # See test_signature_wrapped_bound_method for details.
Yury Selivanov507cd3c2015-05-27 21:59:03 -04002158 return _signature_from_callable(
Yury Selivanov46c759d2015-05-27 21:56:53 -04002159 obj,
2160 follow_wrapper_chains=follow_wrapper_chains,
Yury Selivanov507cd3c2015-05-27 21:59:03 -04002161 skip_bound_arg=skip_bound_arg,
2162 sigcls=sigcls)
Nick Coghlane8c45d62013-07-28 20:00:01 +10002163
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002164 try:
2165 sig = obj.__signature__
2166 except AttributeError:
2167 pass
2168 else:
2169 if sig is not None:
Yury Selivanov42407ab2014-06-23 10:23:50 -07002170 if not isinstance(sig, Signature):
2171 raise TypeError(
2172 'unexpected object {!r} in __signature__ '
2173 'attribute'.format(sig))
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002174 return sig
2175
Yury Selivanovda5fe4f2014-01-27 17:28:37 -05002176 try:
2177 partialmethod = obj._partialmethod
2178 except AttributeError:
2179 pass
2180 else:
Yury Selivanov0486f812014-01-29 12:18:59 -05002181 if isinstance(partialmethod, functools.partialmethod):
2182 # Unbound partialmethod (see functools.partialmethod)
2183 # This means, that we need to calculate the signature
2184 # as if it's a regular partial object, but taking into
2185 # account that the first positional argument
2186 # (usually `self`, or `cls`) will not be passed
2187 # automatically (as for boundmethods)
Yury Selivanovda5fe4f2014-01-27 17:28:37 -05002188
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002189 wrapped_sig = _signature_from_callable(
Yury Selivanovda396452014-03-27 12:09:24 -04002190 partialmethod.func,
2191 follow_wrapper_chains=follow_wrapper_chains,
2192 skip_bound_arg=skip_bound_arg,
2193 sigcls=sigcls)
2194
Yury Selivanov0486f812014-01-29 12:18:59 -05002195 sig = _signature_get_partial(wrapped_sig, partialmethod, (None,))
Yury Selivanovda5fe4f2014-01-27 17:28:37 -05002196
Yury Selivanov0486f812014-01-29 12:18:59 -05002197 first_wrapped_param = tuple(wrapped_sig.parameters.values())[0]
2198 new_params = (first_wrapped_param,) + tuple(sig.parameters.values())
Yury Selivanovda5fe4f2014-01-27 17:28:37 -05002199
Yury Selivanov0486f812014-01-29 12:18:59 -05002200 return sig.replace(parameters=new_params)
Yury Selivanovda5fe4f2014-01-27 17:28:37 -05002201
Yury Selivanov63da7c72014-01-31 14:48:37 -05002202 if isfunction(obj) or _signature_is_functionlike(obj):
2203 # If it's a pure Python function, or an object that is duck type
2204 # of a Python function (Cython functions, for instance), then:
Yury Selivanovcf45f022015-05-20 14:38:50 -04002205 return _signature_from_function(sigcls, obj)
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002206
Yury Selivanova773de02014-02-21 18:30:53 -05002207 if _signature_is_builtin(obj):
Yury Selivanovda396452014-03-27 12:09:24 -04002208 return _signature_from_builtin(sigcls, obj,
Yury Selivanova773de02014-02-21 18:30:53 -05002209 skip_bound_arg=skip_bound_arg)
2210
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002211 if isinstance(obj, functools.partial):
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002212 wrapped_sig = _signature_from_callable(
Yury Selivanovda396452014-03-27 12:09:24 -04002213 obj.func,
2214 follow_wrapper_chains=follow_wrapper_chains,
2215 skip_bound_arg=skip_bound_arg,
2216 sigcls=sigcls)
Yury Selivanov62560fb2014-01-28 12:26:24 -05002217 return _signature_get_partial(wrapped_sig, obj)
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002218
2219 sig = None
2220 if isinstance(obj, type):
2221 # obj is a class or a metaclass
2222
2223 # First, let's see if it has an overloaded __call__ defined
2224 # in its metaclass
Yury Selivanov421f0c72014-01-29 12:05:40 -05002225 call = _signature_get_user_defined_method(type(obj), '__call__')
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002226 if call is not None:
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002227 sig = _signature_from_callable(
Yury Selivanovda396452014-03-27 12:09:24 -04002228 call,
2229 follow_wrapper_chains=follow_wrapper_chains,
2230 skip_bound_arg=skip_bound_arg,
2231 sigcls=sigcls)
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002232 else:
2233 # Now we check if the 'obj' class has a '__new__' method
Yury Selivanov421f0c72014-01-29 12:05:40 -05002234 new = _signature_get_user_defined_method(obj, '__new__')
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002235 if new is not None:
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002236 sig = _signature_from_callable(
Yury Selivanovda396452014-03-27 12:09:24 -04002237 new,
2238 follow_wrapper_chains=follow_wrapper_chains,
2239 skip_bound_arg=skip_bound_arg,
2240 sigcls=sigcls)
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002241 else:
2242 # Finally, we should have at least __init__ implemented
Yury Selivanov421f0c72014-01-29 12:05:40 -05002243 init = _signature_get_user_defined_method(obj, '__init__')
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002244 if init is not None:
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002245 sig = _signature_from_callable(
Yury Selivanovda396452014-03-27 12:09:24 -04002246 init,
2247 follow_wrapper_chains=follow_wrapper_chains,
2248 skip_bound_arg=skip_bound_arg,
2249 sigcls=sigcls)
Yury Selivanove7dcc5e2014-01-27 19:29:45 -05002250
2251 if sig is None:
Yury Selivanov7d2bfed2014-02-03 02:46:07 -05002252 # At this point we know, that `obj` is a class, with no user-
2253 # defined '__init__', '__new__', or class-level '__call__'
2254
Larry Hastings2623c8c2014-02-08 22:15:29 -08002255 for base in obj.__mro__[:-1]:
Yury Selivanov7d2bfed2014-02-03 02:46:07 -05002256 # Since '__text_signature__' is implemented as a
2257 # descriptor that extracts text signature from the
2258 # class docstring, if 'obj' is derived from a builtin
2259 # class, its own '__text_signature__' may be 'None'.
Larry Hastings2623c8c2014-02-08 22:15:29 -08002260 # Therefore, we go through the MRO (except the last
2261 # class in there, which is 'object') to find the first
Yury Selivanov7d2bfed2014-02-03 02:46:07 -05002262 # class with non-empty text signature.
2263 try:
2264 text_sig = base.__text_signature__
2265 except AttributeError:
2266 pass
2267 else:
2268 if text_sig:
2269 # If 'obj' class has a __text_signature__ attribute:
2270 # return a signature based on it
Yury Selivanovda396452014-03-27 12:09:24 -04002271 return _signature_fromstr(sigcls, obj, text_sig)
Yury Selivanov7d2bfed2014-02-03 02:46:07 -05002272
2273 # No '__text_signature__' was found for the 'obj' class.
2274 # Last option is to check if its '__init__' is
2275 # object.__init__ or type.__init__.
Larry Hastings2623c8c2014-02-08 22:15:29 -08002276 if type not in obj.__mro__:
Yury Selivanove7dcc5e2014-01-27 19:29:45 -05002277 # We have a class (not metaclass), but no user-defined
2278 # __init__ or __new__ for it
Yury Selivanovbf304fc2015-05-30 17:08:36 -04002279 if (obj.__init__ is object.__init__ and
2280 obj.__new__ is object.__new__):
Yury Selivanov7d2bfed2014-02-03 02:46:07 -05002281 # Return a signature of 'object' builtin.
2282 return signature(object)
Yury Selivanovbf304fc2015-05-30 17:08:36 -04002283 else:
2284 raise ValueError(
2285 'no signature found for builtin type {!r}'.format(obj))
Yury Selivanove7dcc5e2014-01-27 19:29:45 -05002286
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002287 elif not isinstance(obj, _NonUserDefinedCallables):
2288 # An object with __call__
2289 # We also check that the 'obj' is not an instance of
2290 # _WrapperDescriptor or _MethodWrapper to avoid
2291 # infinite recursion (and even potential segfault)
Yury Selivanov421f0c72014-01-29 12:05:40 -05002292 call = _signature_get_user_defined_method(type(obj), '__call__')
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002293 if call is not None:
Larry Hastings2623c8c2014-02-08 22:15:29 -08002294 try:
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002295 sig = _signature_from_callable(
Yury Selivanovda396452014-03-27 12:09:24 -04002296 call,
2297 follow_wrapper_chains=follow_wrapper_chains,
2298 skip_bound_arg=skip_bound_arg,
2299 sigcls=sigcls)
Larry Hastings2623c8c2014-02-08 22:15:29 -08002300 except ValueError as ex:
2301 msg = 'no signature found for {!r}'.format(obj)
2302 raise ValueError(msg) from ex
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002303
2304 if sig is not None:
2305 # For classes and objects we skip the first parameter of their
2306 # __call__, __new__, or __init__ methods
Yury Selivanov57d240e2014-02-19 16:27:23 -05002307 if skip_bound_arg:
2308 return _signature_bound_method(sig)
2309 else:
2310 return sig
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002311
2312 if isinstance(obj, types.BuiltinFunctionType):
2313 # Raise a nicer error message for builtins
2314 msg = 'no signature found for builtin function {!r}'.format(obj)
2315 raise ValueError(msg)
2316
2317 raise ValueError('callable {!r} is not supported by signature'.format(obj))
2318
2319
2320class _void:
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002321 """A private marker - used in Parameter & Signature."""
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002322
2323
2324class _empty:
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002325 """Marker object for Signature.empty and Parameter.empty."""
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002326
2327
Yury Selivanov21e83a52014-03-27 11:23:13 -04002328class _ParameterKind(enum.IntEnum):
2329 POSITIONAL_ONLY = 0
2330 POSITIONAL_OR_KEYWORD = 1
2331 VAR_POSITIONAL = 2
2332 KEYWORD_ONLY = 3
2333 VAR_KEYWORD = 4
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002334
2335 def __str__(self):
Yury Selivanov21e83a52014-03-27 11:23:13 -04002336 return self._name_
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002337
2338
Yury Selivanov21e83a52014-03-27 11:23:13 -04002339_POSITIONAL_ONLY = _ParameterKind.POSITIONAL_ONLY
2340_POSITIONAL_OR_KEYWORD = _ParameterKind.POSITIONAL_OR_KEYWORD
2341_VAR_POSITIONAL = _ParameterKind.VAR_POSITIONAL
2342_KEYWORD_ONLY = _ParameterKind.KEYWORD_ONLY
2343_VAR_KEYWORD = _ParameterKind.VAR_KEYWORD
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002344
2345
2346class Parameter:
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002347 """Represents a parameter in a function signature.
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002348
2349 Has the following public attributes:
2350
2351 * name : str
2352 The name of the parameter as a string.
2353 * default : object
2354 The default value for the parameter if specified. If the
Yury Selivanov8757ead2014-01-28 16:39:25 -05002355 parameter has no default value, this attribute is set to
2356 `Parameter.empty`.
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002357 * annotation
2358 The annotation for the parameter if specified. If the
Yury Selivanov8757ead2014-01-28 16:39:25 -05002359 parameter has no annotation, this attribute is set to
2360 `Parameter.empty`.
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002361 * kind : str
2362 Describes how argument values are bound to the parameter.
2363 Possible values: `Parameter.POSITIONAL_ONLY`,
2364 `Parameter.POSITIONAL_OR_KEYWORD`, `Parameter.VAR_POSITIONAL`,
2365 `Parameter.KEYWORD_ONLY`, `Parameter.VAR_KEYWORD`.
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002366 """
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002367
Yury Selivanov3f73ca22014-04-08 11:30:45 -04002368 __slots__ = ('_name', '_kind', '_default', '_annotation')
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002369
2370 POSITIONAL_ONLY = _POSITIONAL_ONLY
2371 POSITIONAL_OR_KEYWORD = _POSITIONAL_OR_KEYWORD
2372 VAR_POSITIONAL = _VAR_POSITIONAL
2373 KEYWORD_ONLY = _KEYWORD_ONLY
2374 VAR_KEYWORD = _VAR_KEYWORD
2375
2376 empty = _empty
2377
Yury Selivanov3f73ca22014-04-08 11:30:45 -04002378 def __init__(self, name, kind, *, default=_empty, annotation=_empty):
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002379
2380 if kind not in (_POSITIONAL_ONLY, _POSITIONAL_OR_KEYWORD,
2381 _VAR_POSITIONAL, _KEYWORD_ONLY, _VAR_KEYWORD):
2382 raise ValueError("invalid value for 'Parameter.kind' attribute")
2383 self._kind = kind
2384
2385 if default is not _empty:
2386 if kind in (_VAR_POSITIONAL, _VAR_KEYWORD):
2387 msg = '{} parameters cannot have default values'.format(kind)
2388 raise ValueError(msg)
2389 self._default = default
2390 self._annotation = annotation
2391
Yury Selivanov2393dca2014-01-27 15:07:58 -05002392 if name is _empty:
2393 raise ValueError('name is a required attribute for Parameter')
2394
2395 if not isinstance(name, str):
2396 raise TypeError("name must be a str, not a {!r}".format(name))
2397
Nick Coghlanb4b966e2016-06-04 14:40:03 -07002398 if name[0] == '.' and name[1:].isdigit():
2399 # These are implicit arguments generated by comprehensions. In
2400 # order to provide a friendlier interface to users, we recast
2401 # their name as "implicitN" and treat them as positional-only.
2402 # See issue 19611.
2403 if kind != _POSITIONAL_OR_KEYWORD:
2404 raise ValueError(
2405 'implicit arguments must be passed in as {}'.format(
2406 _POSITIONAL_OR_KEYWORD
2407 )
2408 )
2409 self._kind = _POSITIONAL_ONLY
2410 name = 'implicit{}'.format(name[1:])
2411
Yury Selivanov2393dca2014-01-27 15:07:58 -05002412 if not name.isidentifier():
2413 raise ValueError('{!r} is not a valid parameter name'.format(name))
2414
2415 self._name = name
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002416
Yury Selivanova5d63dd2014-03-27 11:31:43 -04002417 def __reduce__(self):
2418 return (type(self),
2419 (self._name, self._kind),
Yury Selivanov3f73ca22014-04-08 11:30:45 -04002420 {'_default': self._default,
Yury Selivanova5d63dd2014-03-27 11:31:43 -04002421 '_annotation': self._annotation})
2422
2423 def __setstate__(self, state):
Yury Selivanova5d63dd2014-03-27 11:31:43 -04002424 self._default = state['_default']
2425 self._annotation = state['_annotation']
2426
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002427 @property
2428 def name(self):
2429 return self._name
2430
2431 @property
2432 def default(self):
2433 return self._default
2434
2435 @property
2436 def annotation(self):
2437 return self._annotation
2438
2439 @property
2440 def kind(self):
2441 return self._kind
2442
Yury Selivanov3f73ca22014-04-08 11:30:45 -04002443 def replace(self, *, name=_void, kind=_void,
2444 annotation=_void, default=_void):
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002445 """Creates a customized copy of the Parameter."""
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002446
2447 if name is _void:
2448 name = self._name
2449
2450 if kind is _void:
2451 kind = self._kind
2452
2453 if annotation is _void:
2454 annotation = self._annotation
2455
2456 if default is _void:
2457 default = self._default
2458
Yury Selivanov3f73ca22014-04-08 11:30:45 -04002459 return type(self)(name, kind, default=default, annotation=annotation)
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002460
2461 def __str__(self):
2462 kind = self.kind
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002463 formatted = self._name
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002464
2465 # Add annotation and default value
2466 if self._annotation is not _empty:
2467 formatted = '{}:{}'.format(formatted,
2468 formatannotation(self._annotation))
2469
2470 if self._default is not _empty:
2471 formatted = '{}={}'.format(formatted, repr(self._default))
2472
2473 if kind == _VAR_POSITIONAL:
2474 formatted = '*' + formatted
2475 elif kind == _VAR_KEYWORD:
2476 formatted = '**' + formatted
2477
2478 return formatted
2479
2480 def __repr__(self):
Yury Selivanovf229bc52015-05-15 12:53:56 -04002481 return '<{} "{}">'.format(self.__class__.__name__, self)
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002482
Yury Selivanov67ae50e2014-04-08 11:46:50 -04002483 def __hash__(self):
Yury Selivanov08d4a4f2014-09-12 15:48:02 -04002484 return hash((self.name, self.kind, self.annotation, self.default))
Yury Selivanov67ae50e2014-04-08 11:46:50 -04002485
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002486 def __eq__(self, other):
Serhiy Storchaka2489bd52015-07-18 23:20:50 +03002487 if self is other:
2488 return True
Serhiy Storchaka3018cc42015-07-18 23:19:05 +03002489 if not isinstance(other, Parameter):
2490 return NotImplemented
2491 return (self._name == other._name and
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002492 self._kind == other._kind and
2493 self._default == other._default and
2494 self._annotation == other._annotation)
2495
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002496
2497class BoundArguments:
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002498 """Result of `Signature.bind` call. Holds the mapping of arguments
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002499 to the function's parameters.
2500
2501 Has the following public attributes:
2502
2503 * arguments : OrderedDict
2504 An ordered mutable mapping of parameters' names to arguments' values.
2505 Does not contain arguments' default values.
2506 * signature : Signature
2507 The Signature object that created this instance.
2508 * args : tuple
2509 Tuple of positional arguments values.
2510 * kwargs : dict
2511 Dict of keyword arguments values.
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002512 """
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002513
Yury Selivanov6abe0322015-05-13 17:18:41 -04002514 __slots__ = ('arguments', '_signature', '__weakref__')
2515
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002516 def __init__(self, signature, arguments):
2517 self.arguments = arguments
2518 self._signature = signature
2519
2520 @property
2521 def signature(self):
2522 return self._signature
2523
2524 @property
2525 def args(self):
2526 args = []
2527 for param_name, param in self._signature.parameters.items():
Yury Selivanov3f73ca22014-04-08 11:30:45 -04002528 if param.kind in (_VAR_KEYWORD, _KEYWORD_ONLY):
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002529 break
2530
2531 try:
2532 arg = self.arguments[param_name]
2533 except KeyError:
2534 # We're done here. Other arguments
2535 # will be mapped in 'BoundArguments.kwargs'
2536 break
2537 else:
2538 if param.kind == _VAR_POSITIONAL:
2539 # *args
2540 args.extend(arg)
2541 else:
2542 # plain argument
2543 args.append(arg)
2544
2545 return tuple(args)
2546
2547 @property
2548 def kwargs(self):
2549 kwargs = {}
2550 kwargs_started = False
2551 for param_name, param in self._signature.parameters.items():
2552 if not kwargs_started:
Yury Selivanov3f73ca22014-04-08 11:30:45 -04002553 if param.kind in (_VAR_KEYWORD, _KEYWORD_ONLY):
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002554 kwargs_started = True
2555 else:
2556 if param_name not in self.arguments:
2557 kwargs_started = True
2558 continue
2559
2560 if not kwargs_started:
2561 continue
2562
2563 try:
2564 arg = self.arguments[param_name]
2565 except KeyError:
2566 pass
2567 else:
2568 if param.kind == _VAR_KEYWORD:
2569 # **kwargs
2570 kwargs.update(arg)
2571 else:
2572 # plain keyword argument
2573 kwargs[param_name] = arg
2574
2575 return kwargs
2576
Yury Selivanovb907a512015-05-16 13:45:09 -04002577 def apply_defaults(self):
2578 """Set default values for missing arguments.
2579
2580 For variable-positional arguments (*args) the default is an
2581 empty tuple.
2582
2583 For variable-keyword arguments (**kwargs) the default is an
2584 empty dict.
2585 """
2586 arguments = self.arguments
Yury Selivanovb907a512015-05-16 13:45:09 -04002587 new_arguments = []
2588 for name, param in self._signature.parameters.items():
2589 try:
2590 new_arguments.append((name, arguments[name]))
2591 except KeyError:
2592 if param.default is not _empty:
2593 val = param.default
2594 elif param.kind is _VAR_POSITIONAL:
2595 val = ()
2596 elif param.kind is _VAR_KEYWORD:
2597 val = {}
2598 else:
2599 # This BoundArguments was likely produced by
2600 # Signature.bind_partial().
2601 continue
2602 new_arguments.append((name, val))
2603 self.arguments = OrderedDict(new_arguments)
2604
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002605 def __eq__(self, other):
Serhiy Storchaka2489bd52015-07-18 23:20:50 +03002606 if self is other:
2607 return True
Serhiy Storchaka3018cc42015-07-18 23:19:05 +03002608 if not isinstance(other, BoundArguments):
2609 return NotImplemented
2610 return (self.signature == other.signature and
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002611 self.arguments == other.arguments)
2612
Yury Selivanov6abe0322015-05-13 17:18:41 -04002613 def __setstate__(self, state):
2614 self._signature = state['_signature']
2615 self.arguments = state['arguments']
2616
2617 def __getstate__(self):
2618 return {'_signature': self._signature, 'arguments': self.arguments}
2619
Yury Selivanov3f6538f2015-05-14 18:47:17 -04002620 def __repr__(self):
2621 args = []
2622 for arg, value in self.arguments.items():
2623 args.append('{}={!r}'.format(arg, value))
Yury Selivanovf229bc52015-05-15 12:53:56 -04002624 return '<{} ({})>'.format(self.__class__.__name__, ', '.join(args))
Yury Selivanov3f6538f2015-05-14 18:47:17 -04002625
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002626
2627class Signature:
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002628 """A Signature object represents the overall signature of a function.
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002629 It stores a Parameter object for each parameter accepted by the
2630 function, as well as information specific to the function itself.
2631
2632 A Signature object has the following public attributes and methods:
2633
2634 * parameters : OrderedDict
2635 An ordered mapping of parameters' names to the corresponding
2636 Parameter objects (keyword-only arguments are in the same order
2637 as listed in `code.co_varnames`).
2638 * return_annotation : object
2639 The annotation for the return type of the function if specified.
2640 If the function has no annotation for its return type, this
Yury Selivanov8757ead2014-01-28 16:39:25 -05002641 attribute is set to `Signature.empty`.
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002642 * bind(*args, **kwargs) -> BoundArguments
2643 Creates a mapping from positional and keyword arguments to
2644 parameters.
2645 * bind_partial(*args, **kwargs) -> BoundArguments
2646 Creates a partial mapping from positional and keyword arguments
2647 to parameters (simulating 'functools.partial' behavior.)
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002648 """
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002649
2650 __slots__ = ('_return_annotation', '_parameters')
2651
2652 _parameter_cls = Parameter
2653 _bound_arguments_cls = BoundArguments
2654
2655 empty = _empty
2656
2657 def __init__(self, parameters=None, *, return_annotation=_empty,
2658 __validate_parameters__=True):
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002659 """Constructs Signature from the given list of Parameter
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002660 objects and 'return_annotation'. All arguments are optional.
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002661 """
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002662
2663 if parameters is None:
2664 params = OrderedDict()
2665 else:
2666 if __validate_parameters__:
2667 params = OrderedDict()
2668 top_kind = _POSITIONAL_ONLY
Yury Selivanov07a9e452014-01-29 10:58:16 -05002669 kind_defaults = False
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002670
2671 for idx, param in enumerate(parameters):
2672 kind = param.kind
Yury Selivanov2393dca2014-01-27 15:07:58 -05002673 name = param.name
2674
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002675 if kind < top_kind:
Yury Selivanov3f73ca22014-04-08 11:30:45 -04002676 msg = 'wrong parameter order: {!r} before {!r}'
Yury Selivanov2393dca2014-01-27 15:07:58 -05002677 msg = msg.format(top_kind, kind)
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002678 raise ValueError(msg)
Yury Selivanov07a9e452014-01-29 10:58:16 -05002679 elif kind > top_kind:
2680 kind_defaults = False
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002681 top_kind = kind
2682
Yury Selivanov3f73ca22014-04-08 11:30:45 -04002683 if kind in (_POSITIONAL_ONLY, _POSITIONAL_OR_KEYWORD):
Yury Selivanov07a9e452014-01-29 10:58:16 -05002684 if param.default is _empty:
2685 if kind_defaults:
2686 # No default for this parameter, but the
2687 # previous parameter of the same kind had
2688 # a default
2689 msg = 'non-default argument follows default ' \
2690 'argument'
2691 raise ValueError(msg)
2692 else:
2693 # There is a default for this parameter.
2694 kind_defaults = True
2695
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002696 if name in params:
2697 msg = 'duplicate parameter name: {!r}'.format(name)
2698 raise ValueError(msg)
Yury Selivanov2393dca2014-01-27 15:07:58 -05002699
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002700 params[name] = param
2701 else:
2702 params = OrderedDict(((param.name, param)
2703 for param in parameters))
2704
2705 self._parameters = types.MappingProxyType(params)
2706 self._return_annotation = return_annotation
2707
2708 @classmethod
2709 def from_function(cls, func):
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002710 """Constructs Signature for the given python function."""
Yury Selivanov57c74fc2015-05-20 23:07:02 -04002711
2712 warnings.warn("inspect.Signature.from_function() is deprecated, "
Berker Peksagb5601582015-05-21 23:40:54 +03002713 "use Signature.from_callable()",
2714 DeprecationWarning, stacklevel=2)
Yury Selivanovcf45f022015-05-20 14:38:50 -04002715 return _signature_from_function(cls, func)
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002716
Larry Hastings44e2eaa2013-11-23 15:37:55 -08002717 @classmethod
2718 def from_builtin(cls, func):
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002719 """Constructs Signature for the given builtin function."""
Yury Selivanov57c74fc2015-05-20 23:07:02 -04002720
2721 warnings.warn("inspect.Signature.from_builtin() is deprecated, "
Berker Peksagb5601582015-05-21 23:40:54 +03002722 "use Signature.from_callable()",
2723 DeprecationWarning, stacklevel=2)
Yury Selivanov57d240e2014-02-19 16:27:23 -05002724 return _signature_from_builtin(cls, func)
Larry Hastings44e2eaa2013-11-23 15:37:55 -08002725
Yury Selivanovda396452014-03-27 12:09:24 -04002726 @classmethod
Yury Selivanovbcd4fc12015-05-20 14:30:08 -04002727 def from_callable(cls, obj, *, follow_wrapped=True):
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002728 """Constructs Signature for the given callable object."""
Yury Selivanovbcd4fc12015-05-20 14:30:08 -04002729 return _signature_from_callable(obj, sigcls=cls,
2730 follow_wrapper_chains=follow_wrapped)
Yury Selivanovda396452014-03-27 12:09:24 -04002731
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002732 @property
2733 def parameters(self):
2734 return self._parameters
2735
2736 @property
2737 def return_annotation(self):
2738 return self._return_annotation
2739
2740 def replace(self, *, parameters=_void, return_annotation=_void):
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002741 """Creates a customized copy of the Signature.
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002742 Pass 'parameters' and/or 'return_annotation' arguments
2743 to override them in the new copy.
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002744 """
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002745
2746 if parameters is _void:
2747 parameters = self.parameters.values()
2748
2749 if return_annotation is _void:
2750 return_annotation = self._return_annotation
2751
2752 return type(self)(parameters,
2753 return_annotation=return_annotation)
2754
Yury Selivanov08d4a4f2014-09-12 15:48:02 -04002755 def _hash_basis(self):
2756 params = tuple(param for param in self.parameters.values()
2757 if param.kind != _KEYWORD_ONLY)
2758
2759 kwo_params = {param.name: param for param in self.parameters.values()
2760 if param.kind == _KEYWORD_ONLY}
2761
2762 return params, kwo_params, self.return_annotation
2763
Yury Selivanov67ae50e2014-04-08 11:46:50 -04002764 def __hash__(self):
Yury Selivanov08d4a4f2014-09-12 15:48:02 -04002765 params, kwo_params, return_annotation = self._hash_basis()
2766 kwo_params = frozenset(kwo_params.values())
2767 return hash((params, kwo_params, return_annotation))
Yury Selivanov67ae50e2014-04-08 11:46:50 -04002768
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002769 def __eq__(self, other):
Serhiy Storchaka2489bd52015-07-18 23:20:50 +03002770 if self is other:
2771 return True
Serhiy Storchaka3018cc42015-07-18 23:19:05 +03002772 if not isinstance(other, Signature):
2773 return NotImplemented
Serhiy Storchaka2489bd52015-07-18 23:20:50 +03002774 return self._hash_basis() == other._hash_basis()
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002775
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002776 def _bind(self, args, kwargs, *, partial=False):
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002777 """Private method. Don't use directly."""
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002778
2779 arguments = OrderedDict()
2780
2781 parameters = iter(self.parameters.values())
2782 parameters_ex = ()
2783 arg_vals = iter(args)
2784
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002785 while True:
2786 # Let's iterate through the positional arguments and corresponding
2787 # parameters
2788 try:
2789 arg_val = next(arg_vals)
2790 except StopIteration:
2791 # No more positional arguments
2792 try:
2793 param = next(parameters)
2794 except StopIteration:
2795 # No more parameters. That's it. Just need to check that
2796 # we have no `kwargs` after this while loop
2797 break
2798 else:
2799 if param.kind == _VAR_POSITIONAL:
2800 # That's OK, just empty *args. Let's start parsing
2801 # kwargs
2802 break
2803 elif param.name in kwargs:
2804 if param.kind == _POSITIONAL_ONLY:
2805 msg = '{arg!r} parameter is positional only, ' \
2806 'but was passed as a keyword'
2807 msg = msg.format(arg=param.name)
2808 raise TypeError(msg) from None
2809 parameters_ex = (param,)
2810 break
2811 elif (param.kind == _VAR_KEYWORD or
2812 param.default is not _empty):
2813 # That's fine too - we have a default value for this
2814 # parameter. So, lets start parsing `kwargs`, starting
2815 # with the current parameter
2816 parameters_ex = (param,)
2817 break
2818 else:
Yury Selivanov38b0d5a2014-01-28 17:27:39 -05002819 # No default, not VAR_KEYWORD, not VAR_POSITIONAL,
2820 # not in `kwargs`
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002821 if partial:
2822 parameters_ex = (param,)
2823 break
2824 else:
Yury Selivanov86872752015-05-19 00:27:49 -04002825 msg = 'missing a required argument: {arg!r}'
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002826 msg = msg.format(arg=param.name)
2827 raise TypeError(msg) from None
2828 else:
2829 # We have a positional argument to process
2830 try:
2831 param = next(parameters)
2832 except StopIteration:
2833 raise TypeError('too many positional arguments') from None
2834 else:
2835 if param.kind in (_VAR_KEYWORD, _KEYWORD_ONLY):
2836 # Looks like we have no parameter for this positional
2837 # argument
Yury Selivanov86872752015-05-19 00:27:49 -04002838 raise TypeError(
2839 'too many positional arguments') from None
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002840
2841 if param.kind == _VAR_POSITIONAL:
2842 # We have an '*args'-like argument, let's fill it with
2843 # all positional arguments we have left and move on to
2844 # the next phase
2845 values = [arg_val]
2846 values.extend(arg_vals)
2847 arguments[param.name] = tuple(values)
2848 break
2849
2850 if param.name in kwargs:
Yury Selivanov86872752015-05-19 00:27:49 -04002851 raise TypeError(
2852 'multiple values for argument {arg!r}'.format(
2853 arg=param.name)) from None
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002854
2855 arguments[param.name] = arg_val
2856
2857 # Now, we iterate through the remaining parameters to process
2858 # keyword arguments
2859 kwargs_param = None
2860 for param in itertools.chain(parameters_ex, parameters):
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002861 if param.kind == _VAR_KEYWORD:
2862 # Memorize that we have a '**kwargs'-like parameter
2863 kwargs_param = param
2864 continue
2865
Yury Selivanov38b0d5a2014-01-28 17:27:39 -05002866 if param.kind == _VAR_POSITIONAL:
2867 # Named arguments don't refer to '*args'-like parameters.
2868 # We only arrive here if the positional arguments ended
2869 # before reaching the last parameter before *args.
2870 continue
2871
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002872 param_name = param.name
2873 try:
2874 arg_val = kwargs.pop(param_name)
2875 except KeyError:
2876 # We have no value for this parameter. It's fine though,
2877 # if it has a default value, or it is an '*args'-like
2878 # parameter, left alone by the processing of positional
2879 # arguments.
2880 if (not partial and param.kind != _VAR_POSITIONAL and
2881 param.default is _empty):
Yury Selivanov86872752015-05-19 00:27:49 -04002882 raise TypeError('missing a required argument: {arg!r}'. \
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002883 format(arg=param_name)) from None
2884
2885 else:
Yury Selivanov9b9ac952014-01-28 20:54:28 -05002886 if param.kind == _POSITIONAL_ONLY:
2887 # This should never happen in case of a properly built
2888 # Signature object (but let's have this check here
2889 # to ensure correct behaviour just in case)
2890 raise TypeError('{arg!r} parameter is positional only, '
2891 'but was passed as a keyword'. \
2892 format(arg=param.name))
2893
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002894 arguments[param_name] = arg_val
2895
2896 if kwargs:
2897 if kwargs_param is not None:
2898 # Process our '**kwargs'-like parameter
2899 arguments[kwargs_param.name] = kwargs
2900 else:
Yury Selivanov86872752015-05-19 00:27:49 -04002901 raise TypeError(
2902 'got an unexpected keyword argument {arg!r}'.format(
2903 arg=next(iter(kwargs))))
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002904
2905 return self._bound_arguments_cls(self, arguments)
2906
Yury Selivanovc45873e2014-01-29 12:10:27 -05002907 def bind(*args, **kwargs):
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002908 """Get a BoundArguments object, that maps the passed `args`
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002909 and `kwargs` to the function's signature. Raises `TypeError`
2910 if the passed arguments can not be bound.
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002911 """
Yury Selivanovc45873e2014-01-29 12:10:27 -05002912 return args[0]._bind(args[1:], kwargs)
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002913
Yury Selivanovc45873e2014-01-29 12:10:27 -05002914 def bind_partial(*args, **kwargs):
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002915 """Get a BoundArguments object, that partially maps the
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002916 passed `args` and `kwargs` to the function's signature.
2917 Raises `TypeError` if the passed arguments can not be bound.
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002918 """
Yury Selivanovc45873e2014-01-29 12:10:27 -05002919 return args[0]._bind(args[1:], kwargs, partial=True)
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002920
Yury Selivanova5d63dd2014-03-27 11:31:43 -04002921 def __reduce__(self):
2922 return (type(self),
2923 (tuple(self._parameters.values()),),
2924 {'_return_annotation': self._return_annotation})
2925
2926 def __setstate__(self, state):
2927 self._return_annotation = state['_return_annotation']
2928
Yury Selivanov374375d2014-03-27 12:41:53 -04002929 def __repr__(self):
Yury Selivanovf229bc52015-05-15 12:53:56 -04002930 return '<{} {}>'.format(self.__class__.__name__, self)
Yury Selivanov374375d2014-03-27 12:41:53 -04002931
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002932 def __str__(self):
2933 result = []
Yury Selivanov2393dca2014-01-27 15:07:58 -05002934 render_pos_only_separator = False
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002935 render_kw_only_separator = True
Yury Selivanov2393dca2014-01-27 15:07:58 -05002936 for param in self.parameters.values():
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002937 formatted = str(param)
2938
2939 kind = param.kind
Yury Selivanov2393dca2014-01-27 15:07:58 -05002940
2941 if kind == _POSITIONAL_ONLY:
2942 render_pos_only_separator = True
2943 elif render_pos_only_separator:
2944 # It's not a positional-only parameter, and the flag
2945 # is set to 'True' (there were pos-only params before.)
2946 result.append('/')
2947 render_pos_only_separator = False
2948
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002949 if kind == _VAR_POSITIONAL:
2950 # OK, we have an '*args'-like parameter, so we won't need
2951 # a '*' to separate keyword-only arguments
2952 render_kw_only_separator = False
2953 elif kind == _KEYWORD_ONLY and render_kw_only_separator:
2954 # We have a keyword-only parameter to render and we haven't
2955 # rendered an '*args'-like parameter before, so add a '*'
2956 # separator to the parameters list ("foo(arg1, *, arg2)" case)
2957 result.append('*')
2958 # This condition should be only triggered once, so
2959 # reset the flag
2960 render_kw_only_separator = False
2961
2962 result.append(formatted)
2963
Yury Selivanov2393dca2014-01-27 15:07:58 -05002964 if render_pos_only_separator:
2965 # There were only positional-only parameters, hence the
2966 # flag was not reset to 'False'
2967 result.append('/')
2968
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002969 rendered = '({})'.format(', '.join(result))
2970
2971 if self.return_annotation is not _empty:
2972 anno = formatannotation(self.return_annotation)
2973 rendered += ' -> {}'.format(anno)
2974
2975 return rendered
Nick Coghlanf94a16b2013-09-22 22:46:49 +10002976
Yury Selivanovda396452014-03-27 12:09:24 -04002977
Yury Selivanovbcd4fc12015-05-20 14:30:08 -04002978def signature(obj, *, follow_wrapped=True):
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002979 """Get a signature object for the passed callable."""
Yury Selivanovbcd4fc12015-05-20 14:30:08 -04002980 return Signature.from_callable(obj, follow_wrapped=follow_wrapped)
Yury Selivanovda396452014-03-27 12:09:24 -04002981
2982
Nick Coghlanf94a16b2013-09-22 22:46:49 +10002983def _main():
2984 """ Logic for inspecting an object given at command line """
2985 import argparse
2986 import importlib
2987
2988 parser = argparse.ArgumentParser()
2989 parser.add_argument(
2990 'object',
2991 help="The object to be analysed. "
2992 "It supports the 'module:qualname' syntax")
2993 parser.add_argument(
2994 '-d', '--details', action='store_true',
2995 help='Display info about the module rather than its source code')
2996
2997 args = parser.parse_args()
2998
2999 target = args.object
3000 mod_name, has_attrs, attrs = target.partition(":")
3001 try:
3002 obj = module = importlib.import_module(mod_name)
3003 except Exception as exc:
3004 msg = "Failed to import {} ({}: {})".format(mod_name,
3005 type(exc).__name__,
3006 exc)
3007 print(msg, file=sys.stderr)
3008 exit(2)
3009
3010 if has_attrs:
3011 parts = attrs.split(".")
3012 obj = module
3013 for part in parts:
3014 obj = getattr(obj, part)
3015
3016 if module.__name__ in sys.builtin_module_names:
3017 print("Can't get info for builtin modules.", file=sys.stderr)
3018 exit(1)
3019
3020 if args.details:
3021 print('Target: {}'.format(target))
3022 print('Origin: {}'.format(getsourcefile(module)))
3023 print('Cached: {}'.format(module.__cached__))
3024 if obj is module:
3025 print('Loader: {}'.format(repr(module.__loader__)))
3026 if hasattr(module, '__path__'):
3027 print('Submodule search path: {}'.format(module.__path__))
3028 else:
3029 try:
3030 __, lineno = findsource(obj)
3031 except Exception:
3032 pass
3033 else:
3034 print('Line: {}'.format(lineno))
3035
3036 print('\n')
3037 else:
3038 print(getsource(obj))
3039
3040
3041if __name__ == "__main__":
3042 _main()