blob: e08e9f578eea50fa0d4fe50bccf74ecfb0af381f [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
Yury Selivanov4778e132016-11-08 12:23:09 -0500182 Coroutine functions are defined with "async def" syntax.
Yury Selivanov75445082015-05-11 22:57:16 -0400183 """
184 return bool((isfunction(object) or ismethod(object)) and
Yury Selivanov5376ba92015-06-22 12:19:30 -0400185 object.__code__.co_flags & CO_COROUTINE)
Yury Selivanov75445082015-05-11 22:57:16 -0400186
Yury Selivanoveb636452016-09-08 22:01:51 -0700187def isasyncgenfunction(object):
Yury Selivanov4778e132016-11-08 12:23:09 -0500188 """Return true if the object is an asynchronous generator function.
189
190 Asynchronous generator functions are defined with "async def"
191 syntax and have "yield" expressions in their body.
192 """
Yury Selivanoveb636452016-09-08 22:01:51 -0700193 return bool((isfunction(object) or ismethod(object)) and
194 object.__code__.co_flags & CO_ASYNC_GENERATOR)
195
196def isasyncgen(object):
Yury Selivanov4778e132016-11-08 12:23:09 -0500197 """Return true if the object is an asynchronous generator."""
Yury Selivanoveb636452016-09-08 22:01:51 -0700198 return isinstance(object, types.AsyncGeneratorType)
199
Christian Heimes7131fd92008-02-19 14:21:46 +0000200def isgenerator(object):
201 """Return true if the object is a generator.
202
203 Generator objects provide these attributes:
Ezio Melotti30b9d5d2013-08-17 15:50:46 +0300204 __iter__ defined to support iteration over container
Christian Heimes7131fd92008-02-19 14:21:46 +0000205 close raises a new GeneratorExit exception inside the
206 generator to terminate the iteration
207 gi_code code object
208 gi_frame frame object or possibly None once the generator has
209 been exhausted
210 gi_running set to 1 when generator is executing, 0 otherwise
211 next return the next item from the container
212 send resumes the generator and "sends" a value that becomes
213 the result of the current yield-expression
214 throw used to raise an exception inside the generator"""
Yury Selivanov5376ba92015-06-22 12:19:30 -0400215 return isinstance(object, types.GeneratorType)
Yury Selivanov75445082015-05-11 22:57:16 -0400216
217def iscoroutine(object):
218 """Return true if the object is a coroutine."""
Yury Selivanov5376ba92015-06-22 12:19:30 -0400219 return isinstance(object, types.CoroutineType)
Christian Heimes7131fd92008-02-19 14:21:46 +0000220
Yury Selivanovfdbeb2b2015-07-03 13:11:35 -0400221def isawaitable(object):
Yury Selivanovc0215df2016-11-08 19:57:44 -0500222 """Return true if object can be passed to an ``await`` expression."""
Yury Selivanovfdbeb2b2015-07-03 13:11:35 -0400223 return (isinstance(object, types.CoroutineType) or
224 isinstance(object, types.GeneratorType) and
Yury Selivanovc0215df2016-11-08 19:57:44 -0500225 bool(object.gi_code.co_flags & CO_ITERABLE_COROUTINE) or
Yury Selivanovfdbeb2b2015-07-03 13:11:35 -0400226 isinstance(object, collections.abc.Awaitable))
227
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000228def istraceback(object):
229 """Return true if the object is a traceback.
230
231 Traceback objects provide these attributes:
232 tb_frame frame object at this level
233 tb_lasti index of last attempted instruction in bytecode
234 tb_lineno current line number in Python source code
235 tb_next next inner traceback object (called by this level)"""
Tim Peters28bc59f2001-09-16 08:40:16 +0000236 return isinstance(object, types.TracebackType)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000237
238def isframe(object):
239 """Return true if the object is a frame object.
240
241 Frame objects provide these attributes:
242 f_back next outer frame object (this frame's caller)
243 f_builtins built-in namespace seen by this frame
244 f_code code object being executed in this frame
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000245 f_globals global namespace seen by this frame
246 f_lasti index of last attempted instruction in bytecode
247 f_lineno current line number in Python source code
248 f_locals local namespace seen by this frame
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000249 f_trace tracing function for this frame, or None"""
Tim Peters28bc59f2001-09-16 08:40:16 +0000250 return isinstance(object, types.FrameType)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000251
252def iscode(object):
253 """Return true if the object is a code object.
254
255 Code objects provide these attributes:
256 co_argcount number of arguments (not including * or ** args)
257 co_code string of raw compiled bytecode
258 co_consts tuple of constants used in the bytecode
259 co_filename name of file in which this code object was created
260 co_firstlineno number of first line in Python source code
261 co_flags bitmap: 1=optimized | 2=newlocals | 4=*arg | 8=**arg
262 co_lnotab encoded mapping of line numbers to bytecode indices
263 co_name name with which this code object was defined
264 co_names tuple of names of local variables
265 co_nlocals number of local variables
266 co_stacksize virtual machine stack space required
267 co_varnames tuple of names of arguments and local variables"""
Tim Peters28bc59f2001-09-16 08:40:16 +0000268 return isinstance(object, types.CodeType)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000269
270def isbuiltin(object):
271 """Return true if the object is a built-in function or method.
272
273 Built-in functions and methods provide these attributes:
274 __doc__ documentation string
275 __name__ original name of this function or method
276 __self__ instance to which a method is bound, or None"""
Tim Peters28bc59f2001-09-16 08:40:16 +0000277 return isinstance(object, types.BuiltinFunctionType)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000278
279def isroutine(object):
280 """Return true if the object is any kind of function or method."""
Tim Peters536d2262001-09-20 05:13:38 +0000281 return (isbuiltin(object)
282 or isfunction(object)
283 or ismethod(object)
284 or ismethoddescriptor(object))
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000285
Christian Heimesbe5b30b2008-03-03 19:18:51 +0000286def isabstract(object):
287 """Return true if the object is an abstract base class (ABC)."""
Benjamin Petersona0dfa822009-11-13 02:25:08 +0000288 return bool(isinstance(object, type) and object.__flags__ & TPFLAGS_IS_ABSTRACT)
Christian Heimesbe5b30b2008-03-03 19:18:51 +0000289
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000290def getmembers(object, predicate=None):
291 """Return all members of an object as (name, value) pairs sorted by name.
292 Optionally, only return members that satisfy a given predicate."""
Antoine Pitrou86a8a9a2011-12-21 09:57:40 +0100293 if isclass(object):
294 mro = (object,) + getmro(object)
295 else:
296 mro = ()
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000297 results = []
Ethan Furmane03ea372013-09-25 07:14:41 -0700298 processed = set()
299 names = dir(object)
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700300 # :dd any DynamicClassAttributes to the list of names if object is a class;
Ethan Furmane03ea372013-09-25 07:14:41 -0700301 # this may result in duplicate entries if, for example, a virtual
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700302 # attribute with the same name as a DynamicClassAttribute exists
Ethan Furmane03ea372013-09-25 07:14:41 -0700303 try:
304 for base in object.__bases__:
305 for k, v in base.__dict__.items():
306 if isinstance(v, types.DynamicClassAttribute):
307 names.append(k)
308 except AttributeError:
309 pass
310 for key in names:
Ethan Furman63c141c2013-10-18 00:27:39 -0700311 # First try to get the value via getattr. Some descriptors don't
312 # like calling their __get__ (see bug #1785), so fall back to
313 # looking in the __dict__.
314 try:
315 value = getattr(object, key)
316 # handle the duplicate key
317 if key in processed:
318 raise AttributeError
319 except AttributeError:
320 for base in mro:
321 if key in base.__dict__:
322 value = base.__dict__[key]
323 break
324 else:
325 # could be a (currently) missing slot member, or a buggy
326 # __dir__; discard and move on
Antoine Pitrou86a8a9a2011-12-21 09:57:40 +0100327 continue
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000328 if not predicate or predicate(value):
329 results.append((key, value))
Ethan Furmane03ea372013-09-25 07:14:41 -0700330 processed.add(key)
331 results.sort(key=lambda pair: pair[0])
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000332 return results
333
Christian Heimes25bb7832008-01-11 16:17:00 +0000334Attribute = namedtuple('Attribute', 'name kind defining_class object')
335
Tim Peters13b49d32001-09-23 02:00:29 +0000336def classify_class_attrs(cls):
337 """Return list of attribute-descriptor tuples.
338
339 For each name in dir(cls), the return list contains a 4-tuple
340 with these elements:
341
342 0. The name (a string).
343
344 1. The kind of attribute this is, one of these strings:
345 'class method' created via classmethod()
346 'static method' created via staticmethod()
347 'property' created via property()
Ethan Furmane03ea372013-09-25 07:14:41 -0700348 'method' any other flavor of method or descriptor
Tim Peters13b49d32001-09-23 02:00:29 +0000349 'data' not a method
350
351 2. The class which defined this attribute (a class).
352
Ethan Furmane03ea372013-09-25 07:14:41 -0700353 3. The object as obtained by calling getattr; if this fails, or if the
354 resulting object does not live anywhere in the class' mro (including
355 metaclasses) then the object is looked up in the defining class's
356 dict (found by walking the mro).
Ethan Furman668dede2013-09-14 18:53:26 -0700357
358 If one of the items in dir(cls) is stored in the metaclass it will now
359 be discovered and not have None be listed as the class in which it was
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700360 defined. Any items whose home class cannot be discovered are skipped.
Tim Peters13b49d32001-09-23 02:00:29 +0000361 """
362
363 mro = getmro(cls)
Ethan Furman668dede2013-09-14 18:53:26 -0700364 metamro = getmro(type(cls)) # for attributes stored in the metaclass
Ethan Furmane03ea372013-09-25 07:14:41 -0700365 metamro = tuple([cls for cls in metamro if cls not in (type, object)])
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700366 class_bases = (cls,) + mro
367 all_bases = class_bases + metamro
Tim Peters13b49d32001-09-23 02:00:29 +0000368 names = dir(cls)
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700369 # :dd any DynamicClassAttributes to the list of names;
Ethan Furmane03ea372013-09-25 07:14:41 -0700370 # this may result in duplicate entries if, for example, a virtual
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700371 # attribute with the same name as a DynamicClassAttribute exists.
Ethan Furman63c141c2013-10-18 00:27:39 -0700372 for base in mro:
Ethan Furmane03ea372013-09-25 07:14:41 -0700373 for k, v in base.__dict__.items():
374 if isinstance(v, types.DynamicClassAttribute):
375 names.append(k)
Tim Peters13b49d32001-09-23 02:00:29 +0000376 result = []
Ethan Furmane03ea372013-09-25 07:14:41 -0700377 processed = set()
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700378
Tim Peters13b49d32001-09-23 02:00:29 +0000379 for name in names:
Antoine Pitrou86a8a9a2011-12-21 09:57:40 +0100380 # Get the object associated with the name, and where it was defined.
Ethan Furmane03ea372013-09-25 07:14:41 -0700381 # Normal objects will be looked up with both getattr and directly in
382 # its class' dict (in case getattr fails [bug #1785], and also to look
383 # for a docstring).
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700384 # For DynamicClassAttributes on the second pass we only look in the
Ethan Furmane03ea372013-09-25 07:14:41 -0700385 # class's dict.
386 #
Tim Peters13b49d32001-09-23 02:00:29 +0000387 # Getting an obj from the __dict__ sometimes reveals more than
388 # using getattr. Static and class methods are dramatic examples.
Antoine Pitrou86a8a9a2011-12-21 09:57:40 +0100389 homecls = None
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700390 get_obj = None
391 dict_obj = None
Ethan Furmane03ea372013-09-25 07:14:41 -0700392 if name not in processed:
393 try:
Ethan Furmana8b07072013-10-18 01:22:08 -0700394 if name == '__dict__':
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700395 raise Exception("__dict__ is special, don't want the proxy")
Ethan Furmane03ea372013-09-25 07:14:41 -0700396 get_obj = getattr(cls, name)
397 except Exception as exc:
398 pass
399 else:
Ethan Furmane03ea372013-09-25 07:14:41 -0700400 homecls = getattr(get_obj, "__objclass__", homecls)
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700401 if homecls not in class_bases:
Ethan Furmane03ea372013-09-25 07:14:41 -0700402 # if the resulting object does not live somewhere in the
Ethan Furman63c141c2013-10-18 00:27:39 -0700403 # mro, drop it and search the mro manually
Ethan Furmane03ea372013-09-25 07:14:41 -0700404 homecls = None
Ethan Furman63c141c2013-10-18 00:27:39 -0700405 last_cls = None
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700406 # first look in the classes
407 for srch_cls in class_bases:
Ethan Furman63c141c2013-10-18 00:27:39 -0700408 srch_obj = getattr(srch_cls, name, None)
Yury Selivanovbf341fb2015-05-21 15:41:57 -0400409 if srch_obj is get_obj:
Ethan Furman63c141c2013-10-18 00:27:39 -0700410 last_cls = srch_cls
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700411 # then check the metaclasses
412 for srch_cls in metamro:
413 try:
414 srch_obj = srch_cls.__getattr__(cls, name)
415 except AttributeError:
416 continue
Yury Selivanovbf341fb2015-05-21 15:41:57 -0400417 if srch_obj is get_obj:
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700418 last_cls = srch_cls
Ethan Furman63c141c2013-10-18 00:27:39 -0700419 if last_cls is not None:
420 homecls = last_cls
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700421 for base in all_bases:
Ethan Furmane03ea372013-09-25 07:14:41 -0700422 if name in base.__dict__:
423 dict_obj = base.__dict__[name]
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700424 if homecls not in metamro:
425 homecls = base
Ethan Furmane03ea372013-09-25 07:14:41 -0700426 break
Ethan Furman63c141c2013-10-18 00:27:39 -0700427 if homecls is None:
428 # unable to locate the attribute anywhere, most likely due to
429 # buggy custom __dir__; discard and move on
430 continue
Yury Selivanovbf341fb2015-05-21 15:41:57 -0400431 obj = get_obj if get_obj is not None else dict_obj
Ethan Furmane03ea372013-09-25 07:14:41 -0700432 # Classify the object or its descriptor.
Ethan Furman63c141c2013-10-18 00:27:39 -0700433 if isinstance(dict_obj, staticmethod):
Tim Peters13b49d32001-09-23 02:00:29 +0000434 kind = "static method"
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700435 obj = dict_obj
Ethan Furman63c141c2013-10-18 00:27:39 -0700436 elif isinstance(dict_obj, classmethod):
Tim Peters13b49d32001-09-23 02:00:29 +0000437 kind = "class method"
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700438 obj = dict_obj
439 elif isinstance(dict_obj, property):
Tim Peters13b49d32001-09-23 02:00:29 +0000440 kind = "property"
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700441 obj = dict_obj
Yury Selivanov0860a0b2014-01-31 14:28:44 -0500442 elif isroutine(obj):
Tim Peters13b49d32001-09-23 02:00:29 +0000443 kind = "method"
Antoine Pitrou86a8a9a2011-12-21 09:57:40 +0100444 else:
Ethan Furmane03ea372013-09-25 07:14:41 -0700445 kind = "data"
Christian Heimes25bb7832008-01-11 16:17:00 +0000446 result.append(Attribute(name, kind, homecls, obj))
Ethan Furmane03ea372013-09-25 07:14:41 -0700447 processed.add(name)
Tim Peters13b49d32001-09-23 02:00:29 +0000448 return result
449
Tim Peterse0b2d7a2001-09-22 06:10:55 +0000450# ----------------------------------------------------------- class helpers
Tim Peterse0b2d7a2001-09-22 06:10:55 +0000451
452def getmro(cls):
453 "Return tuple of base classes (including cls) in method resolution order."
Benjamin Petersonb82c8e52010-11-04 00:38:49 +0000454 return cls.__mro__
Tim Peterse0b2d7a2001-09-22 06:10:55 +0000455
Nick Coghlane8c45d62013-07-28 20:00:01 +1000456# -------------------------------------------------------- function helpers
457
458def unwrap(func, *, stop=None):
459 """Get the object wrapped by *func*.
460
461 Follows the chain of :attr:`__wrapped__` attributes returning the last
462 object in the chain.
463
464 *stop* is an optional callback accepting an object in the wrapper chain
465 as its sole argument that allows the unwrapping to be terminated early if
466 the callback returns a true value. If the callback never returns a true
467 value, the last object in the chain is returned as usual. For example,
468 :func:`signature` uses this to stop unwrapping if any object in the
469 chain has a ``__signature__`` attribute defined.
470
471 :exc:`ValueError` is raised if a cycle is encountered.
472
473 """
474 if stop is None:
475 def _is_wrapper(f):
476 return hasattr(f, '__wrapped__')
477 else:
478 def _is_wrapper(f):
479 return hasattr(f, '__wrapped__') and not stop(f)
480 f = func # remember the original func for error reporting
481 memo = {id(f)} # Memoise by id to tolerate non-hashable objects
482 while _is_wrapper(func):
483 func = func.__wrapped__
484 id_func = id(func)
485 if id_func in memo:
486 raise ValueError('wrapper loop when unwrapping {!r}'.format(f))
487 memo.add(id_func)
488 return func
489
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000490# -------------------------------------------------- source code extraction
491def indentsize(line):
492 """Return the indent size, in spaces, at the start of a line of text."""
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000493 expline = line.expandtabs()
494 return len(expline) - len(expline.lstrip())
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000495
Serhiy Storchaka5cf2b7252015-04-03 22:38:53 +0300496def _findclass(func):
497 cls = sys.modules.get(func.__module__)
498 if cls is None:
499 return None
500 for name in func.__qualname__.split('.')[:-1]:
501 cls = getattr(cls, name)
502 if not isclass(cls):
503 return None
504 return cls
505
506def _finddoc(obj):
507 if isclass(obj):
508 for base in obj.__mro__:
509 if base is not object:
510 try:
511 doc = base.__doc__
512 except AttributeError:
513 continue
514 if doc is not None:
515 return doc
516 return None
517
518 if ismethod(obj):
519 name = obj.__func__.__name__
520 self = obj.__self__
521 if (isclass(self) and
522 getattr(getattr(self, name, None), '__func__') is obj.__func__):
523 # classmethod
524 cls = self
525 else:
526 cls = self.__class__
527 elif isfunction(obj):
528 name = obj.__name__
529 cls = _findclass(obj)
530 if cls is None or getattr(cls, name) is not obj:
531 return None
532 elif isbuiltin(obj):
533 name = obj.__name__
534 self = obj.__self__
535 if (isclass(self) and
536 self.__qualname__ + '.' + name == obj.__qualname__):
537 # classmethod
538 cls = self
539 else:
540 cls = self.__class__
Serhiy Storchakaac4bdcc2015-10-29 08:15:50 +0200541 # Should be tested before isdatadescriptor().
542 elif isinstance(obj, property):
543 func = obj.fget
544 name = func.__name__
545 cls = _findclass(func)
546 if cls is None or getattr(cls, name) is not obj:
547 return None
Serhiy Storchaka5cf2b7252015-04-03 22:38:53 +0300548 elif ismethoddescriptor(obj) or isdatadescriptor(obj):
549 name = obj.__name__
550 cls = obj.__objclass__
551 if getattr(cls, name) is not obj:
552 return None
Serhiy Storchaka5cf2b7252015-04-03 22:38:53 +0300553 else:
554 return None
555
556 for base in cls.__mro__:
557 try:
558 doc = getattr(base, name).__doc__
559 except AttributeError:
560 continue
561 if doc is not None:
562 return doc
563 return None
564
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000565def getdoc(object):
566 """Get the documentation string for an object.
567
568 All tabs are expanded to spaces. To clean up docstrings that are
569 indented to line up with blocks of code, any whitespace than can be
570 uniformly removed from the second line onwards is removed."""
Tim Peters24008312002-03-17 18:56:20 +0000571 try:
572 doc = object.__doc__
573 except AttributeError:
574 return None
Serhiy Storchaka5cf2b7252015-04-03 22:38:53 +0300575 if doc is None:
576 try:
577 doc = _finddoc(object)
578 except (AttributeError, TypeError):
579 return None
Guido van Rossum3172c5d2007-10-16 18:12:55 +0000580 if not isinstance(doc, str):
Tim Peters24008312002-03-17 18:56:20 +0000581 return None
Georg Brandl0c77a822008-06-10 16:37:50 +0000582 return cleandoc(doc)
583
584def cleandoc(doc):
585 """Clean up indentation from docstrings.
586
587 Any whitespace that can be uniformly removed from the second line
588 onwards is removed."""
Tim Peters24008312002-03-17 18:56:20 +0000589 try:
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000590 lines = doc.expandtabs().split('\n')
Tim Peters24008312002-03-17 18:56:20 +0000591 except UnicodeError:
592 return None
593 else:
Ka-Ping Yeea59ef7b2002-11-30 03:53:15 +0000594 # Find minimum indentation of any non-blank lines after first line.
Christian Heimesa37d4c62007-12-04 23:02:19 +0000595 margin = sys.maxsize
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000596 for line in lines[1:]:
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000597 content = len(line.lstrip())
Ka-Ping Yeea59ef7b2002-11-30 03:53:15 +0000598 if content:
599 indent = len(line) - content
600 margin = min(margin, indent)
601 # Remove indentation.
602 if lines:
603 lines[0] = lines[0].lstrip()
Christian Heimesa37d4c62007-12-04 23:02:19 +0000604 if margin < sys.maxsize:
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000605 for i in range(1, len(lines)): lines[i] = lines[i][margin:]
Ka-Ping Yeea59ef7b2002-11-30 03:53:15 +0000606 # Remove any trailing or leading blank lines.
607 while lines and not lines[-1]:
608 lines.pop()
609 while lines and not lines[0]:
610 lines.pop(0)
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000611 return '\n'.join(lines)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000612
613def getfile(object):
Ka-Ping Yeec113c242001-03-02 02:08:53 +0000614 """Work out which source or compiled file an object was defined in."""
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000615 if ismodule(object):
616 if hasattr(object, '__file__'):
617 return object.__file__
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +0000618 raise TypeError('{!r} is a built-in module'.format(object))
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000619 if isclass(object):
Yury Selivanov2eed8b72014-01-27 13:24:56 -0500620 if hasattr(object, '__module__'):
621 object = sys.modules.get(object.__module__)
622 if hasattr(object, '__file__'):
623 return object.__file__
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +0000624 raise TypeError('{!r} is a built-in class'.format(object))
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000625 if ismethod(object):
Christian Heimesff737952007-11-27 10:40:20 +0000626 object = object.__func__
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000627 if isfunction(object):
Neal Norwitz221085d2007-02-25 20:55:47 +0000628 object = object.__code__
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000629 if istraceback(object):
630 object = object.tb_frame
631 if isframe(object):
632 object = object.f_code
633 if iscode(object):
634 return object.co_filename
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +0000635 raise TypeError('{!r} is not a module, class, method, '
636 'function, traceback, frame, or code object'.format(object))
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000637
Ka-Ping Yee4d6fc7f2001-04-10 11:43:00 +0000638def getmodulename(path):
639 """Return the module name for a given file, or None."""
Nick Coghlan76e07702012-07-18 23:14:57 +1000640 fname = os.path.basename(path)
641 # Check for paths that look like an actual module file
642 suffixes = [(-len(suffix), suffix)
643 for suffix in importlib.machinery.all_suffixes()]
644 suffixes.sort() # try longest suffixes first, in case they overlap
645 for neglen, suffix in suffixes:
646 if fname.endswith(suffix):
647 return fname[:neglen]
648 return None
Ka-Ping Yee4d6fc7f2001-04-10 11:43:00 +0000649
Ka-Ping Yeec113c242001-03-02 02:08:53 +0000650def getsourcefile(object):
R. David Murraya1b37402010-06-17 02:04:29 +0000651 """Return the filename that can be used to locate an object's source.
652 Return None if no way can be identified to get the source.
653 """
Ka-Ping Yeec113c242001-03-02 02:08:53 +0000654 filename = getfile(object)
Brett Cannoncb66eb02012-05-11 12:58:42 -0400655 all_bytecode_suffixes = importlib.machinery.DEBUG_BYTECODE_SUFFIXES[:]
656 all_bytecode_suffixes += importlib.machinery.OPTIMIZED_BYTECODE_SUFFIXES[:]
657 if any(filename.endswith(s) for s in all_bytecode_suffixes):
658 filename = (os.path.splitext(filename)[0] +
659 importlib.machinery.SOURCE_SUFFIXES[0])
660 elif any(filename.endswith(s) for s in
661 importlib.machinery.EXTENSION_SUFFIXES):
662 return None
Thomas Wouters477c8d52006-05-27 19:21:47 +0000663 if os.path.exists(filename):
664 return filename
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000665 # only return a non-existent filename if the module has a PEP 302 loader
Brett Cannon4c14b5d2013-05-04 13:56:58 -0400666 if getattr(getmodule(object, filename), '__loader__', None) is not None:
Ka-Ping Yeec113c242001-03-02 02:08:53 +0000667 return filename
R. David Murraya1b37402010-06-17 02:04:29 +0000668 # or it is in the linecache
669 if filename in linecache.cache:
670 return filename
Ka-Ping Yeec113c242001-03-02 02:08:53 +0000671
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000672def getabsfile(object, _filename=None):
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000673 """Return an absolute path to the source or compiled file for an object.
Ka-Ping Yeec113c242001-03-02 02:08:53 +0000674
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000675 The idea is for each object to have a unique origin, so this routine
676 normalizes the result as much as possible."""
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000677 if _filename is None:
678 _filename = getsourcefile(object) or getfile(object)
679 return os.path.normcase(os.path.abspath(_filename))
Ka-Ping Yeec113c242001-03-02 02:08:53 +0000680
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000681modulesbyfile = {}
Thomas Wouters89f507f2006-12-13 04:49:30 +0000682_filesbymodname = {}
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000683
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000684def getmodule(object, _filename=None):
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000685 """Return the module an object was defined in, or None if not found."""
Ka-Ping Yee202c99b2001-04-13 09:15:08 +0000686 if ismodule(object):
687 return object
Johannes Gijsbers93245262004-09-11 15:53:22 +0000688 if hasattr(object, '__module__'):
Ka-Ping Yee8b58b842001-03-01 13:56:16 +0000689 return sys.modules.get(object.__module__)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000690 # Try the filename to modulename cache
691 if _filename is not None and _filename in modulesbyfile:
692 return sys.modules.get(modulesbyfile[_filename])
693 # Try the cache again with the absolute file name
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000694 try:
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000695 file = getabsfile(object, _filename)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000696 except TypeError:
697 return None
Raymond Hettinger54f02222002-06-01 14:18:47 +0000698 if file in modulesbyfile:
Ka-Ping Yeeb38bbbd2003-03-28 16:29:50 +0000699 return sys.modules.get(modulesbyfile[file])
Thomas Wouters89f507f2006-12-13 04:49:30 +0000700 # Update the filename to module name cache and check yet again
701 # Copy sys.modules in order to cope with changes while iterating
Éric Araujoa74f8ef2011-11-29 16:58:53 +0100702 for modname, module in list(sys.modules.items()):
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000703 if ismodule(module) and hasattr(module, '__file__'):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000704 f = module.__file__
705 if f == _filesbymodname.get(modname, None):
706 # Have already mapped this module, so skip it
707 continue
708 _filesbymodname[modname] = f
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000709 f = getabsfile(module)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000710 # Always map to the name the module knows itself by
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000711 modulesbyfile[f] = modulesbyfile[
712 os.path.realpath(f)] = module.__name__
Raymond Hettinger54f02222002-06-01 14:18:47 +0000713 if file in modulesbyfile:
Ka-Ping Yeeb38bbbd2003-03-28 16:29:50 +0000714 return sys.modules.get(modulesbyfile[file])
Thomas Wouters89f507f2006-12-13 04:49:30 +0000715 # Check the main module
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000716 main = sys.modules['__main__']
Brett Cannon4a671fe2003-06-15 22:33:28 +0000717 if not hasattr(object, '__name__'):
718 return None
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000719 if hasattr(main, object.__name__):
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000720 mainobject = getattr(main, object.__name__)
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000721 if mainobject is object:
722 return main
Thomas Wouters89f507f2006-12-13 04:49:30 +0000723 # Check builtins
Georg Brandl1a3284e2007-12-02 09:40:06 +0000724 builtin = sys.modules['builtins']
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000725 if hasattr(builtin, object.__name__):
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000726 builtinobject = getattr(builtin, object.__name__)
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000727 if builtinobject is object:
728 return builtin
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000729
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000730def findsource(object):
731 """Return the entire source file and starting line number for an object.
732
733 The argument may be a module, class, method, function, traceback, frame,
734 or code object. The source code is returned as a list of all the lines
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200735 in the file and the line number indexes a line in that list. An OSError
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000736 is raised if the source code cannot be retrieved."""
Benjamin Peterson9620cc02011-06-11 15:53:11 -0500737
Yury Selivanovef1e7502014-12-08 16:05:34 -0500738 file = getsourcefile(object)
739 if file:
740 # Invalidate cache if needed.
741 linecache.checkcache(file)
742 else:
743 file = getfile(object)
744 # Allow filenames in form of "<something>" to pass through.
745 # `doctest` monkeypatches `linecache` module to enable
746 # inspection, so let `linecache.getlines` to be called.
747 if not (file.startswith('<') and file.endswith('>')):
748 raise OSError('source code not available')
Benjamin Peterson9620cc02011-06-11 15:53:11 -0500749
Thomas Wouters89f507f2006-12-13 04:49:30 +0000750 module = getmodule(object, file)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000751 if module:
752 lines = linecache.getlines(file, module.__dict__)
753 else:
754 lines = linecache.getlines(file)
Neil Schemenauerf06f8532002-03-23 23:51:04 +0000755 if not lines:
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200756 raise OSError('could not get source code')
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000757
758 if ismodule(object):
759 return lines, 0
760
761 if isclass(object):
762 name = object.__name__
Thomas Wouters89f507f2006-12-13 04:49:30 +0000763 pat = re.compile(r'^(\s*)class\s*' + name + r'\b')
764 # make some effort to find the best matching class definition:
765 # use the one with the least indentation, which is the one
766 # that's most probably not inside a function definition.
767 candidates = []
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000768 for i in range(len(lines)):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000769 match = pat.match(lines[i])
770 if match:
771 # if it's at toplevel, it's already the best one
772 if lines[i][0] == 'c':
773 return lines, i
774 # else add whitespace to candidate list
775 candidates.append((match.group(1), i))
776 if candidates:
777 # this will sort by whitespace, and by line number,
778 # less whitespace first
779 candidates.sort()
780 return lines, candidates[0][1]
Jeremy Hyltonab919022003-06-27 18:41:20 +0000781 else:
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200782 raise OSError('could not find class definition')
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000783
784 if ismethod(object):
Christian Heimesff737952007-11-27 10:40:20 +0000785 object = object.__func__
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000786 if isfunction(object):
Neal Norwitz221085d2007-02-25 20:55:47 +0000787 object = object.__code__
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000788 if istraceback(object):
789 object = object.tb_frame
790 if isframe(object):
791 object = object.f_code
792 if iscode(object):
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000793 if not hasattr(object, 'co_firstlineno'):
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200794 raise OSError('could not find function definition')
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000795 lnum = object.co_firstlineno - 1
Yury Selivanove4e811d2015-07-21 19:01:52 +0300796 pat = re.compile(r'^(\s*def\s)|(\s*async\s+def\s)|(.*(?<!\w)lambda(:|\s))|^(\s*@)')
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000797 while lnum > 0:
Ka-Ping Yeea6e59712001-03-10 09:31:55 +0000798 if pat.match(lines[lnum]): break
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000799 lnum = lnum - 1
800 return lines, lnum
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200801 raise OSError('could not find code object')
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000802
803def getcomments(object):
Jeremy Hyltonb4c17c82002-03-28 23:01:56 +0000804 """Get lines of comments immediately preceding an object's source code.
805
806 Returns None when source can't be found.
807 """
808 try:
809 lines, lnum = findsource(object)
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200810 except (OSError, TypeError):
Jeremy Hyltonb4c17c82002-03-28 23:01:56 +0000811 return None
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000812
813 if ismodule(object):
814 # Look for a comment block at the top of the file.
815 start = 0
Ka-Ping Yeeb910efe2001-04-12 13:17:17 +0000816 if lines and lines[0][:2] == '#!': start = 1
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000817 while start < len(lines) and lines[start].strip() in ('', '#'):
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000818 start = start + 1
Ka-Ping Yeeb910efe2001-04-12 13:17:17 +0000819 if start < len(lines) and lines[start][:1] == '#':
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000820 comments = []
821 end = start
822 while end < len(lines) and lines[end][:1] == '#':
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000823 comments.append(lines[end].expandtabs())
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000824 end = end + 1
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000825 return ''.join(comments)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000826
827 # Look for a preceding block of comments at the same indentation.
828 elif lnum > 0:
829 indent = indentsize(lines[lnum])
830 end = lnum - 1
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000831 if end >= 0 and lines[end].lstrip()[:1] == '#' and \
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000832 indentsize(lines[end]) == indent:
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000833 comments = [lines[end].expandtabs().lstrip()]
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000834 if end > 0:
835 end = end - 1
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000836 comment = lines[end].expandtabs().lstrip()
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000837 while comment[:1] == '#' and indentsize(lines[end]) == indent:
838 comments[:0] = [comment]
839 end = end - 1
840 if end < 0: break
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000841 comment = lines[end].expandtabs().lstrip()
842 while comments and comments[0].strip() == '#':
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000843 comments[:1] = []
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000844 while comments and comments[-1].strip() == '#':
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000845 comments[-1:] = []
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000846 return ''.join(comments)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000847
Tim Peters4efb6e92001-06-29 23:51:08 +0000848class EndOfBlock(Exception): pass
849
850class BlockFinder:
851 """Provide a tokeneater() method to detect the end of a code block."""
852 def __init__(self):
853 self.indent = 0
Johannes Gijsbersa5855d52005-03-12 16:37:11 +0000854 self.islambda = False
Johannes Gijsbers1542f342004-12-12 16:46:28 +0000855 self.started = False
856 self.passline = False
Meador Inge5b718d72015-07-23 22:49:37 -0500857 self.indecorator = False
858 self.decoratorhasargs = False
Armin Rigodd5c0232005-09-25 11:45:45 +0000859 self.last = 1
Tim Peters4efb6e92001-06-29 23:51:08 +0000860
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000861 def tokeneater(self, type, token, srowcol, erowcol, line):
Meador Inge5b718d72015-07-23 22:49:37 -0500862 if not self.started and not self.indecorator:
863 # skip any decorators
864 if token == "@":
865 self.indecorator = True
Armin Rigodd5c0232005-09-25 11:45:45 +0000866 # look for the first "def", "class" or "lambda"
Meador Inge5b718d72015-07-23 22:49:37 -0500867 elif token in ("def", "class", "lambda"):
Johannes Gijsbersa5855d52005-03-12 16:37:11 +0000868 if token == "lambda":
869 self.islambda = True
Johannes Gijsbers1542f342004-12-12 16:46:28 +0000870 self.started = True
Armin Rigodd5c0232005-09-25 11:45:45 +0000871 self.passline = True # skip to the end of the line
Meador Inge5b718d72015-07-23 22:49:37 -0500872 elif token == "(":
873 if self.indecorator:
874 self.decoratorhasargs = True
875 elif token == ")":
876 if self.indecorator:
877 self.indecorator = False
878 self.decoratorhasargs = False
Tim Peters4efb6e92001-06-29 23:51:08 +0000879 elif type == tokenize.NEWLINE:
Armin Rigodd5c0232005-09-25 11:45:45 +0000880 self.passline = False # stop skipping when a NEWLINE is seen
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000881 self.last = srowcol[0]
Armin Rigodd5c0232005-09-25 11:45:45 +0000882 if self.islambda: # lambdas always end at the first NEWLINE
883 raise EndOfBlock
Meador Inge5b718d72015-07-23 22:49:37 -0500884 # hitting a NEWLINE when in a decorator without args
885 # ends the decorator
886 if self.indecorator and not self.decoratorhasargs:
887 self.indecorator = False
Johannes Gijsbers1542f342004-12-12 16:46:28 +0000888 elif self.passline:
889 pass
Tim Peters4efb6e92001-06-29 23:51:08 +0000890 elif type == tokenize.INDENT:
891 self.indent = self.indent + 1
Johannes Gijsbers1542f342004-12-12 16:46:28 +0000892 self.passline = True
Tim Peters4efb6e92001-06-29 23:51:08 +0000893 elif type == tokenize.DEDENT:
894 self.indent = self.indent - 1
Armin Rigodd5c0232005-09-25 11:45:45 +0000895 # the end of matching indent/dedent pairs end a block
896 # (note that this only works for "def"/"class" blocks,
897 # not e.g. for "if: else:" or "try: finally:" blocks)
898 if self.indent <= 0:
899 raise EndOfBlock
900 elif self.indent == 0 and type not in (tokenize.COMMENT, tokenize.NL):
901 # any other token on the same indentation level end the previous
902 # block as well, except the pseudo-tokens COMMENT and NL.
903 raise EndOfBlock
Tim Peters4efb6e92001-06-29 23:51:08 +0000904
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000905def getblock(lines):
906 """Extract the block of code at the top of the given list of lines."""
Armin Rigodd5c0232005-09-25 11:45:45 +0000907 blockfinder = BlockFinder()
Tim Peters4efb6e92001-06-29 23:51:08 +0000908 try:
Trent Nelson428de652008-03-18 22:41:35 +0000909 tokens = tokenize.generate_tokens(iter(lines).__next__)
910 for _token in tokens:
911 blockfinder.tokeneater(*_token)
Armin Rigodd5c0232005-09-25 11:45:45 +0000912 except (EndOfBlock, IndentationError):
913 pass
914 return lines[:blockfinder.last]
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000915
916def getsourcelines(object):
917 """Return a list of source lines and starting line number for an object.
918
919 The argument may be a module, class, method, function, traceback, frame,
920 or code object. The source code is returned as a list of the lines
921 corresponding to the object and the line number indicates where in the
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200922 original source file the first line of code was found. An OSError is
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000923 raised if the source code cannot be retrieved."""
Yury Selivanov081bbf62014-09-26 17:34:54 -0400924 object = unwrap(object)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000925 lines, lnum = findsource(object)
926
Meador Inge5b718d72015-07-23 22:49:37 -0500927 if ismodule(object):
928 return lines, 0
929 else:
930 return getblock(lines[lnum:]), lnum + 1
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000931
932def getsource(object):
933 """Return the text of the source code for an object.
934
935 The argument may be a module, class, method, function, traceback, frame,
936 or code object. The source code is returned as a single string. An
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200937 OSError is raised if the source code cannot be retrieved."""
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000938 lines, lnum = getsourcelines(object)
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000939 return ''.join(lines)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000940
941# --------------------------------------------------- class tree extraction
942def walktree(classes, children, parent):
943 """Recursive helper function for getclasstree()."""
944 results = []
Raymond Hettingera1a992c2005-03-11 06:46:45 +0000945 classes.sort(key=attrgetter('__module__', '__name__'))
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000946 for c in classes:
947 results.append((c, c.__bases__))
Raymond Hettinger54f02222002-06-01 14:18:47 +0000948 if c in children:
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000949 results.append(walktree(children[c], children, c))
950 return results
951
Georg Brandl5ce83a02009-06-01 17:23:51 +0000952def getclasstree(classes, unique=False):
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000953 """Arrange the given list of classes into a hierarchy of nested lists.
954
955 Where a nested list appears, it contains classes derived from the class
956 whose entry immediately precedes the list. Each entry is a 2-tuple
957 containing a class and a tuple of its base classes. If the 'unique'
958 argument is true, exactly one entry appears in the returned structure
959 for each class in the given list. Otherwise, classes using multiple
960 inheritance and their descendants will appear multiple times."""
961 children = {}
962 roots = []
963 for c in classes:
964 if c.__bases__:
965 for parent in c.__bases__:
Raymond Hettinger54f02222002-06-01 14:18:47 +0000966 if not parent in children:
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000967 children[parent] = []
Serhiy Storchaka362c1b52013-09-05 17:14:32 +0300968 if c not in children[parent]:
969 children[parent].append(c)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000970 if unique and parent in classes: break
971 elif c not in roots:
972 roots.append(c)
Raymond Hettingere0d49722002-06-02 18:55:56 +0000973 for parent in children:
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000974 if parent not in classes:
975 roots.append(parent)
976 return walktree(roots, children, None)
977
978# ------------------------------------------------ argument list extraction
Christian Heimes25bb7832008-01-11 16:17:00 +0000979Arguments = namedtuple('Arguments', 'args, varargs, varkw')
980
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000981def getargs(co):
982 """Get information about the arguments accepted by a code object.
983
Guido van Rossum2e65f892007-02-28 22:03:49 +0000984 Three things are returned: (args, varargs, varkw), where
Georg Brandlc1c4bf82010-10-15 16:07:41 +0000985 'args' is the list of argument names. Keyword-only arguments are
986 appended. 'varargs' and 'varkw' are the names of the * and **
987 arguments or None."""
Guido van Rossum2e65f892007-02-28 22:03:49 +0000988 args, varargs, kwonlyargs, varkw = _getfullargs(co)
Christian Heimes25bb7832008-01-11 16:17:00 +0000989 return Arguments(args + kwonlyargs, varargs, varkw)
Guido van Rossum2e65f892007-02-28 22:03:49 +0000990
991def _getfullargs(co):
992 """Get information about the arguments accepted by a code object.
993
994 Four things are returned: (args, varargs, kwonlyargs, varkw), where
Georg Brandlc1c4bf82010-10-15 16:07:41 +0000995 'args' and 'kwonlyargs' are lists of argument names, and 'varargs'
996 and 'varkw' are the names of the * and ** arguments or None."""
Jeremy Hylton64967882003-06-27 18:14:39 +0000997
998 if not iscode(co):
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +0000999 raise TypeError('{!r} is not a code object'.format(co))
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001000
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001001 nargs = co.co_argcount
1002 names = co.co_varnames
Guido van Rossum2e65f892007-02-28 22:03:49 +00001003 nkwargs = co.co_kwonlyargcount
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001004 args = list(names[:nargs])
Guido van Rossum2e65f892007-02-28 22:03:49 +00001005 kwonlyargs = list(names[nargs:nargs+nkwargs])
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001006 step = 0
1007
Guido van Rossum2e65f892007-02-28 22:03:49 +00001008 nargs += nkwargs
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001009 varargs = None
1010 if co.co_flags & CO_VARARGS:
1011 varargs = co.co_varnames[nargs]
1012 nargs = nargs + 1
1013 varkw = None
1014 if co.co_flags & CO_VARKEYWORDS:
1015 varkw = co.co_varnames[nargs]
Guido van Rossum2e65f892007-02-28 22:03:49 +00001016 return args, varargs, kwonlyargs, varkw
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001017
Yury Selivanov37dc2b22016-01-11 15:15:01 -05001018
1019ArgSpec = namedtuple('ArgSpec', 'args varargs keywords defaults')
1020
1021def getargspec(func):
Nick Coghlan3c35fdb2016-12-02 20:29:57 +10001022 """Get the names and default values of a function's parameters.
Yury Selivanov37dc2b22016-01-11 15:15:01 -05001023
1024 A tuple of four things is returned: (args, varargs, keywords, defaults).
1025 'args' is a list of the argument names, including keyword-only argument names.
Nick Coghlan3c35fdb2016-12-02 20:29:57 +10001026 'varargs' and 'keywords' are the names of the * and ** parameters or None.
1027 'defaults' is an n-tuple of the default values of the last n parameters.
Yury Selivanov37dc2b22016-01-11 15:15:01 -05001028
Nick Coghlan3c35fdb2016-12-02 20:29:57 +10001029 This function is deprecated, as it does not support annotations or
1030 keyword-only parameters and will raise ValueError if either is present
1031 on the supplied callable.
1032
1033 For a more structured introspection API, use inspect.signature() instead.
1034
1035 Alternatively, use getfullargspec() for an API with a similar namedtuple
1036 based interface, but full support for annotations and keyword-only
1037 parameters.
Yury Selivanov37dc2b22016-01-11 15:15:01 -05001038 """
1039 warnings.warn("inspect.getargspec() is deprecated, "
Nick Coghlan3c35fdb2016-12-02 20:29:57 +10001040 "use inspect.signature() or inspect.getfullargspec()",
1041 DeprecationWarning, stacklevel=2)
Yury Selivanov37dc2b22016-01-11 15:15:01 -05001042 args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults, ann = \
1043 getfullargspec(func)
1044 if kwonlyargs or ann:
Nick Coghlan3c35fdb2016-12-02 20:29:57 +10001045 raise ValueError("Function has keyword-only parameters or annotations"
Yury Selivanov37dc2b22016-01-11 15:15:01 -05001046 ", use getfullargspec() API which can support them")
1047 return ArgSpec(args, varargs, varkw, defaults)
1048
Christian Heimes25bb7832008-01-11 16:17:00 +00001049FullArgSpec = namedtuple('FullArgSpec',
Benjamin Peterson3d4ca742008-11-12 21:39:01 +00001050 'args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults, annotations')
Guido van Rossum2e65f892007-02-28 22:03:49 +00001051
1052def getfullargspec(func):
Nick Coghlan3c35fdb2016-12-02 20:29:57 +10001053 """Get the names and default values of a callable object's parameters.
Guido van Rossum2e65f892007-02-28 22:03:49 +00001054
Brett Cannon504d8852007-09-07 02:12:14 +00001055 A tuple of seven things is returned:
Nick Coghlan3c35fdb2016-12-02 20:29:57 +10001056 (args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults, annotations).
1057 'args' is a list of the parameter names.
1058 'varargs' and 'varkw' are the names of the * and ** parameters or None.
1059 'defaults' is an n-tuple of the default values of the last n parameters.
1060 'kwonlyargs' is a list of keyword-only parameter names.
Guido van Rossum2e65f892007-02-28 22:03:49 +00001061 'kwonlydefaults' is a dictionary mapping names from kwonlyargs to defaults.
Nick Coghlan3c35fdb2016-12-02 20:29:57 +10001062 'annotations' is a dictionary mapping parameter names to annotations.
Guido van Rossuma8add0e2007-05-14 22:03:55 +00001063
Nick Coghlan3c35fdb2016-12-02 20:29:57 +10001064 Notable differences from inspect.signature():
1065 - the "self" parameter is always reported, even for bound methods
1066 - wrapper chains defined by __wrapped__ *not* unwrapped automatically
Jeremy Hylton64967882003-06-27 18:14:39 +00001067 """
1068
Yury Selivanov57d240e2014-02-19 16:27:23 -05001069 try:
1070 # Re: `skip_bound_arg=False`
1071 #
Yury Selivanovd82eddc2014-01-29 11:24:39 -05001072 # There is a notable difference in behaviour between getfullargspec
1073 # and Signature: the former always returns 'self' parameter for bound
1074 # methods, whereas the Signature always shows the actual calling
1075 # signature of the passed object.
1076 #
1077 # To simulate this behaviour, we "unbind" bound methods, to trick
1078 # inspect.signature to always return their first parameter ("self",
1079 # usually)
Yury Selivanovd82eddc2014-01-29 11:24:39 -05001080
Yury Selivanov57d240e2014-02-19 16:27:23 -05001081 # Re: `follow_wrapper_chains=False`
1082 #
1083 # getfullargspec() historically ignored __wrapped__ attributes,
1084 # so we ensure that remains the case in 3.3+
Yury Selivanovd82eddc2014-01-29 11:24:39 -05001085
Yury Selivanov5a23bd02014-03-29 13:47:11 -04001086 sig = _signature_from_callable(func,
1087 follow_wrapper_chains=False,
1088 skip_bound_arg=False,
1089 sigcls=Signature)
Yury Selivanovd82eddc2014-01-29 11:24:39 -05001090 except Exception as ex:
1091 # Most of the times 'signature' will raise ValueError.
1092 # But, it can also raise AttributeError, and, maybe something
1093 # else. So to be fully backwards compatible, we catch all
1094 # possible exceptions here, and reraise a TypeError.
1095 raise TypeError('unsupported callable') from ex
1096
1097 args = []
1098 varargs = None
1099 varkw = None
1100 kwonlyargs = []
1101 defaults = ()
1102 annotations = {}
1103 defaults = ()
1104 kwdefaults = {}
1105
1106 if sig.return_annotation is not sig.empty:
1107 annotations['return'] = sig.return_annotation
1108
1109 for param in sig.parameters.values():
1110 kind = param.kind
1111 name = param.name
1112
1113 if kind is _POSITIONAL_ONLY:
1114 args.append(name)
1115 elif kind is _POSITIONAL_OR_KEYWORD:
1116 args.append(name)
1117 if param.default is not param.empty:
1118 defaults += (param.default,)
1119 elif kind is _VAR_POSITIONAL:
1120 varargs = name
1121 elif kind is _KEYWORD_ONLY:
1122 kwonlyargs.append(name)
1123 if param.default is not param.empty:
1124 kwdefaults[name] = param.default
1125 elif kind is _VAR_KEYWORD:
1126 varkw = name
1127
1128 if param.annotation is not param.empty:
1129 annotations[name] = param.annotation
1130
1131 if not kwdefaults:
1132 # compatibility with 'func.__kwdefaults__'
1133 kwdefaults = None
1134
1135 if not defaults:
1136 # compatibility with 'func.__defaults__'
1137 defaults = None
1138
Yury Selivanovd82eddc2014-01-29 11:24:39 -05001139 return FullArgSpec(args, varargs, varkw, defaults,
1140 kwonlyargs, kwdefaults, annotations)
1141
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001142
Christian Heimes25bb7832008-01-11 16:17:00 +00001143ArgInfo = namedtuple('ArgInfo', 'args varargs keywords locals')
1144
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001145def getargvalues(frame):
1146 """Get information about arguments passed into a particular frame.
1147
1148 A tuple of four things is returned: (args, varargs, varkw, locals).
Georg Brandlc1c4bf82010-10-15 16:07:41 +00001149 'args' is a list of the argument names.
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001150 'varargs' and 'varkw' are the names of the * and ** arguments or None.
1151 'locals' is the locals dictionary of the given frame."""
1152 args, varargs, varkw = getargs(frame.f_code)
Benjamin Peterson1a6e0d02008-10-25 15:49:17 +00001153 return ArgInfo(args, varargs, varkw, frame.f_locals)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001154
Guido van Rossum2e65f892007-02-28 22:03:49 +00001155def formatannotation(annotation, base_module=None):
Guido van Rossum52e50042016-10-22 07:55:18 -07001156 if getattr(annotation, '__module__', None) == 'typing':
1157 return repr(annotation).replace('typing.', '')
Guido van Rossum2e65f892007-02-28 22:03:49 +00001158 if isinstance(annotation, type):
Georg Brandl1a3284e2007-12-02 09:40:06 +00001159 if annotation.__module__ in ('builtins', base_module):
Serhiy Storchaka521e5862014-07-22 15:00:37 +03001160 return annotation.__qualname__
1161 return annotation.__module__+'.'+annotation.__qualname__
Guido van Rossum2e65f892007-02-28 22:03:49 +00001162 return repr(annotation)
Guido van Rossuma8add0e2007-05-14 22:03:55 +00001163
Guido van Rossum2e65f892007-02-28 22:03:49 +00001164def formatannotationrelativeto(object):
Guido van Rossuma8add0e2007-05-14 22:03:55 +00001165 module = getattr(object, '__module__', None)
1166 def _formatannotation(annotation):
1167 return formatannotation(annotation, module)
1168 return _formatannotation
Guido van Rossum2e65f892007-02-28 22:03:49 +00001169
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001170def formatargspec(args, varargs=None, varkw=None, defaults=None,
Guido van Rossum2e65f892007-02-28 22:03:49 +00001171 kwonlyargs=(), kwonlydefaults={}, annotations={},
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001172 formatarg=str,
1173 formatvarargs=lambda name: '*' + name,
1174 formatvarkw=lambda name: '**' + name,
1175 formatvalue=lambda value: '=' + repr(value),
Guido van Rossum2e65f892007-02-28 22:03:49 +00001176 formatreturns=lambda text: ' -> ' + text,
Georg Brandlc1c4bf82010-10-15 16:07:41 +00001177 formatannotation=formatannotation):
Berker Peksagfa3922c2015-07-31 04:11:29 +03001178 """Format an argument spec from the values returned by getfullargspec.
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001179
Guido van Rossum2e65f892007-02-28 22:03:49 +00001180 The first seven arguments are (args, varargs, varkw, defaults,
1181 kwonlyargs, kwonlydefaults, annotations). The other five arguments
1182 are the corresponding optional formatting functions that are called to
1183 turn names and values into strings. The last argument is an optional
1184 function to format the sequence of arguments."""
1185 def formatargandannotation(arg):
1186 result = formatarg(arg)
1187 if arg in annotations:
1188 result += ': ' + formatannotation(annotations[arg])
1189 return result
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001190 specs = []
1191 if defaults:
1192 firstdefault = len(args) - len(defaults)
Benjamin Petersonb58dda72009-01-18 22:27:04 +00001193 for i, arg in enumerate(args):
Georg Brandlc1c4bf82010-10-15 16:07:41 +00001194 spec = formatargandannotation(arg)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001195 if defaults and i >= firstdefault:
1196 spec = spec + formatvalue(defaults[i - firstdefault])
1197 specs.append(spec)
Raymond Hettinger936654b2002-06-01 03:06:31 +00001198 if varargs is not None:
Guido van Rossum2e65f892007-02-28 22:03:49 +00001199 specs.append(formatvarargs(formatargandannotation(varargs)))
1200 else:
1201 if kwonlyargs:
1202 specs.append('*')
1203 if kwonlyargs:
1204 for kwonlyarg in kwonlyargs:
1205 spec = formatargandannotation(kwonlyarg)
Benjamin Peterson9953a8d2009-01-17 04:15:01 +00001206 if kwonlydefaults and kwonlyarg in kwonlydefaults:
Guido van Rossum2e65f892007-02-28 22:03:49 +00001207 spec += formatvalue(kwonlydefaults[kwonlyarg])
1208 specs.append(spec)
Raymond Hettinger936654b2002-06-01 03:06:31 +00001209 if varkw is not None:
Guido van Rossum2e65f892007-02-28 22:03:49 +00001210 specs.append(formatvarkw(formatargandannotation(varkw)))
Neal Norwitz9d72bb42007-04-17 08:48:32 +00001211 result = '(' + ', '.join(specs) + ')'
Guido van Rossum2e65f892007-02-28 22:03:49 +00001212 if 'return' in annotations:
1213 result += formatreturns(formatannotation(annotations['return']))
1214 return result
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001215
1216def formatargvalues(args, varargs, varkw, locals,
1217 formatarg=str,
1218 formatvarargs=lambda name: '*' + name,
1219 formatvarkw=lambda name: '**' + name,
Georg Brandlc1c4bf82010-10-15 16:07:41 +00001220 formatvalue=lambda value: '=' + repr(value)):
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001221 """Format an argument spec from the 4 values returned by getargvalues.
1222
1223 The first four arguments are (args, varargs, varkw, locals). The
1224 next four arguments are the corresponding optional formatting functions
1225 that are called to turn names and values into strings. The ninth
1226 argument is an optional function to format the sequence of arguments."""
1227 def convert(name, locals=locals,
1228 formatarg=formatarg, formatvalue=formatvalue):
1229 return formatarg(name) + formatvalue(locals[name])
1230 specs = []
1231 for i in range(len(args)):
Georg Brandlc1c4bf82010-10-15 16:07:41 +00001232 specs.append(convert(args[i]))
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001233 if varargs:
1234 specs.append(formatvarargs(varargs) + formatvalue(locals[varargs]))
1235 if varkw:
1236 specs.append(formatvarkw(varkw) + formatvalue(locals[varkw]))
Neal Norwitz9d72bb42007-04-17 08:48:32 +00001237 return '(' + ', '.join(specs) + ')'
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001238
Benjamin Petersone109c702011-06-24 09:37:26 -05001239def _missing_arguments(f_name, argnames, pos, values):
1240 names = [repr(name) for name in argnames if name not in values]
1241 missing = len(names)
1242 if missing == 1:
1243 s = names[0]
1244 elif missing == 2:
1245 s = "{} and {}".format(*names)
1246 else:
Yury Selivanovdccfa132014-03-27 18:42:52 -04001247 tail = ", {} and {}".format(*names[-2:])
Benjamin Petersone109c702011-06-24 09:37:26 -05001248 del names[-2:]
1249 s = ", ".join(names) + tail
1250 raise TypeError("%s() missing %i required %s argument%s: %s" %
1251 (f_name, missing,
1252 "positional" if pos else "keyword-only",
1253 "" if missing == 1 else "s", s))
1254
1255def _too_many(f_name, args, kwonly, varargs, defcount, given, values):
Benjamin Petersonb204a422011-06-05 22:04:07 -05001256 atleast = len(args) - defcount
Benjamin Petersonb204a422011-06-05 22:04:07 -05001257 kwonly_given = len([arg for arg in kwonly if arg in values])
1258 if varargs:
1259 plural = atleast != 1
1260 sig = "at least %d" % (atleast,)
1261 elif defcount:
1262 plural = True
1263 sig = "from %d to %d" % (atleast, len(args))
1264 else:
1265 plural = len(args) != 1
1266 sig = str(len(args))
1267 kwonly_sig = ""
1268 if kwonly_given:
1269 msg = " positional argument%s (and %d keyword-only argument%s)"
1270 kwonly_sig = (msg % ("s" if given != 1 else "", kwonly_given,
1271 "s" if kwonly_given != 1 else ""))
1272 raise TypeError("%s() takes %s positional argument%s but %d%s %s given" %
1273 (f_name, sig, "s" if plural else "", given, kwonly_sig,
1274 "was" if given == 1 and not kwonly_given else "were"))
1275
Benjamin Peterson3e6ab172014-01-02 12:24:08 -06001276def getcallargs(*func_and_positional, **named):
Benjamin Peterson25cd7eb2010-03-30 18:42:32 +00001277 """Get the mapping of arguments to values.
1278
1279 A dict is returned, with keys the function argument names (including the
1280 names of the * and ** arguments, if any), and values the respective bound
1281 values from 'positional' and 'named'."""
Benjamin Peterson3e6ab172014-01-02 12:24:08 -06001282 func = func_and_positional[0]
1283 positional = func_and_positional[1:]
Benjamin Peterson25cd7eb2010-03-30 18:42:32 +00001284 spec = getfullargspec(func)
1285 args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults, ann = spec
1286 f_name = func.__name__
1287 arg2value = {}
1288
Benjamin Petersonb204a422011-06-05 22:04:07 -05001289
Benjamin Peterson25cd7eb2010-03-30 18:42:32 +00001290 if ismethod(func) and func.__self__ is not None:
1291 # implicit 'self' (or 'cls' for classmethods) argument
1292 positional = (func.__self__,) + positional
1293 num_pos = len(positional)
Benjamin Peterson25cd7eb2010-03-30 18:42:32 +00001294 num_args = len(args)
1295 num_defaults = len(defaults) if defaults else 0
Benjamin Peterson25cd7eb2010-03-30 18:42:32 +00001296
Benjamin Petersonb204a422011-06-05 22:04:07 -05001297 n = min(num_pos, num_args)
1298 for i in range(n):
1299 arg2value[args[i]] = positional[i]
1300 if varargs:
1301 arg2value[varargs] = tuple(positional[n:])
1302 possible_kwargs = set(args + kwonlyargs)
Benjamin Peterson25cd7eb2010-03-30 18:42:32 +00001303 if varkw:
Benjamin Petersonb204a422011-06-05 22:04:07 -05001304 arg2value[varkw] = {}
1305 for kw, value in named.items():
1306 if kw not in possible_kwargs:
1307 if not varkw:
1308 raise TypeError("%s() got an unexpected keyword argument %r" %
1309 (f_name, kw))
1310 arg2value[varkw][kw] = value
1311 continue
1312 if kw in arg2value:
1313 raise TypeError("%s() got multiple values for argument %r" %
1314 (f_name, kw))
1315 arg2value[kw] = value
1316 if num_pos > num_args and not varargs:
Benjamin Petersone109c702011-06-24 09:37:26 -05001317 _too_many(f_name, args, kwonlyargs, varargs, num_defaults,
1318 num_pos, arg2value)
Benjamin Petersonb204a422011-06-05 22:04:07 -05001319 if num_pos < num_args:
Benjamin Petersone109c702011-06-24 09:37:26 -05001320 req = args[:num_args - num_defaults]
1321 for arg in req:
Benjamin Petersonb204a422011-06-05 22:04:07 -05001322 if arg not in arg2value:
Benjamin Petersone109c702011-06-24 09:37:26 -05001323 _missing_arguments(f_name, req, True, arg2value)
Benjamin Petersonb204a422011-06-05 22:04:07 -05001324 for i, arg in enumerate(args[num_args - num_defaults:]):
1325 if arg not in arg2value:
1326 arg2value[arg] = defaults[i]
Benjamin Petersone109c702011-06-24 09:37:26 -05001327 missing = 0
Benjamin Petersonb204a422011-06-05 22:04:07 -05001328 for kwarg in kwonlyargs:
1329 if kwarg not in arg2value:
Yury Selivanov875df202014-03-27 18:23:03 -04001330 if kwonlydefaults and kwarg in kwonlydefaults:
Benjamin Petersone109c702011-06-24 09:37:26 -05001331 arg2value[kwarg] = kwonlydefaults[kwarg]
1332 else:
1333 missing += 1
1334 if missing:
1335 _missing_arguments(f_name, kwonlyargs, False, arg2value)
Benjamin Peterson25cd7eb2010-03-30 18:42:32 +00001336 return arg2value
1337
Nick Coghlan2f92e542012-06-23 19:39:55 +10001338ClosureVars = namedtuple('ClosureVars', 'nonlocals globals builtins unbound')
1339
1340def getclosurevars(func):
1341 """
1342 Get the mapping of free variables to their current values.
1343
Meador Inge8fda3592012-07-19 21:33:21 -05001344 Returns a named tuple of dicts mapping the current nonlocal, global
Nick Coghlan2f92e542012-06-23 19:39:55 +10001345 and builtin references as seen by the body of the function. A final
1346 set of unbound names that could not be resolved is also provided.
1347 """
1348
1349 if ismethod(func):
1350 func = func.__func__
1351
1352 if not isfunction(func):
1353 raise TypeError("'{!r}' is not a Python function".format(func))
1354
1355 code = func.__code__
1356 # Nonlocal references are named in co_freevars and resolved
1357 # by looking them up in __closure__ by positional index
1358 if func.__closure__ is None:
1359 nonlocal_vars = {}
1360 else:
1361 nonlocal_vars = {
1362 var : cell.cell_contents
1363 for var, cell in zip(code.co_freevars, func.__closure__)
1364 }
1365
1366 # Global and builtin references are named in co_names and resolved
1367 # by looking them up in __globals__ or __builtins__
1368 global_ns = func.__globals__
1369 builtin_ns = global_ns.get("__builtins__", builtins.__dict__)
1370 if ismodule(builtin_ns):
1371 builtin_ns = builtin_ns.__dict__
1372 global_vars = {}
1373 builtin_vars = {}
1374 unbound_names = set()
1375 for name in code.co_names:
1376 if name in ("None", "True", "False"):
1377 # Because these used to be builtins instead of keywords, they
1378 # may still show up as name references. We ignore them.
1379 continue
1380 try:
1381 global_vars[name] = global_ns[name]
1382 except KeyError:
1383 try:
1384 builtin_vars[name] = builtin_ns[name]
1385 except KeyError:
1386 unbound_names.add(name)
1387
1388 return ClosureVars(nonlocal_vars, global_vars,
1389 builtin_vars, unbound_names)
1390
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001391# -------------------------------------------------- stack frame extraction
Christian Heimes25bb7832008-01-11 16:17:00 +00001392
1393Traceback = namedtuple('Traceback', 'filename lineno function code_context index')
1394
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001395def getframeinfo(frame, context=1):
1396 """Get information about a frame or traceback object.
1397
1398 A tuple of five things is returned: the filename, the line number of
1399 the current line, the function name, a list of lines of context from
1400 the source code, and the index of the current line within that list.
1401 The optional second argument specifies the number of lines of context
1402 to return, which are centered around the current line."""
1403 if istraceback(frame):
Andrew M. Kuchlingba8b6bc2004-06-05 14:11:59 +00001404 lineno = frame.tb_lineno
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001405 frame = frame.tb_frame
Andrew M. Kuchlingba8b6bc2004-06-05 14:11:59 +00001406 else:
1407 lineno = frame.f_lineno
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001408 if not isframe(frame):
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00001409 raise TypeError('{!r} is not a frame or traceback object'.format(frame))
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001410
Neil Schemenauerf06f8532002-03-23 23:51:04 +00001411 filename = getsourcefile(frame) or getfile(frame)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001412 if context > 0:
Guido van Rossum54e54c62001-09-04 19:14:14 +00001413 start = lineno - 1 - context//2
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001414 try:
1415 lines, lnum = findsource(frame)
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02001416 except OSError:
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +00001417 lines = index = None
1418 else:
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001419 start = max(start, 1)
Raymond Hettingera0501712004-06-15 11:22:53 +00001420 start = max(0, min(start, len(lines) - context))
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001421 lines = lines[start:start+context]
Ka-Ping Yee59ade082001-03-01 03:55:35 +00001422 index = lineno - 1 - start
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001423 else:
1424 lines = index = None
1425
Christian Heimes25bb7832008-01-11 16:17:00 +00001426 return Traceback(filename, lineno, frame.f_code.co_name, lines, index)
Ka-Ping Yee59ade082001-03-01 03:55:35 +00001427
1428def getlineno(frame):
1429 """Get the line number from a frame object, allowing for optimization."""
Michael W. Hudsondd32a912002-08-15 14:59:02 +00001430 # FrameType.f_lineno is now a descriptor that grovels co_lnotab
1431 return frame.f_lineno
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001432
Antoine Pitroucdcafb72014-08-24 10:50:28 -04001433FrameInfo = namedtuple('FrameInfo', ('frame',) + Traceback._fields)
1434
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001435def getouterframes(frame, context=1):
1436 """Get a list of records for a frame and all higher (calling) frames.
1437
1438 Each record contains a frame object, filename, line number, function
1439 name, a list of lines of context, and index within the context."""
1440 framelist = []
1441 while frame:
Antoine Pitroucdcafb72014-08-24 10:50:28 -04001442 frameinfo = (frame,) + getframeinfo(frame, context)
1443 framelist.append(FrameInfo(*frameinfo))
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001444 frame = frame.f_back
1445 return framelist
1446
1447def getinnerframes(tb, context=1):
1448 """Get a list of records for a traceback's frame and all lower frames.
1449
1450 Each record contains a frame object, filename, line number, function
1451 name, a list of lines of context, and index within the context."""
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001452 framelist = []
1453 while tb:
Antoine Pitroucdcafb72014-08-24 10:50:28 -04001454 frameinfo = (tb.tb_frame,) + getframeinfo(tb, context)
1455 framelist.append(FrameInfo(*frameinfo))
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001456 tb = tb.tb_next
1457 return framelist
1458
Benjamin Peterson42ac4752010-08-09 13:05:35 +00001459def currentframe():
Benjamin Petersona3a3fc62010-08-09 15:49:56 +00001460 """Return the frame of the caller or None if this is not possible."""
Benjamin Peterson42ac4752010-08-09 13:05:35 +00001461 return sys._getframe(1) if hasattr(sys, "_getframe") else None
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001462
1463def stack(context=1):
1464 """Return a list of records for the stack above the caller's frame."""
Jeremy Hyltonab919022003-06-27 18:41:20 +00001465 return getouterframes(sys._getframe(1), context)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001466
1467def trace(context=1):
Tim Peters85ba6732001-02-28 08:26:44 +00001468 """Return a list of records for the stack below the current exception."""
Fred Draked451ec12002-04-26 02:29:55 +00001469 return getinnerframes(sys.exc_info()[2], context)
Michael Foord95fc51d2010-11-20 15:07:30 +00001470
1471
1472# ------------------------------------------------ static version of getattr
1473
1474_sentinel = object()
1475
Michael Foorde5162652010-11-20 16:40:44 +00001476def _static_getmro(klass):
1477 return type.__dict__['__mro__'].__get__(klass)
1478
Michael Foord95fc51d2010-11-20 15:07:30 +00001479def _check_instance(obj, attr):
1480 instance_dict = {}
1481 try:
1482 instance_dict = object.__getattribute__(obj, "__dict__")
1483 except AttributeError:
1484 pass
Michael Foorddcebe0f2011-03-15 19:20:44 -04001485 return dict.get(instance_dict, attr, _sentinel)
Michael Foord95fc51d2010-11-20 15:07:30 +00001486
1487
1488def _check_class(klass, attr):
Michael Foorde5162652010-11-20 16:40:44 +00001489 for entry in _static_getmro(klass):
Michael Foorda51623b2011-12-18 22:01:40 +00001490 if _shadowed_dict(type(entry)) is _sentinel:
Michael Foorddcebe0f2011-03-15 19:20:44 -04001491 try:
1492 return entry.__dict__[attr]
1493 except KeyError:
1494 pass
Michael Foord95fc51d2010-11-20 15:07:30 +00001495 return _sentinel
1496
Michael Foord35184ed2010-11-20 16:58:30 +00001497def _is_type(obj):
1498 try:
1499 _static_getmro(obj)
1500 except TypeError:
1501 return False
1502 return True
1503
Michael Foorddcebe0f2011-03-15 19:20:44 -04001504def _shadowed_dict(klass):
1505 dict_attr = type.__dict__["__dict__"]
1506 for entry in _static_getmro(klass):
1507 try:
1508 class_dict = dict_attr.__get__(entry)["__dict__"]
1509 except KeyError:
1510 pass
1511 else:
1512 if not (type(class_dict) is types.GetSetDescriptorType and
1513 class_dict.__name__ == "__dict__" and
1514 class_dict.__objclass__ is entry):
Michael Foorda51623b2011-12-18 22:01:40 +00001515 return class_dict
1516 return _sentinel
Michael Foord95fc51d2010-11-20 15:07:30 +00001517
1518def getattr_static(obj, attr, default=_sentinel):
1519 """Retrieve attributes without triggering dynamic lookup via the
1520 descriptor protocol, __getattr__ or __getattribute__.
1521
1522 Note: this function may not be able to retrieve all attributes
1523 that getattr can fetch (like dynamically created attributes)
1524 and may find attributes that getattr can't (like descriptors
1525 that raise AttributeError). It can also return descriptor objects
1526 instead of instance members in some cases. See the
1527 documentation for details.
1528 """
1529 instance_result = _sentinel
Michael Foord35184ed2010-11-20 16:58:30 +00001530 if not _is_type(obj):
Michael Foordcc7ebb82010-11-20 16:20:16 +00001531 klass = type(obj)
Michael Foorda51623b2011-12-18 22:01:40 +00001532 dict_attr = _shadowed_dict(klass)
1533 if (dict_attr is _sentinel or
1534 type(dict_attr) is types.MemberDescriptorType):
Michael Foorddcebe0f2011-03-15 19:20:44 -04001535 instance_result = _check_instance(obj, attr)
Michael Foord95fc51d2010-11-20 15:07:30 +00001536 else:
1537 klass = obj
1538
1539 klass_result = _check_class(klass, attr)
1540
1541 if instance_result is not _sentinel and klass_result is not _sentinel:
1542 if (_check_class(type(klass_result), '__get__') is not _sentinel and
1543 _check_class(type(klass_result), '__set__') is not _sentinel):
1544 return klass_result
1545
1546 if instance_result is not _sentinel:
1547 return instance_result
1548 if klass_result is not _sentinel:
1549 return klass_result
1550
1551 if obj is klass:
1552 # for types we check the metaclass too
Michael Foorde5162652010-11-20 16:40:44 +00001553 for entry in _static_getmro(type(klass)):
Michael Foord3ba95f82011-12-22 01:13:37 +00001554 if _shadowed_dict(type(entry)) is _sentinel:
1555 try:
1556 return entry.__dict__[attr]
1557 except KeyError:
1558 pass
Michael Foord95fc51d2010-11-20 15:07:30 +00001559 if default is not _sentinel:
1560 return default
1561 raise AttributeError(attr)
Nick Coghlane0f04652010-11-21 03:44:04 +00001562
1563
Nick Coghlan04e2e3f2012-06-23 19:52:05 +10001564# ------------------------------------------------ generator introspection
1565
Nick Coghlan7921b9f2010-11-30 06:36:04 +00001566GEN_CREATED = 'GEN_CREATED'
1567GEN_RUNNING = 'GEN_RUNNING'
1568GEN_SUSPENDED = 'GEN_SUSPENDED'
1569GEN_CLOSED = 'GEN_CLOSED'
Nick Coghlane0f04652010-11-21 03:44:04 +00001570
1571def getgeneratorstate(generator):
1572 """Get current state of a generator-iterator.
1573
1574 Possible states are:
1575 GEN_CREATED: Waiting to start execution.
1576 GEN_RUNNING: Currently being executed by the interpreter.
1577 GEN_SUSPENDED: Currently suspended at a yield expression.
1578 GEN_CLOSED: Execution has completed.
1579 """
1580 if generator.gi_running:
1581 return GEN_RUNNING
1582 if generator.gi_frame is None:
1583 return GEN_CLOSED
1584 if generator.gi_frame.f_lasti == -1:
1585 return GEN_CREATED
1586 return GEN_SUSPENDED
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07001587
1588
Nick Coghlan04e2e3f2012-06-23 19:52:05 +10001589def getgeneratorlocals(generator):
1590 """
1591 Get the mapping of generator local variables to their current values.
1592
1593 A dict is returned, with the keys the local variable names and values the
1594 bound values."""
1595
1596 if not isgenerator(generator):
1597 raise TypeError("'{!r}' is not a Python generator".format(generator))
1598
1599 frame = getattr(generator, "gi_frame", None)
1600 if frame is not None:
1601 return generator.gi_frame.f_locals
1602 else:
1603 return {}
1604
Yury Selivanov5376ba92015-06-22 12:19:30 -04001605
1606# ------------------------------------------------ coroutine introspection
1607
1608CORO_CREATED = 'CORO_CREATED'
1609CORO_RUNNING = 'CORO_RUNNING'
1610CORO_SUSPENDED = 'CORO_SUSPENDED'
1611CORO_CLOSED = 'CORO_CLOSED'
1612
1613def getcoroutinestate(coroutine):
1614 """Get current state of a coroutine object.
1615
1616 Possible states are:
1617 CORO_CREATED: Waiting to start execution.
1618 CORO_RUNNING: Currently being executed by the interpreter.
1619 CORO_SUSPENDED: Currently suspended at an await expression.
1620 CORO_CLOSED: Execution has completed.
1621 """
1622 if coroutine.cr_running:
1623 return CORO_RUNNING
1624 if coroutine.cr_frame is None:
1625 return CORO_CLOSED
1626 if coroutine.cr_frame.f_lasti == -1:
1627 return CORO_CREATED
1628 return CORO_SUSPENDED
1629
1630
1631def getcoroutinelocals(coroutine):
1632 """
1633 Get the mapping of coroutine local variables to their current values.
1634
1635 A dict is returned, with the keys the local variable names and values the
1636 bound values."""
1637 frame = getattr(coroutine, "cr_frame", None)
1638 if frame is not None:
1639 return frame.f_locals
1640 else:
1641 return {}
1642
1643
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07001644###############################################################################
1645### Function Signature Object (PEP 362)
1646###############################################################################
1647
1648
1649_WrapperDescriptor = type(type.__call__)
1650_MethodWrapper = type(all.__call__)
Larry Hastings5c661892014-01-24 06:17:25 -08001651_ClassMethodWrapper = type(int.__dict__['from_bytes'])
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07001652
1653_NonUserDefinedCallables = (_WrapperDescriptor,
1654 _MethodWrapper,
Larry Hastings5c661892014-01-24 06:17:25 -08001655 _ClassMethodWrapper,
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07001656 types.BuiltinFunctionType)
1657
1658
Yury Selivanov421f0c72014-01-29 12:05:40 -05001659def _signature_get_user_defined_method(cls, method_name):
Yury Selivanov5a23bd02014-03-29 13:47:11 -04001660 """Private helper. Checks if ``cls`` has an attribute
1661 named ``method_name`` and returns it only if it is a
1662 pure python function.
1663 """
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07001664 try:
1665 meth = getattr(cls, method_name)
1666 except AttributeError:
1667 return
1668 else:
1669 if not isinstance(meth, _NonUserDefinedCallables):
1670 # Once '__signature__' will be added to 'C'-level
1671 # callables, this check won't be necessary
1672 return meth
1673
1674
Yury Selivanov62560fb2014-01-28 12:26:24 -05001675def _signature_get_partial(wrapped_sig, partial, extra_args=()):
Yury Selivanov5a23bd02014-03-29 13:47:11 -04001676 """Private helper to calculate how 'wrapped_sig' signature will
1677 look like after applying a 'functools.partial' object (or alike)
1678 on it.
1679 """
Yury Selivanov62560fb2014-01-28 12:26:24 -05001680
Yury Selivanov3f73ca22014-04-08 11:30:45 -04001681 old_params = wrapped_sig.parameters
1682 new_params = OrderedDict(old_params.items())
Yury Selivanovda5fe4f2014-01-27 17:28:37 -05001683
1684 partial_args = partial.args or ()
1685 partial_keywords = partial.keywords or {}
1686
1687 if extra_args:
1688 partial_args = extra_args + partial_args
1689
1690 try:
1691 ba = wrapped_sig.bind_partial(*partial_args, **partial_keywords)
1692 except TypeError as ex:
1693 msg = 'partial object {!r} has incorrect arguments'.format(partial)
1694 raise ValueError(msg) from ex
1695
Yury Selivanovda5fe4f2014-01-27 17:28:37 -05001696
Yury Selivanov3f73ca22014-04-08 11:30:45 -04001697 transform_to_kwonly = False
1698 for param_name, param in old_params.items():
1699 try:
1700 arg_value = ba.arguments[param_name]
1701 except KeyError:
1702 pass
1703 else:
1704 if param.kind is _POSITIONAL_ONLY:
1705 # If positional-only parameter is bound by partial,
1706 # it effectively disappears from the signature
1707 new_params.pop(param_name)
1708 continue
1709
1710 if param.kind is _POSITIONAL_OR_KEYWORD:
1711 if param_name in partial_keywords:
1712 # This means that this parameter, and all parameters
1713 # after it should be keyword-only (and var-positional
1714 # should be removed). Here's why. Consider the following
1715 # function:
1716 # foo(a, b, *args, c):
1717 # pass
1718 #
1719 # "partial(foo, a='spam')" will have the following
1720 # signature: "(*, a='spam', b, c)". Because attempting
1721 # to call that partial with "(10, 20)" arguments will
1722 # raise a TypeError, saying that "a" argument received
1723 # multiple values.
1724 transform_to_kwonly = True
1725 # Set the new default value
1726 new_params[param_name] = param.replace(default=arg_value)
1727 else:
1728 # was passed as a positional argument
1729 new_params.pop(param.name)
1730 continue
1731
1732 if param.kind is _KEYWORD_ONLY:
1733 # Set the new default value
1734 new_params[param_name] = param.replace(default=arg_value)
1735
1736 if transform_to_kwonly:
1737 assert param.kind is not _POSITIONAL_ONLY
1738
1739 if param.kind is _POSITIONAL_OR_KEYWORD:
1740 new_param = new_params[param_name].replace(kind=_KEYWORD_ONLY)
1741 new_params[param_name] = new_param
1742 new_params.move_to_end(param_name)
1743 elif param.kind in (_KEYWORD_ONLY, _VAR_KEYWORD):
1744 new_params.move_to_end(param_name)
1745 elif param.kind is _VAR_POSITIONAL:
1746 new_params.pop(param.name)
Yury Selivanovda5fe4f2014-01-27 17:28:37 -05001747
1748 return wrapped_sig.replace(parameters=new_params.values())
1749
1750
Yury Selivanov62560fb2014-01-28 12:26:24 -05001751def _signature_bound_method(sig):
Yury Selivanov5a23bd02014-03-29 13:47:11 -04001752 """Private helper to transform signatures for unbound
1753 functions to bound methods.
1754 """
Yury Selivanov62560fb2014-01-28 12:26:24 -05001755
1756 params = tuple(sig.parameters.values())
1757
1758 if not params or params[0].kind in (_VAR_KEYWORD, _KEYWORD_ONLY):
1759 raise ValueError('invalid method signature')
1760
1761 kind = params[0].kind
1762 if kind in (_POSITIONAL_OR_KEYWORD, _POSITIONAL_ONLY):
1763 # Drop first parameter:
1764 # '(p1, p2[, ...])' -> '(p2[, ...])'
1765 params = params[1:]
1766 else:
1767 if kind is not _VAR_POSITIONAL:
1768 # Unless we add a new parameter type we never
1769 # get here
1770 raise ValueError('invalid argument type')
1771 # It's a var-positional parameter.
1772 # Do nothing. '(*args[, ...])' -> '(*args[, ...])'
1773
1774 return sig.replace(parameters=params)
1775
1776
Yury Selivanovb77511d2014-01-29 10:46:14 -05001777def _signature_is_builtin(obj):
Yury Selivanov5a23bd02014-03-29 13:47:11 -04001778 """Private helper to test if `obj` is a callable that might
1779 support Argument Clinic's __text_signature__ protocol.
1780 """
Yury Selivanov1d241832014-02-02 12:51:20 -05001781 return (isbuiltin(obj) or
Yury Selivanovb77511d2014-01-29 10:46:14 -05001782 ismethoddescriptor(obj) or
Yury Selivanov1d241832014-02-02 12:51:20 -05001783 isinstance(obj, _NonUserDefinedCallables) or
Yury Selivanovb77511d2014-01-29 10:46:14 -05001784 # Can't test 'isinstance(type)' here, as it would
1785 # also be True for regular python classes
1786 obj in (type, object))
1787
1788
Yury Selivanov63da7c72014-01-31 14:48:37 -05001789def _signature_is_functionlike(obj):
Yury Selivanov5a23bd02014-03-29 13:47:11 -04001790 """Private helper to test if `obj` is a duck type of FunctionType.
1791 A good example of such objects are functions compiled with
1792 Cython, which have all attributes that a pure Python function
1793 would have, but have their code statically compiled.
1794 """
Yury Selivanov63da7c72014-01-31 14:48:37 -05001795
1796 if not callable(obj) or isclass(obj):
1797 # All function-like objects are obviously callables,
1798 # and not classes.
1799 return False
1800
1801 name = getattr(obj, '__name__', None)
1802 code = getattr(obj, '__code__', None)
1803 defaults = getattr(obj, '__defaults__', _void) # Important to use _void ...
1804 kwdefaults = getattr(obj, '__kwdefaults__', _void) # ... and not None here
1805 annotations = getattr(obj, '__annotations__', None)
1806
1807 return (isinstance(code, types.CodeType) and
1808 isinstance(name, str) and
1809 (defaults is None or isinstance(defaults, tuple)) and
1810 (kwdefaults is None or isinstance(kwdefaults, dict)) and
1811 isinstance(annotations, dict))
1812
1813
Yury Selivanovd82eddc2014-01-29 11:24:39 -05001814def _signature_get_bound_param(spec):
Yury Selivanov5a23bd02014-03-29 13:47:11 -04001815 """ Private helper to get first parameter name from a
1816 __text_signature__ of a builtin method, which should
1817 be in the following format: '($param1, ...)'.
1818 Assumptions are that the first argument won't have
1819 a default value or an annotation.
1820 """
Yury Selivanovd82eddc2014-01-29 11:24:39 -05001821
1822 assert spec.startswith('($')
1823
1824 pos = spec.find(',')
1825 if pos == -1:
1826 pos = spec.find(')')
1827
1828 cpos = spec.find(':')
1829 assert cpos == -1 or cpos > pos
1830
1831 cpos = spec.find('=')
1832 assert cpos == -1 or cpos > pos
1833
1834 return spec[2:pos]
1835
1836
Larry Hastings2623c8c2014-02-08 22:15:29 -08001837def _signature_strip_non_python_syntax(signature):
1838 """
Yury Selivanov5a23bd02014-03-29 13:47:11 -04001839 Private helper function. Takes a signature in Argument Clinic's
1840 extended signature format.
1841
Larry Hastings2623c8c2014-02-08 22:15:29 -08001842 Returns a tuple of three things:
1843 * that signature re-rendered in standard Python syntax,
1844 * the index of the "self" parameter (generally 0), or None if
1845 the function does not have a "self" parameter, and
1846 * the index of the last "positional only" parameter,
1847 or None if the signature has no positional-only parameters.
1848 """
1849
1850 if not signature:
1851 return signature, None, None
1852
1853 self_parameter = None
1854 last_positional_only = None
1855
1856 lines = [l.encode('ascii') for l in signature.split('\n')]
1857 generator = iter(lines).__next__
1858 token_stream = tokenize.tokenize(generator)
1859
1860 delayed_comma = False
1861 skip_next_comma = False
1862 text = []
1863 add = text.append
1864
1865 current_parameter = 0
1866 OP = token.OP
1867 ERRORTOKEN = token.ERRORTOKEN
1868
1869 # token stream always starts with ENCODING token, skip it
1870 t = next(token_stream)
1871 assert t.type == tokenize.ENCODING
1872
1873 for t in token_stream:
1874 type, string = t.type, t.string
1875
1876 if type == OP:
1877 if string == ',':
1878 if skip_next_comma:
1879 skip_next_comma = False
1880 else:
1881 assert not delayed_comma
1882 delayed_comma = True
1883 current_parameter += 1
1884 continue
1885
1886 if string == '/':
1887 assert not skip_next_comma
1888 assert last_positional_only is None
1889 skip_next_comma = True
1890 last_positional_only = current_parameter - 1
1891 continue
1892
1893 if (type == ERRORTOKEN) and (string == '$'):
1894 assert self_parameter is None
1895 self_parameter = current_parameter
1896 continue
1897
1898 if delayed_comma:
1899 delayed_comma = False
1900 if not ((type == OP) and (string == ')')):
1901 add(', ')
1902 add(string)
1903 if (string == ','):
1904 add(' ')
1905 clean_signature = ''.join(text)
1906 return clean_signature, self_parameter, last_positional_only
1907
1908
Yury Selivanov57d240e2014-02-19 16:27:23 -05001909def _signature_fromstr(cls, obj, s, skip_bound_arg=True):
Yury Selivanov5a23bd02014-03-29 13:47:11 -04001910 """Private helper to parse content of '__text_signature__'
1911 and return a Signature based on it.
1912 """
1913
Yury Selivanov7d2bfed2014-02-03 02:46:07 -05001914 Parameter = cls._parameter_cls
1915
Larry Hastings2623c8c2014-02-08 22:15:29 -08001916 clean_signature, self_parameter, last_positional_only = \
1917 _signature_strip_non_python_syntax(s)
Yury Selivanov7d2bfed2014-02-03 02:46:07 -05001918
Larry Hastings2623c8c2014-02-08 22:15:29 -08001919 program = "def foo" + clean_signature + ": pass"
Yury Selivanov7d2bfed2014-02-03 02:46:07 -05001920
1921 try:
Larry Hastings2623c8c2014-02-08 22:15:29 -08001922 module = ast.parse(program)
Yury Selivanov7d2bfed2014-02-03 02:46:07 -05001923 except SyntaxError:
1924 module = None
1925
1926 if not isinstance(module, ast.Module):
1927 raise ValueError("{!r} builtin has invalid signature".format(obj))
1928
1929 f = module.body[0]
1930
1931 parameters = []
1932 empty = Parameter.empty
1933 invalid = object()
1934
1935 module = None
1936 module_dict = {}
1937 module_name = getattr(obj, '__module__', None)
1938 if module_name:
1939 module = sys.modules.get(module_name, None)
1940 if module:
1941 module_dict = module.__dict__
1942 sys_module_dict = sys.modules
1943
1944 def parse_name(node):
1945 assert isinstance(node, ast.arg)
1946 if node.annotation != None:
1947 raise ValueError("Annotations are not currently supported")
1948 return node.arg
1949
1950 def wrap_value(s):
1951 try:
1952 value = eval(s, module_dict)
1953 except NameError:
1954 try:
1955 value = eval(s, sys_module_dict)
1956 except NameError:
1957 raise RuntimeError()
1958
1959 if isinstance(value, str):
1960 return ast.Str(value)
1961 if isinstance(value, (int, float)):
1962 return ast.Num(value)
1963 if isinstance(value, bytes):
1964 return ast.Bytes(value)
1965 if value in (True, False, None):
1966 return ast.NameConstant(value)
1967 raise RuntimeError()
1968
1969 class RewriteSymbolics(ast.NodeTransformer):
1970 def visit_Attribute(self, node):
1971 a = []
1972 n = node
1973 while isinstance(n, ast.Attribute):
1974 a.append(n.attr)
1975 n = n.value
1976 if not isinstance(n, ast.Name):
1977 raise RuntimeError()
1978 a.append(n.id)
1979 value = ".".join(reversed(a))
1980 return wrap_value(value)
1981
1982 def visit_Name(self, node):
1983 if not isinstance(node.ctx, ast.Load):
1984 raise ValueError()
1985 return wrap_value(node.id)
1986
1987 def p(name_node, default_node, default=empty):
1988 name = parse_name(name_node)
1989 if name is invalid:
1990 return None
1991 if default_node and default_node is not _empty:
1992 try:
1993 default_node = RewriteSymbolics().visit(default_node)
1994 o = ast.literal_eval(default_node)
1995 except ValueError:
1996 o = invalid
1997 if o is invalid:
1998 return None
1999 default = o if o is not invalid else default
2000 parameters.append(Parameter(name, kind, default=default, annotation=empty))
2001
2002 # non-keyword-only parameters
2003 args = reversed(f.args.args)
2004 defaults = reversed(f.args.defaults)
2005 iter = itertools.zip_longest(args, defaults, fillvalue=None)
Larry Hastings2623c8c2014-02-08 22:15:29 -08002006 if last_positional_only is not None:
2007 kind = Parameter.POSITIONAL_ONLY
2008 else:
2009 kind = Parameter.POSITIONAL_OR_KEYWORD
2010 for i, (name, default) in enumerate(reversed(list(iter))):
Yury Selivanov7d2bfed2014-02-03 02:46:07 -05002011 p(name, default)
Larry Hastings2623c8c2014-02-08 22:15:29 -08002012 if i == last_positional_only:
2013 kind = Parameter.POSITIONAL_OR_KEYWORD
Yury Selivanov7d2bfed2014-02-03 02:46:07 -05002014
2015 # *args
2016 if f.args.vararg:
2017 kind = Parameter.VAR_POSITIONAL
2018 p(f.args.vararg, empty)
2019
2020 # keyword-only arguments
2021 kind = Parameter.KEYWORD_ONLY
2022 for name, default in zip(f.args.kwonlyargs, f.args.kw_defaults):
2023 p(name, default)
2024
2025 # **kwargs
2026 if f.args.kwarg:
2027 kind = Parameter.VAR_KEYWORD
2028 p(f.args.kwarg, empty)
2029
Larry Hastings2623c8c2014-02-08 22:15:29 -08002030 if self_parameter is not None:
Yury Selivanov8c185ee2014-02-21 01:32:42 -05002031 # Possibly strip the bound argument:
2032 # - We *always* strip first bound argument if
2033 # it is a module.
2034 # - We don't strip first bound argument if
2035 # skip_bound_arg is False.
Yury Selivanov7d2bfed2014-02-03 02:46:07 -05002036 assert parameters
Yury Selivanov8c185ee2014-02-21 01:32:42 -05002037 _self = getattr(obj, '__self__', None)
2038 self_isbound = _self is not None
2039 self_ismodule = ismodule(_self)
2040 if self_isbound and (self_ismodule or skip_bound_arg):
Yury Selivanov7d2bfed2014-02-03 02:46:07 -05002041 parameters.pop(0)
2042 else:
2043 # for builtins, self parameter is always positional-only!
2044 p = parameters[0].replace(kind=Parameter.POSITIONAL_ONLY)
2045 parameters[0] = p
2046
2047 return cls(parameters, return_annotation=cls.empty)
2048
2049
Yury Selivanov57d240e2014-02-19 16:27:23 -05002050def _signature_from_builtin(cls, func, skip_bound_arg=True):
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002051 """Private helper function to get signature for
2052 builtin callables.
2053 """
2054
Yury Selivanov57d240e2014-02-19 16:27:23 -05002055 if not _signature_is_builtin(func):
2056 raise TypeError("{!r} is not a Python builtin "
2057 "function".format(func))
2058
2059 s = getattr(func, "__text_signature__", None)
2060 if not s:
2061 raise ValueError("no signature found for builtin {!r}".format(func))
2062
2063 return _signature_fromstr(cls, func, s, skip_bound_arg)
2064
2065
Yury Selivanovcf45f022015-05-20 14:38:50 -04002066def _signature_from_function(cls, func):
2067 """Private helper: constructs Signature for the given python function."""
2068
2069 is_duck_function = False
2070 if not isfunction(func):
2071 if _signature_is_functionlike(func):
2072 is_duck_function = True
2073 else:
2074 # If it's not a pure Python function, and not a duck type
2075 # of pure function:
2076 raise TypeError('{!r} is not a Python function'.format(func))
2077
2078 Parameter = cls._parameter_cls
2079
2080 # Parameter information.
2081 func_code = func.__code__
2082 pos_count = func_code.co_argcount
2083 arg_names = func_code.co_varnames
2084 positional = tuple(arg_names[:pos_count])
2085 keyword_only_count = func_code.co_kwonlyargcount
2086 keyword_only = arg_names[pos_count:(pos_count + keyword_only_count)]
2087 annotations = func.__annotations__
2088 defaults = func.__defaults__
2089 kwdefaults = func.__kwdefaults__
2090
2091 if defaults:
2092 pos_default_count = len(defaults)
2093 else:
2094 pos_default_count = 0
2095
2096 parameters = []
2097
2098 # Non-keyword-only parameters w/o defaults.
2099 non_default_count = pos_count - pos_default_count
2100 for name in positional[:non_default_count]:
2101 annotation = annotations.get(name, _empty)
2102 parameters.append(Parameter(name, annotation=annotation,
2103 kind=_POSITIONAL_OR_KEYWORD))
2104
2105 # ... w/ defaults.
2106 for offset, name in enumerate(positional[non_default_count:]):
2107 annotation = annotations.get(name, _empty)
2108 parameters.append(Parameter(name, annotation=annotation,
2109 kind=_POSITIONAL_OR_KEYWORD,
2110 default=defaults[offset]))
2111
2112 # *args
2113 if func_code.co_flags & CO_VARARGS:
2114 name = arg_names[pos_count + keyword_only_count]
2115 annotation = annotations.get(name, _empty)
2116 parameters.append(Parameter(name, annotation=annotation,
2117 kind=_VAR_POSITIONAL))
2118
2119 # Keyword-only parameters.
2120 for name in keyword_only:
2121 default = _empty
2122 if kwdefaults is not None:
2123 default = kwdefaults.get(name, _empty)
2124
2125 annotation = annotations.get(name, _empty)
2126 parameters.append(Parameter(name, annotation=annotation,
2127 kind=_KEYWORD_ONLY,
2128 default=default))
2129 # **kwargs
2130 if func_code.co_flags & CO_VARKEYWORDS:
2131 index = pos_count + keyword_only_count
2132 if func_code.co_flags & CO_VARARGS:
2133 index += 1
2134
2135 name = arg_names[index]
2136 annotation = annotations.get(name, _empty)
2137 parameters.append(Parameter(name, annotation=annotation,
2138 kind=_VAR_KEYWORD))
2139
2140 # Is 'func' is a pure Python function - don't validate the
2141 # parameters list (for correct order and defaults), it should be OK.
2142 return cls(parameters,
2143 return_annotation=annotations.get('return', _empty),
2144 __validate_parameters__=is_duck_function)
2145
2146
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002147def _signature_from_callable(obj, *,
2148 follow_wrapper_chains=True,
2149 skip_bound_arg=True,
2150 sigcls):
2151
2152 """Private helper function to get signature for arbitrary
2153 callable objects.
2154 """
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002155
2156 if not callable(obj):
2157 raise TypeError('{!r} is not a callable object'.format(obj))
2158
2159 if isinstance(obj, types.MethodType):
2160 # In this case we skip the first parameter of the underlying
2161 # function (usually `self` or `cls`).
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002162 sig = _signature_from_callable(
Yury Selivanovda396452014-03-27 12:09:24 -04002163 obj.__func__,
2164 follow_wrapper_chains=follow_wrapper_chains,
2165 skip_bound_arg=skip_bound_arg,
2166 sigcls=sigcls)
2167
Yury Selivanov57d240e2014-02-19 16:27:23 -05002168 if skip_bound_arg:
2169 return _signature_bound_method(sig)
2170 else:
2171 return sig
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002172
Nick Coghlane8c45d62013-07-28 20:00:01 +10002173 # Was this function wrapped by a decorator?
Yury Selivanov57d240e2014-02-19 16:27:23 -05002174 if follow_wrapper_chains:
2175 obj = unwrap(obj, stop=(lambda f: hasattr(f, "__signature__")))
Yury Selivanov46c759d2015-05-27 21:56:53 -04002176 if isinstance(obj, types.MethodType):
2177 # If the unwrapped object is a *method*, we might want to
2178 # skip its first parameter (self).
2179 # See test_signature_wrapped_bound_method for details.
Yury Selivanov507cd3c2015-05-27 21:59:03 -04002180 return _signature_from_callable(
Yury Selivanov46c759d2015-05-27 21:56:53 -04002181 obj,
2182 follow_wrapper_chains=follow_wrapper_chains,
Yury Selivanov507cd3c2015-05-27 21:59:03 -04002183 skip_bound_arg=skip_bound_arg,
2184 sigcls=sigcls)
Nick Coghlane8c45d62013-07-28 20:00:01 +10002185
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002186 try:
2187 sig = obj.__signature__
2188 except AttributeError:
2189 pass
2190 else:
2191 if sig is not None:
Yury Selivanov42407ab2014-06-23 10:23:50 -07002192 if not isinstance(sig, Signature):
2193 raise TypeError(
2194 'unexpected object {!r} in __signature__ '
2195 'attribute'.format(sig))
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002196 return sig
2197
Yury Selivanovda5fe4f2014-01-27 17:28:37 -05002198 try:
2199 partialmethod = obj._partialmethod
2200 except AttributeError:
2201 pass
2202 else:
Yury Selivanov0486f812014-01-29 12:18:59 -05002203 if isinstance(partialmethod, functools.partialmethod):
2204 # Unbound partialmethod (see functools.partialmethod)
2205 # This means, that we need to calculate the signature
2206 # as if it's a regular partial object, but taking into
2207 # account that the first positional argument
2208 # (usually `self`, or `cls`) will not be passed
2209 # automatically (as for boundmethods)
Yury Selivanovda5fe4f2014-01-27 17:28:37 -05002210
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002211 wrapped_sig = _signature_from_callable(
Yury Selivanovda396452014-03-27 12:09:24 -04002212 partialmethod.func,
2213 follow_wrapper_chains=follow_wrapper_chains,
2214 skip_bound_arg=skip_bound_arg,
2215 sigcls=sigcls)
2216
Yury Selivanov0486f812014-01-29 12:18:59 -05002217 sig = _signature_get_partial(wrapped_sig, partialmethod, (None,))
Yury Selivanovda5fe4f2014-01-27 17:28:37 -05002218
Yury Selivanov0486f812014-01-29 12:18:59 -05002219 first_wrapped_param = tuple(wrapped_sig.parameters.values())[0]
2220 new_params = (first_wrapped_param,) + tuple(sig.parameters.values())
Yury Selivanovda5fe4f2014-01-27 17:28:37 -05002221
Yury Selivanov0486f812014-01-29 12:18:59 -05002222 return sig.replace(parameters=new_params)
Yury Selivanovda5fe4f2014-01-27 17:28:37 -05002223
Yury Selivanov63da7c72014-01-31 14:48:37 -05002224 if isfunction(obj) or _signature_is_functionlike(obj):
2225 # If it's a pure Python function, or an object that is duck type
2226 # of a Python function (Cython functions, for instance), then:
Yury Selivanovcf45f022015-05-20 14:38:50 -04002227 return _signature_from_function(sigcls, obj)
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002228
Yury Selivanova773de02014-02-21 18:30:53 -05002229 if _signature_is_builtin(obj):
Yury Selivanovda396452014-03-27 12:09:24 -04002230 return _signature_from_builtin(sigcls, obj,
Yury Selivanova773de02014-02-21 18:30:53 -05002231 skip_bound_arg=skip_bound_arg)
2232
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002233 if isinstance(obj, functools.partial):
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002234 wrapped_sig = _signature_from_callable(
Yury Selivanovda396452014-03-27 12:09:24 -04002235 obj.func,
2236 follow_wrapper_chains=follow_wrapper_chains,
2237 skip_bound_arg=skip_bound_arg,
2238 sigcls=sigcls)
Yury Selivanov62560fb2014-01-28 12:26:24 -05002239 return _signature_get_partial(wrapped_sig, obj)
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002240
2241 sig = None
2242 if isinstance(obj, type):
2243 # obj is a class or a metaclass
2244
2245 # First, let's see if it has an overloaded __call__ defined
2246 # in its metaclass
Yury Selivanov421f0c72014-01-29 12:05:40 -05002247 call = _signature_get_user_defined_method(type(obj), '__call__')
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002248 if call is not None:
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002249 sig = _signature_from_callable(
Yury Selivanovda396452014-03-27 12:09:24 -04002250 call,
2251 follow_wrapper_chains=follow_wrapper_chains,
2252 skip_bound_arg=skip_bound_arg,
2253 sigcls=sigcls)
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002254 else:
2255 # Now we check if the 'obj' class has a '__new__' method
Yury Selivanov421f0c72014-01-29 12:05:40 -05002256 new = _signature_get_user_defined_method(obj, '__new__')
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002257 if new is not None:
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002258 sig = _signature_from_callable(
Yury Selivanovda396452014-03-27 12:09:24 -04002259 new,
2260 follow_wrapper_chains=follow_wrapper_chains,
2261 skip_bound_arg=skip_bound_arg,
2262 sigcls=sigcls)
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002263 else:
2264 # Finally, we should have at least __init__ implemented
Yury Selivanov421f0c72014-01-29 12:05:40 -05002265 init = _signature_get_user_defined_method(obj, '__init__')
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002266 if init is not None:
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002267 sig = _signature_from_callable(
Yury Selivanovda396452014-03-27 12:09:24 -04002268 init,
2269 follow_wrapper_chains=follow_wrapper_chains,
2270 skip_bound_arg=skip_bound_arg,
2271 sigcls=sigcls)
Yury Selivanove7dcc5e2014-01-27 19:29:45 -05002272
2273 if sig is None:
Yury Selivanov7d2bfed2014-02-03 02:46:07 -05002274 # At this point we know, that `obj` is a class, with no user-
2275 # defined '__init__', '__new__', or class-level '__call__'
2276
Larry Hastings2623c8c2014-02-08 22:15:29 -08002277 for base in obj.__mro__[:-1]:
Yury Selivanov7d2bfed2014-02-03 02:46:07 -05002278 # Since '__text_signature__' is implemented as a
2279 # descriptor that extracts text signature from the
2280 # class docstring, if 'obj' is derived from a builtin
2281 # class, its own '__text_signature__' may be 'None'.
Larry Hastings2623c8c2014-02-08 22:15:29 -08002282 # Therefore, we go through the MRO (except the last
2283 # class in there, which is 'object') to find the first
Yury Selivanov7d2bfed2014-02-03 02:46:07 -05002284 # class with non-empty text signature.
2285 try:
2286 text_sig = base.__text_signature__
2287 except AttributeError:
2288 pass
2289 else:
2290 if text_sig:
2291 # If 'obj' class has a __text_signature__ attribute:
2292 # return a signature based on it
Yury Selivanovda396452014-03-27 12:09:24 -04002293 return _signature_fromstr(sigcls, obj, text_sig)
Yury Selivanov7d2bfed2014-02-03 02:46:07 -05002294
2295 # No '__text_signature__' was found for the 'obj' class.
2296 # Last option is to check if its '__init__' is
2297 # object.__init__ or type.__init__.
Larry Hastings2623c8c2014-02-08 22:15:29 -08002298 if type not in obj.__mro__:
Yury Selivanove7dcc5e2014-01-27 19:29:45 -05002299 # We have a class (not metaclass), but no user-defined
2300 # __init__ or __new__ for it
Yury Selivanovbf304fc2015-05-30 17:08:36 -04002301 if (obj.__init__ is object.__init__ and
2302 obj.__new__ is object.__new__):
Yury Selivanov7d2bfed2014-02-03 02:46:07 -05002303 # Return a signature of 'object' builtin.
2304 return signature(object)
Yury Selivanovbf304fc2015-05-30 17:08:36 -04002305 else:
2306 raise ValueError(
2307 'no signature found for builtin type {!r}'.format(obj))
Yury Selivanove7dcc5e2014-01-27 19:29:45 -05002308
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002309 elif not isinstance(obj, _NonUserDefinedCallables):
2310 # An object with __call__
2311 # We also check that the 'obj' is not an instance of
2312 # _WrapperDescriptor or _MethodWrapper to avoid
2313 # infinite recursion (and even potential segfault)
Yury Selivanov421f0c72014-01-29 12:05:40 -05002314 call = _signature_get_user_defined_method(type(obj), '__call__')
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002315 if call is not None:
Larry Hastings2623c8c2014-02-08 22:15:29 -08002316 try:
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002317 sig = _signature_from_callable(
Yury Selivanovda396452014-03-27 12:09:24 -04002318 call,
2319 follow_wrapper_chains=follow_wrapper_chains,
2320 skip_bound_arg=skip_bound_arg,
2321 sigcls=sigcls)
Larry Hastings2623c8c2014-02-08 22:15:29 -08002322 except ValueError as ex:
2323 msg = 'no signature found for {!r}'.format(obj)
2324 raise ValueError(msg) from ex
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002325
2326 if sig is not None:
2327 # For classes and objects we skip the first parameter of their
2328 # __call__, __new__, or __init__ methods
Yury Selivanov57d240e2014-02-19 16:27:23 -05002329 if skip_bound_arg:
2330 return _signature_bound_method(sig)
2331 else:
2332 return sig
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002333
2334 if isinstance(obj, types.BuiltinFunctionType):
2335 # Raise a nicer error message for builtins
2336 msg = 'no signature found for builtin function {!r}'.format(obj)
2337 raise ValueError(msg)
2338
2339 raise ValueError('callable {!r} is not supported by signature'.format(obj))
2340
2341
2342class _void:
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002343 """A private marker - used in Parameter & Signature."""
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002344
2345
2346class _empty:
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002347 """Marker object for Signature.empty and Parameter.empty."""
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002348
2349
Yury Selivanov21e83a52014-03-27 11:23:13 -04002350class _ParameterKind(enum.IntEnum):
2351 POSITIONAL_ONLY = 0
2352 POSITIONAL_OR_KEYWORD = 1
2353 VAR_POSITIONAL = 2
2354 KEYWORD_ONLY = 3
2355 VAR_KEYWORD = 4
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002356
2357 def __str__(self):
Yury Selivanov21e83a52014-03-27 11:23:13 -04002358 return self._name_
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002359
2360
Yury Selivanov21e83a52014-03-27 11:23:13 -04002361_POSITIONAL_ONLY = _ParameterKind.POSITIONAL_ONLY
2362_POSITIONAL_OR_KEYWORD = _ParameterKind.POSITIONAL_OR_KEYWORD
2363_VAR_POSITIONAL = _ParameterKind.VAR_POSITIONAL
2364_KEYWORD_ONLY = _ParameterKind.KEYWORD_ONLY
2365_VAR_KEYWORD = _ParameterKind.VAR_KEYWORD
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002366
2367
2368class Parameter:
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002369 """Represents a parameter in a function signature.
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002370
2371 Has the following public attributes:
2372
2373 * name : str
2374 The name of the parameter as a string.
2375 * default : object
2376 The default value for the parameter if specified. If the
Yury Selivanov8757ead2014-01-28 16:39:25 -05002377 parameter has no default value, this attribute is set to
2378 `Parameter.empty`.
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002379 * annotation
2380 The annotation for the parameter if specified. If the
Yury Selivanov8757ead2014-01-28 16:39:25 -05002381 parameter has no annotation, this attribute is set to
2382 `Parameter.empty`.
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002383 * kind : str
2384 Describes how argument values are bound to the parameter.
2385 Possible values: `Parameter.POSITIONAL_ONLY`,
2386 `Parameter.POSITIONAL_OR_KEYWORD`, `Parameter.VAR_POSITIONAL`,
2387 `Parameter.KEYWORD_ONLY`, `Parameter.VAR_KEYWORD`.
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002388 """
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002389
Yury Selivanov3f73ca22014-04-08 11:30:45 -04002390 __slots__ = ('_name', '_kind', '_default', '_annotation')
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002391
2392 POSITIONAL_ONLY = _POSITIONAL_ONLY
2393 POSITIONAL_OR_KEYWORD = _POSITIONAL_OR_KEYWORD
2394 VAR_POSITIONAL = _VAR_POSITIONAL
2395 KEYWORD_ONLY = _KEYWORD_ONLY
2396 VAR_KEYWORD = _VAR_KEYWORD
2397
2398 empty = _empty
2399
Yury Selivanov3f73ca22014-04-08 11:30:45 -04002400 def __init__(self, name, kind, *, default=_empty, annotation=_empty):
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002401
2402 if kind not in (_POSITIONAL_ONLY, _POSITIONAL_OR_KEYWORD,
2403 _VAR_POSITIONAL, _KEYWORD_ONLY, _VAR_KEYWORD):
2404 raise ValueError("invalid value for 'Parameter.kind' attribute")
2405 self._kind = kind
2406
2407 if default is not _empty:
2408 if kind in (_VAR_POSITIONAL, _VAR_KEYWORD):
2409 msg = '{} parameters cannot have default values'.format(kind)
2410 raise ValueError(msg)
2411 self._default = default
2412 self._annotation = annotation
2413
Yury Selivanov2393dca2014-01-27 15:07:58 -05002414 if name is _empty:
2415 raise ValueError('name is a required attribute for Parameter')
2416
2417 if not isinstance(name, str):
2418 raise TypeError("name must be a str, not a {!r}".format(name))
2419
Nick Coghlanb4b966e2016-06-04 14:40:03 -07002420 if name[0] == '.' and name[1:].isdigit():
2421 # These are implicit arguments generated by comprehensions. In
2422 # order to provide a friendlier interface to users, we recast
2423 # their name as "implicitN" and treat them as positional-only.
2424 # See issue 19611.
2425 if kind != _POSITIONAL_OR_KEYWORD:
2426 raise ValueError(
2427 'implicit arguments must be passed in as {}'.format(
2428 _POSITIONAL_OR_KEYWORD
2429 )
2430 )
2431 self._kind = _POSITIONAL_ONLY
2432 name = 'implicit{}'.format(name[1:])
2433
Yury Selivanov2393dca2014-01-27 15:07:58 -05002434 if not name.isidentifier():
2435 raise ValueError('{!r} is not a valid parameter name'.format(name))
2436
2437 self._name = name
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002438
Yury Selivanova5d63dd2014-03-27 11:31:43 -04002439 def __reduce__(self):
2440 return (type(self),
2441 (self._name, self._kind),
Yury Selivanov3f73ca22014-04-08 11:30:45 -04002442 {'_default': self._default,
Yury Selivanova5d63dd2014-03-27 11:31:43 -04002443 '_annotation': self._annotation})
2444
2445 def __setstate__(self, state):
Yury Selivanova5d63dd2014-03-27 11:31:43 -04002446 self._default = state['_default']
2447 self._annotation = state['_annotation']
2448
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002449 @property
2450 def name(self):
2451 return self._name
2452
2453 @property
2454 def default(self):
2455 return self._default
2456
2457 @property
2458 def annotation(self):
2459 return self._annotation
2460
2461 @property
2462 def kind(self):
2463 return self._kind
2464
Yury Selivanov3f73ca22014-04-08 11:30:45 -04002465 def replace(self, *, name=_void, kind=_void,
2466 annotation=_void, default=_void):
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002467 """Creates a customized copy of the Parameter."""
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002468
2469 if name is _void:
2470 name = self._name
2471
2472 if kind is _void:
2473 kind = self._kind
2474
2475 if annotation is _void:
2476 annotation = self._annotation
2477
2478 if default is _void:
2479 default = self._default
2480
Yury Selivanov3f73ca22014-04-08 11:30:45 -04002481 return type(self)(name, kind, default=default, annotation=annotation)
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002482
2483 def __str__(self):
2484 kind = self.kind
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002485 formatted = self._name
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002486
2487 # Add annotation and default value
2488 if self._annotation is not _empty:
2489 formatted = '{}:{}'.format(formatted,
2490 formatannotation(self._annotation))
2491
2492 if self._default is not _empty:
2493 formatted = '{}={}'.format(formatted, repr(self._default))
2494
2495 if kind == _VAR_POSITIONAL:
2496 formatted = '*' + formatted
2497 elif kind == _VAR_KEYWORD:
2498 formatted = '**' + formatted
2499
2500 return formatted
2501
2502 def __repr__(self):
Yury Selivanovf229bc52015-05-15 12:53:56 -04002503 return '<{} "{}">'.format(self.__class__.__name__, self)
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002504
Yury Selivanov67ae50e2014-04-08 11:46:50 -04002505 def __hash__(self):
Yury Selivanov08d4a4f2014-09-12 15:48:02 -04002506 return hash((self.name, self.kind, self.annotation, self.default))
Yury Selivanov67ae50e2014-04-08 11:46:50 -04002507
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002508 def __eq__(self, other):
Serhiy Storchaka2489bd52015-07-18 23:20:50 +03002509 if self is other:
2510 return True
Serhiy Storchaka3018cc42015-07-18 23:19:05 +03002511 if not isinstance(other, Parameter):
2512 return NotImplemented
2513 return (self._name == other._name and
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002514 self._kind == other._kind and
2515 self._default == other._default and
2516 self._annotation == other._annotation)
2517
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002518
2519class BoundArguments:
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002520 """Result of `Signature.bind` call. Holds the mapping of arguments
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002521 to the function's parameters.
2522
2523 Has the following public attributes:
2524
2525 * arguments : OrderedDict
2526 An ordered mutable mapping of parameters' names to arguments' values.
2527 Does not contain arguments' default values.
2528 * signature : Signature
2529 The Signature object that created this instance.
2530 * args : tuple
2531 Tuple of positional arguments values.
2532 * kwargs : dict
2533 Dict of keyword arguments values.
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002534 """
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002535
Yury Selivanov6abe0322015-05-13 17:18:41 -04002536 __slots__ = ('arguments', '_signature', '__weakref__')
2537
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002538 def __init__(self, signature, arguments):
2539 self.arguments = arguments
2540 self._signature = signature
2541
2542 @property
2543 def signature(self):
2544 return self._signature
2545
2546 @property
2547 def args(self):
2548 args = []
2549 for param_name, param in self._signature.parameters.items():
Yury Selivanov3f73ca22014-04-08 11:30:45 -04002550 if param.kind in (_VAR_KEYWORD, _KEYWORD_ONLY):
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002551 break
2552
2553 try:
2554 arg = self.arguments[param_name]
2555 except KeyError:
2556 # We're done here. Other arguments
2557 # will be mapped in 'BoundArguments.kwargs'
2558 break
2559 else:
2560 if param.kind == _VAR_POSITIONAL:
2561 # *args
2562 args.extend(arg)
2563 else:
2564 # plain argument
2565 args.append(arg)
2566
2567 return tuple(args)
2568
2569 @property
2570 def kwargs(self):
2571 kwargs = {}
2572 kwargs_started = False
2573 for param_name, param in self._signature.parameters.items():
2574 if not kwargs_started:
Yury Selivanov3f73ca22014-04-08 11:30:45 -04002575 if param.kind in (_VAR_KEYWORD, _KEYWORD_ONLY):
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002576 kwargs_started = True
2577 else:
2578 if param_name not in self.arguments:
2579 kwargs_started = True
2580 continue
2581
2582 if not kwargs_started:
2583 continue
2584
2585 try:
2586 arg = self.arguments[param_name]
2587 except KeyError:
2588 pass
2589 else:
2590 if param.kind == _VAR_KEYWORD:
2591 # **kwargs
2592 kwargs.update(arg)
2593 else:
2594 # plain keyword argument
2595 kwargs[param_name] = arg
2596
2597 return kwargs
2598
Yury Selivanovb907a512015-05-16 13:45:09 -04002599 def apply_defaults(self):
2600 """Set default values for missing arguments.
2601
2602 For variable-positional arguments (*args) the default is an
2603 empty tuple.
2604
2605 For variable-keyword arguments (**kwargs) the default is an
2606 empty dict.
2607 """
2608 arguments = self.arguments
Yury Selivanovb907a512015-05-16 13:45:09 -04002609 new_arguments = []
2610 for name, param in self._signature.parameters.items():
2611 try:
2612 new_arguments.append((name, arguments[name]))
2613 except KeyError:
2614 if param.default is not _empty:
2615 val = param.default
2616 elif param.kind is _VAR_POSITIONAL:
2617 val = ()
2618 elif param.kind is _VAR_KEYWORD:
2619 val = {}
2620 else:
2621 # This BoundArguments was likely produced by
2622 # Signature.bind_partial().
2623 continue
2624 new_arguments.append((name, val))
2625 self.arguments = OrderedDict(new_arguments)
2626
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002627 def __eq__(self, other):
Serhiy Storchaka2489bd52015-07-18 23:20:50 +03002628 if self is other:
2629 return True
Serhiy Storchaka3018cc42015-07-18 23:19:05 +03002630 if not isinstance(other, BoundArguments):
2631 return NotImplemented
2632 return (self.signature == other.signature and
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002633 self.arguments == other.arguments)
2634
Yury Selivanov6abe0322015-05-13 17:18:41 -04002635 def __setstate__(self, state):
2636 self._signature = state['_signature']
2637 self.arguments = state['arguments']
2638
2639 def __getstate__(self):
2640 return {'_signature': self._signature, 'arguments': self.arguments}
2641
Yury Selivanov3f6538f2015-05-14 18:47:17 -04002642 def __repr__(self):
2643 args = []
2644 for arg, value in self.arguments.items():
2645 args.append('{}={!r}'.format(arg, value))
Yury Selivanovf229bc52015-05-15 12:53:56 -04002646 return '<{} ({})>'.format(self.__class__.__name__, ', '.join(args))
Yury Selivanov3f6538f2015-05-14 18:47:17 -04002647
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002648
2649class Signature:
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002650 """A Signature object represents the overall signature of a function.
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002651 It stores a Parameter object for each parameter accepted by the
2652 function, as well as information specific to the function itself.
2653
2654 A Signature object has the following public attributes and methods:
2655
2656 * parameters : OrderedDict
2657 An ordered mapping of parameters' names to the corresponding
2658 Parameter objects (keyword-only arguments are in the same order
2659 as listed in `code.co_varnames`).
2660 * return_annotation : object
2661 The annotation for the return type of the function if specified.
2662 If the function has no annotation for its return type, this
Yury Selivanov8757ead2014-01-28 16:39:25 -05002663 attribute is set to `Signature.empty`.
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002664 * bind(*args, **kwargs) -> BoundArguments
2665 Creates a mapping from positional and keyword arguments to
2666 parameters.
2667 * bind_partial(*args, **kwargs) -> BoundArguments
2668 Creates a partial mapping from positional and keyword arguments
2669 to parameters (simulating 'functools.partial' behavior.)
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002670 """
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002671
2672 __slots__ = ('_return_annotation', '_parameters')
2673
2674 _parameter_cls = Parameter
2675 _bound_arguments_cls = BoundArguments
2676
2677 empty = _empty
2678
2679 def __init__(self, parameters=None, *, return_annotation=_empty,
2680 __validate_parameters__=True):
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002681 """Constructs Signature from the given list of Parameter
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002682 objects and 'return_annotation'. All arguments are optional.
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002683 """
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002684
2685 if parameters is None:
2686 params = OrderedDict()
2687 else:
2688 if __validate_parameters__:
2689 params = OrderedDict()
2690 top_kind = _POSITIONAL_ONLY
Yury Selivanov07a9e452014-01-29 10:58:16 -05002691 kind_defaults = False
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002692
2693 for idx, param in enumerate(parameters):
2694 kind = param.kind
Yury Selivanov2393dca2014-01-27 15:07:58 -05002695 name = param.name
2696
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002697 if kind < top_kind:
Yury Selivanov3f73ca22014-04-08 11:30:45 -04002698 msg = 'wrong parameter order: {!r} before {!r}'
Yury Selivanov2393dca2014-01-27 15:07:58 -05002699 msg = msg.format(top_kind, kind)
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002700 raise ValueError(msg)
Yury Selivanov07a9e452014-01-29 10:58:16 -05002701 elif kind > top_kind:
2702 kind_defaults = False
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002703 top_kind = kind
2704
Yury Selivanov3f73ca22014-04-08 11:30:45 -04002705 if kind in (_POSITIONAL_ONLY, _POSITIONAL_OR_KEYWORD):
Yury Selivanov07a9e452014-01-29 10:58:16 -05002706 if param.default is _empty:
2707 if kind_defaults:
2708 # No default for this parameter, but the
2709 # previous parameter of the same kind had
2710 # a default
2711 msg = 'non-default argument follows default ' \
2712 'argument'
2713 raise ValueError(msg)
2714 else:
2715 # There is a default for this parameter.
2716 kind_defaults = True
2717
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002718 if name in params:
2719 msg = 'duplicate parameter name: {!r}'.format(name)
2720 raise ValueError(msg)
Yury Selivanov2393dca2014-01-27 15:07:58 -05002721
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002722 params[name] = param
2723 else:
2724 params = OrderedDict(((param.name, param)
2725 for param in parameters))
2726
2727 self._parameters = types.MappingProxyType(params)
2728 self._return_annotation = return_annotation
2729
2730 @classmethod
2731 def from_function(cls, func):
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002732 """Constructs Signature for the given python function."""
Yury Selivanov57c74fc2015-05-20 23:07:02 -04002733
2734 warnings.warn("inspect.Signature.from_function() is deprecated, "
Berker Peksagb5601582015-05-21 23:40:54 +03002735 "use Signature.from_callable()",
2736 DeprecationWarning, stacklevel=2)
Yury Selivanovcf45f022015-05-20 14:38:50 -04002737 return _signature_from_function(cls, func)
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002738
Larry Hastings44e2eaa2013-11-23 15:37:55 -08002739 @classmethod
2740 def from_builtin(cls, func):
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002741 """Constructs Signature for the given builtin function."""
Yury Selivanov57c74fc2015-05-20 23:07:02 -04002742
2743 warnings.warn("inspect.Signature.from_builtin() is deprecated, "
Berker Peksagb5601582015-05-21 23:40:54 +03002744 "use Signature.from_callable()",
2745 DeprecationWarning, stacklevel=2)
Yury Selivanov57d240e2014-02-19 16:27:23 -05002746 return _signature_from_builtin(cls, func)
Larry Hastings44e2eaa2013-11-23 15:37:55 -08002747
Yury Selivanovda396452014-03-27 12:09:24 -04002748 @classmethod
Yury Selivanovbcd4fc12015-05-20 14:30:08 -04002749 def from_callable(cls, obj, *, follow_wrapped=True):
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002750 """Constructs Signature for the given callable object."""
Yury Selivanovbcd4fc12015-05-20 14:30:08 -04002751 return _signature_from_callable(obj, sigcls=cls,
2752 follow_wrapper_chains=follow_wrapped)
Yury Selivanovda396452014-03-27 12:09:24 -04002753
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002754 @property
2755 def parameters(self):
2756 return self._parameters
2757
2758 @property
2759 def return_annotation(self):
2760 return self._return_annotation
2761
2762 def replace(self, *, parameters=_void, return_annotation=_void):
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002763 """Creates a customized copy of the Signature.
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002764 Pass 'parameters' and/or 'return_annotation' arguments
2765 to override them in the new copy.
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002766 """
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002767
2768 if parameters is _void:
2769 parameters = self.parameters.values()
2770
2771 if return_annotation is _void:
2772 return_annotation = self._return_annotation
2773
2774 return type(self)(parameters,
2775 return_annotation=return_annotation)
2776
Yury Selivanov08d4a4f2014-09-12 15:48:02 -04002777 def _hash_basis(self):
2778 params = tuple(param for param in self.parameters.values()
2779 if param.kind != _KEYWORD_ONLY)
2780
2781 kwo_params = {param.name: param for param in self.parameters.values()
2782 if param.kind == _KEYWORD_ONLY}
2783
2784 return params, kwo_params, self.return_annotation
2785
Yury Selivanov67ae50e2014-04-08 11:46:50 -04002786 def __hash__(self):
Yury Selivanov08d4a4f2014-09-12 15:48:02 -04002787 params, kwo_params, return_annotation = self._hash_basis()
2788 kwo_params = frozenset(kwo_params.values())
2789 return hash((params, kwo_params, return_annotation))
Yury Selivanov67ae50e2014-04-08 11:46:50 -04002790
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002791 def __eq__(self, other):
Serhiy Storchaka2489bd52015-07-18 23:20:50 +03002792 if self is other:
2793 return True
Serhiy Storchaka3018cc42015-07-18 23:19:05 +03002794 if not isinstance(other, Signature):
2795 return NotImplemented
Serhiy Storchaka2489bd52015-07-18 23:20:50 +03002796 return self._hash_basis() == other._hash_basis()
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002797
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002798 def _bind(self, args, kwargs, *, partial=False):
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002799 """Private method. Don't use directly."""
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002800
2801 arguments = OrderedDict()
2802
2803 parameters = iter(self.parameters.values())
2804 parameters_ex = ()
2805 arg_vals = iter(args)
2806
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002807 while True:
2808 # Let's iterate through the positional arguments and corresponding
2809 # parameters
2810 try:
2811 arg_val = next(arg_vals)
2812 except StopIteration:
2813 # No more positional arguments
2814 try:
2815 param = next(parameters)
2816 except StopIteration:
2817 # No more parameters. That's it. Just need to check that
2818 # we have no `kwargs` after this while loop
2819 break
2820 else:
2821 if param.kind == _VAR_POSITIONAL:
2822 # That's OK, just empty *args. Let's start parsing
2823 # kwargs
2824 break
2825 elif param.name in kwargs:
2826 if param.kind == _POSITIONAL_ONLY:
2827 msg = '{arg!r} parameter is positional only, ' \
2828 'but was passed as a keyword'
2829 msg = msg.format(arg=param.name)
2830 raise TypeError(msg) from None
2831 parameters_ex = (param,)
2832 break
2833 elif (param.kind == _VAR_KEYWORD or
2834 param.default is not _empty):
2835 # That's fine too - we have a default value for this
2836 # parameter. So, lets start parsing `kwargs`, starting
2837 # with the current parameter
2838 parameters_ex = (param,)
2839 break
2840 else:
Yury Selivanov38b0d5a2014-01-28 17:27:39 -05002841 # No default, not VAR_KEYWORD, not VAR_POSITIONAL,
2842 # not in `kwargs`
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002843 if partial:
2844 parameters_ex = (param,)
2845 break
2846 else:
Yury Selivanov86872752015-05-19 00:27:49 -04002847 msg = 'missing a required argument: {arg!r}'
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002848 msg = msg.format(arg=param.name)
2849 raise TypeError(msg) from None
2850 else:
2851 # We have a positional argument to process
2852 try:
2853 param = next(parameters)
2854 except StopIteration:
2855 raise TypeError('too many positional arguments') from None
2856 else:
2857 if param.kind in (_VAR_KEYWORD, _KEYWORD_ONLY):
2858 # Looks like we have no parameter for this positional
2859 # argument
Yury Selivanov86872752015-05-19 00:27:49 -04002860 raise TypeError(
2861 'too many positional arguments') from None
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002862
2863 if param.kind == _VAR_POSITIONAL:
2864 # We have an '*args'-like argument, let's fill it with
2865 # all positional arguments we have left and move on to
2866 # the next phase
2867 values = [arg_val]
2868 values.extend(arg_vals)
2869 arguments[param.name] = tuple(values)
2870 break
2871
2872 if param.name in kwargs:
Yury Selivanov86872752015-05-19 00:27:49 -04002873 raise TypeError(
2874 'multiple values for argument {arg!r}'.format(
2875 arg=param.name)) from None
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002876
2877 arguments[param.name] = arg_val
2878
2879 # Now, we iterate through the remaining parameters to process
2880 # keyword arguments
2881 kwargs_param = None
2882 for param in itertools.chain(parameters_ex, parameters):
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002883 if param.kind == _VAR_KEYWORD:
2884 # Memorize that we have a '**kwargs'-like parameter
2885 kwargs_param = param
2886 continue
2887
Yury Selivanov38b0d5a2014-01-28 17:27:39 -05002888 if param.kind == _VAR_POSITIONAL:
2889 # Named arguments don't refer to '*args'-like parameters.
2890 # We only arrive here if the positional arguments ended
2891 # before reaching the last parameter before *args.
2892 continue
2893
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002894 param_name = param.name
2895 try:
2896 arg_val = kwargs.pop(param_name)
2897 except KeyError:
2898 # We have no value for this parameter. It's fine though,
2899 # if it has a default value, or it is an '*args'-like
2900 # parameter, left alone by the processing of positional
2901 # arguments.
2902 if (not partial and param.kind != _VAR_POSITIONAL and
2903 param.default is _empty):
Yury Selivanov86872752015-05-19 00:27:49 -04002904 raise TypeError('missing a required argument: {arg!r}'. \
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002905 format(arg=param_name)) from None
2906
2907 else:
Yury Selivanov9b9ac952014-01-28 20:54:28 -05002908 if param.kind == _POSITIONAL_ONLY:
2909 # This should never happen in case of a properly built
2910 # Signature object (but let's have this check here
2911 # to ensure correct behaviour just in case)
2912 raise TypeError('{arg!r} parameter is positional only, '
2913 'but was passed as a keyword'. \
2914 format(arg=param.name))
2915
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002916 arguments[param_name] = arg_val
2917
2918 if kwargs:
2919 if kwargs_param is not None:
2920 # Process our '**kwargs'-like parameter
2921 arguments[kwargs_param.name] = kwargs
2922 else:
Yury Selivanov86872752015-05-19 00:27:49 -04002923 raise TypeError(
2924 'got an unexpected keyword argument {arg!r}'.format(
2925 arg=next(iter(kwargs))))
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002926
2927 return self._bound_arguments_cls(self, arguments)
2928
Yury Selivanovc45873e2014-01-29 12:10:27 -05002929 def bind(*args, **kwargs):
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002930 """Get a BoundArguments object, that maps the passed `args`
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002931 and `kwargs` to the function's signature. Raises `TypeError`
2932 if the passed arguments can not be bound.
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002933 """
Yury Selivanovc45873e2014-01-29 12:10:27 -05002934 return args[0]._bind(args[1:], kwargs)
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002935
Yury Selivanovc45873e2014-01-29 12:10:27 -05002936 def bind_partial(*args, **kwargs):
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002937 """Get a BoundArguments object, that partially maps the
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002938 passed `args` and `kwargs` to the function's signature.
2939 Raises `TypeError` if the passed arguments can not be bound.
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002940 """
Yury Selivanovc45873e2014-01-29 12:10:27 -05002941 return args[0]._bind(args[1:], kwargs, partial=True)
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002942
Yury Selivanova5d63dd2014-03-27 11:31:43 -04002943 def __reduce__(self):
2944 return (type(self),
2945 (tuple(self._parameters.values()),),
2946 {'_return_annotation': self._return_annotation})
2947
2948 def __setstate__(self, state):
2949 self._return_annotation = state['_return_annotation']
2950
Yury Selivanov374375d2014-03-27 12:41:53 -04002951 def __repr__(self):
Yury Selivanovf229bc52015-05-15 12:53:56 -04002952 return '<{} {}>'.format(self.__class__.__name__, self)
Yury Selivanov374375d2014-03-27 12:41:53 -04002953
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002954 def __str__(self):
2955 result = []
Yury Selivanov2393dca2014-01-27 15:07:58 -05002956 render_pos_only_separator = False
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002957 render_kw_only_separator = True
Yury Selivanov2393dca2014-01-27 15:07:58 -05002958 for param in self.parameters.values():
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002959 formatted = str(param)
2960
2961 kind = param.kind
Yury Selivanov2393dca2014-01-27 15:07:58 -05002962
2963 if kind == _POSITIONAL_ONLY:
2964 render_pos_only_separator = True
2965 elif render_pos_only_separator:
2966 # It's not a positional-only parameter, and the flag
2967 # is set to 'True' (there were pos-only params before.)
2968 result.append('/')
2969 render_pos_only_separator = False
2970
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002971 if kind == _VAR_POSITIONAL:
2972 # OK, we have an '*args'-like parameter, so we won't need
2973 # a '*' to separate keyword-only arguments
2974 render_kw_only_separator = False
2975 elif kind == _KEYWORD_ONLY and render_kw_only_separator:
2976 # We have a keyword-only parameter to render and we haven't
2977 # rendered an '*args'-like parameter before, so add a '*'
2978 # separator to the parameters list ("foo(arg1, *, arg2)" case)
2979 result.append('*')
2980 # This condition should be only triggered once, so
2981 # reset the flag
2982 render_kw_only_separator = False
2983
2984 result.append(formatted)
2985
Yury Selivanov2393dca2014-01-27 15:07:58 -05002986 if render_pos_only_separator:
2987 # There were only positional-only parameters, hence the
2988 # flag was not reset to 'False'
2989 result.append('/')
2990
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002991 rendered = '({})'.format(', '.join(result))
2992
2993 if self.return_annotation is not _empty:
2994 anno = formatannotation(self.return_annotation)
2995 rendered += ' -> {}'.format(anno)
2996
2997 return rendered
Nick Coghlanf94a16b2013-09-22 22:46:49 +10002998
Yury Selivanovda396452014-03-27 12:09:24 -04002999
Yury Selivanovbcd4fc12015-05-20 14:30:08 -04003000def signature(obj, *, follow_wrapped=True):
Yury Selivanov5a23bd02014-03-29 13:47:11 -04003001 """Get a signature object for the passed callable."""
Yury Selivanovbcd4fc12015-05-20 14:30:08 -04003002 return Signature.from_callable(obj, follow_wrapped=follow_wrapped)
Yury Selivanovda396452014-03-27 12:09:24 -04003003
3004
Nick Coghlanf94a16b2013-09-22 22:46:49 +10003005def _main():
3006 """ Logic for inspecting an object given at command line """
3007 import argparse
3008 import importlib
3009
3010 parser = argparse.ArgumentParser()
3011 parser.add_argument(
3012 'object',
3013 help="The object to be analysed. "
3014 "It supports the 'module:qualname' syntax")
3015 parser.add_argument(
3016 '-d', '--details', action='store_true',
3017 help='Display info about the module rather than its source code')
3018
3019 args = parser.parse_args()
3020
3021 target = args.object
3022 mod_name, has_attrs, attrs = target.partition(":")
3023 try:
3024 obj = module = importlib.import_module(mod_name)
3025 except Exception as exc:
3026 msg = "Failed to import {} ({}: {})".format(mod_name,
3027 type(exc).__name__,
3028 exc)
3029 print(msg, file=sys.stderr)
3030 exit(2)
3031
3032 if has_attrs:
3033 parts = attrs.split(".")
3034 obj = module
3035 for part in parts:
3036 obj = getattr(obj, part)
3037
3038 if module.__name__ in sys.builtin_module_names:
3039 print("Can't get info for builtin modules.", file=sys.stderr)
3040 exit(1)
3041
3042 if args.details:
3043 print('Target: {}'.format(target))
3044 print('Origin: {}'.format(getsourcefile(module)))
3045 print('Cached: {}'.format(module.__cached__))
3046 if obj is module:
3047 print('Loader: {}'.format(repr(module.__loader__)))
3048 if hasattr(module, '__path__'):
3049 print('Submodule search path: {}'.format(module.__path__))
3050 else:
3051 try:
3052 __, lineno = findsource(obj)
3053 except Exception:
3054 pass
3055 else:
3056 print('Line: {}'.format(lineno))
3057
3058 print('\n')
3059 else:
3060 print(getsource(obj))
3061
3062
3063if __name__ == "__main__":
3064 _main()