blob: a2dcb888a0c6094f768d6c83ecdb367b88da0eea [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:
Xiang Zhang14944c62017-04-13 11:14:17 +0800256 co_argcount number of arguments (not including *, ** args
257 or keyword only arguments)
258 co_code string of raw compiled bytecode
259 co_cellvars tuple of names of cell variables
260 co_consts tuple of constants used in the bytecode
261 co_filename name of file in which this code object was created
262 co_firstlineno number of first line in Python source code
263 co_flags bitmap: 1=optimized | 2=newlocals | 4=*arg | 8=**arg
264 | 16=nested | 32=generator | 64=nofree | 128=coroutine
265 | 256=iterable_coroutine | 512=async_generator
266 co_freevars tuple of names of free variables
267 co_kwonlyargcount number of keyword only arguments (not including ** arg)
268 co_lnotab encoded mapping of line numbers to bytecode indices
269 co_name name with which this code object was defined
270 co_names tuple of names of local variables
271 co_nlocals number of local variables
272 co_stacksize virtual machine stack space required
273 co_varnames tuple of names of arguments and local variables"""
Tim Peters28bc59f2001-09-16 08:40:16 +0000274 return isinstance(object, types.CodeType)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000275
276def isbuiltin(object):
277 """Return true if the object is a built-in function or method.
278
279 Built-in functions and methods provide these attributes:
280 __doc__ documentation string
281 __name__ original name of this function or method
282 __self__ instance to which a method is bound, or None"""
Tim Peters28bc59f2001-09-16 08:40:16 +0000283 return isinstance(object, types.BuiltinFunctionType)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000284
285def isroutine(object):
286 """Return true if the object is any kind of function or method."""
Tim Peters536d2262001-09-20 05:13:38 +0000287 return (isbuiltin(object)
288 or isfunction(object)
289 or ismethod(object)
290 or ismethoddescriptor(object))
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000291
Christian Heimesbe5b30b2008-03-03 19:18:51 +0000292def isabstract(object):
293 """Return true if the object is an abstract base class (ABC)."""
Benjamin Petersona0dfa822009-11-13 02:25:08 +0000294 return bool(isinstance(object, type) and object.__flags__ & TPFLAGS_IS_ABSTRACT)
Christian Heimesbe5b30b2008-03-03 19:18:51 +0000295
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000296def getmembers(object, predicate=None):
297 """Return all members of an object as (name, value) pairs sorted by name.
298 Optionally, only return members that satisfy a given predicate."""
Antoine Pitrou86a8a9a2011-12-21 09:57:40 +0100299 if isclass(object):
300 mro = (object,) + getmro(object)
301 else:
302 mro = ()
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000303 results = []
Ethan Furmane03ea372013-09-25 07:14:41 -0700304 processed = set()
305 names = dir(object)
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700306 # :dd any DynamicClassAttributes to the list of names if object is a class;
Ethan Furmane03ea372013-09-25 07:14:41 -0700307 # this may result in duplicate entries if, for example, a virtual
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700308 # attribute with the same name as a DynamicClassAttribute exists
Ethan Furmane03ea372013-09-25 07:14:41 -0700309 try:
310 for base in object.__bases__:
311 for k, v in base.__dict__.items():
312 if isinstance(v, types.DynamicClassAttribute):
313 names.append(k)
314 except AttributeError:
315 pass
316 for key in names:
Ethan Furman63c141c2013-10-18 00:27:39 -0700317 # First try to get the value via getattr. Some descriptors don't
318 # like calling their __get__ (see bug #1785), so fall back to
319 # looking in the __dict__.
320 try:
321 value = getattr(object, key)
322 # handle the duplicate key
323 if key in processed:
324 raise AttributeError
325 except AttributeError:
326 for base in mro:
327 if key in base.__dict__:
328 value = base.__dict__[key]
329 break
330 else:
331 # could be a (currently) missing slot member, or a buggy
332 # __dir__; discard and move on
Antoine Pitrou86a8a9a2011-12-21 09:57:40 +0100333 continue
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000334 if not predicate or predicate(value):
335 results.append((key, value))
Ethan Furmane03ea372013-09-25 07:14:41 -0700336 processed.add(key)
337 results.sort(key=lambda pair: pair[0])
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000338 return results
339
Christian Heimes25bb7832008-01-11 16:17:00 +0000340Attribute = namedtuple('Attribute', 'name kind defining_class object')
341
Tim Peters13b49d32001-09-23 02:00:29 +0000342def classify_class_attrs(cls):
343 """Return list of attribute-descriptor tuples.
344
345 For each name in dir(cls), the return list contains a 4-tuple
346 with these elements:
347
348 0. The name (a string).
349
350 1. The kind of attribute this is, one of these strings:
351 'class method' created via classmethod()
352 'static method' created via staticmethod()
353 'property' created via property()
Ethan Furmane03ea372013-09-25 07:14:41 -0700354 'method' any other flavor of method or descriptor
Tim Peters13b49d32001-09-23 02:00:29 +0000355 'data' not a method
356
357 2. The class which defined this attribute (a class).
358
Ethan Furmane03ea372013-09-25 07:14:41 -0700359 3. The object as obtained by calling getattr; if this fails, or if the
360 resulting object does not live anywhere in the class' mro (including
361 metaclasses) then the object is looked up in the defining class's
362 dict (found by walking the mro).
Ethan Furman668dede2013-09-14 18:53:26 -0700363
364 If one of the items in dir(cls) is stored in the metaclass it will now
365 be discovered and not have None be listed as the class in which it was
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700366 defined. Any items whose home class cannot be discovered are skipped.
Tim Peters13b49d32001-09-23 02:00:29 +0000367 """
368
369 mro = getmro(cls)
Ethan Furman668dede2013-09-14 18:53:26 -0700370 metamro = getmro(type(cls)) # for attributes stored in the metaclass
Ethan Furmane03ea372013-09-25 07:14:41 -0700371 metamro = tuple([cls for cls in metamro if cls not in (type, object)])
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700372 class_bases = (cls,) + mro
373 all_bases = class_bases + metamro
Tim Peters13b49d32001-09-23 02:00:29 +0000374 names = dir(cls)
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700375 # :dd any DynamicClassAttributes to the list of names;
Ethan Furmane03ea372013-09-25 07:14:41 -0700376 # this may result in duplicate entries if, for example, a virtual
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700377 # attribute with the same name as a DynamicClassAttribute exists.
Ethan Furman63c141c2013-10-18 00:27:39 -0700378 for base in mro:
Ethan Furmane03ea372013-09-25 07:14:41 -0700379 for k, v in base.__dict__.items():
380 if isinstance(v, types.DynamicClassAttribute):
381 names.append(k)
Tim Peters13b49d32001-09-23 02:00:29 +0000382 result = []
Ethan Furmane03ea372013-09-25 07:14:41 -0700383 processed = set()
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700384
Tim Peters13b49d32001-09-23 02:00:29 +0000385 for name in names:
Antoine Pitrou86a8a9a2011-12-21 09:57:40 +0100386 # Get the object associated with the name, and where it was defined.
Ethan Furmane03ea372013-09-25 07:14:41 -0700387 # Normal objects will be looked up with both getattr and directly in
388 # its class' dict (in case getattr fails [bug #1785], and also to look
389 # for a docstring).
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700390 # For DynamicClassAttributes on the second pass we only look in the
Ethan Furmane03ea372013-09-25 07:14:41 -0700391 # class's dict.
392 #
Tim Peters13b49d32001-09-23 02:00:29 +0000393 # Getting an obj from the __dict__ sometimes reveals more than
394 # using getattr. Static and class methods are dramatic examples.
Antoine Pitrou86a8a9a2011-12-21 09:57:40 +0100395 homecls = None
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700396 get_obj = None
397 dict_obj = None
Ethan Furmane03ea372013-09-25 07:14:41 -0700398 if name not in processed:
399 try:
Ethan Furmana8b07072013-10-18 01:22:08 -0700400 if name == '__dict__':
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700401 raise Exception("__dict__ is special, don't want the proxy")
Ethan Furmane03ea372013-09-25 07:14:41 -0700402 get_obj = getattr(cls, name)
403 except Exception as exc:
404 pass
405 else:
Ethan Furmane03ea372013-09-25 07:14:41 -0700406 homecls = getattr(get_obj, "__objclass__", homecls)
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700407 if homecls not in class_bases:
Ethan Furmane03ea372013-09-25 07:14:41 -0700408 # if the resulting object does not live somewhere in the
Ethan Furman63c141c2013-10-18 00:27:39 -0700409 # mro, drop it and search the mro manually
Ethan Furmane03ea372013-09-25 07:14:41 -0700410 homecls = None
Ethan Furman63c141c2013-10-18 00:27:39 -0700411 last_cls = None
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700412 # first look in the classes
413 for srch_cls in class_bases:
Ethan Furman63c141c2013-10-18 00:27:39 -0700414 srch_obj = getattr(srch_cls, name, None)
Yury Selivanovbf341fb2015-05-21 15:41:57 -0400415 if srch_obj is get_obj:
Ethan Furman63c141c2013-10-18 00:27:39 -0700416 last_cls = srch_cls
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700417 # then check the metaclasses
418 for srch_cls in metamro:
419 try:
420 srch_obj = srch_cls.__getattr__(cls, name)
421 except AttributeError:
422 continue
Yury Selivanovbf341fb2015-05-21 15:41:57 -0400423 if srch_obj is get_obj:
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700424 last_cls = srch_cls
Ethan Furman63c141c2013-10-18 00:27:39 -0700425 if last_cls is not None:
426 homecls = last_cls
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700427 for base in all_bases:
Ethan Furmane03ea372013-09-25 07:14:41 -0700428 if name in base.__dict__:
429 dict_obj = base.__dict__[name]
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700430 if homecls not in metamro:
431 homecls = base
Ethan Furmane03ea372013-09-25 07:14:41 -0700432 break
Ethan Furman63c141c2013-10-18 00:27:39 -0700433 if homecls is None:
434 # unable to locate the attribute anywhere, most likely due to
435 # buggy custom __dir__; discard and move on
436 continue
Yury Selivanovbf341fb2015-05-21 15:41:57 -0400437 obj = get_obj if get_obj is not None else dict_obj
Ethan Furmane03ea372013-09-25 07:14:41 -0700438 # Classify the object or its descriptor.
Ethan Furman63c141c2013-10-18 00:27:39 -0700439 if isinstance(dict_obj, staticmethod):
Tim Peters13b49d32001-09-23 02:00:29 +0000440 kind = "static method"
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700441 obj = dict_obj
Ethan Furman63c141c2013-10-18 00:27:39 -0700442 elif isinstance(dict_obj, classmethod):
Tim Peters13b49d32001-09-23 02:00:29 +0000443 kind = "class method"
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700444 obj = dict_obj
445 elif isinstance(dict_obj, property):
Tim Peters13b49d32001-09-23 02:00:29 +0000446 kind = "property"
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700447 obj = dict_obj
Yury Selivanov0860a0b2014-01-31 14:28:44 -0500448 elif isroutine(obj):
Tim Peters13b49d32001-09-23 02:00:29 +0000449 kind = "method"
Antoine Pitrou86a8a9a2011-12-21 09:57:40 +0100450 else:
Ethan Furmane03ea372013-09-25 07:14:41 -0700451 kind = "data"
Christian Heimes25bb7832008-01-11 16:17:00 +0000452 result.append(Attribute(name, kind, homecls, obj))
Ethan Furmane03ea372013-09-25 07:14:41 -0700453 processed.add(name)
Tim Peters13b49d32001-09-23 02:00:29 +0000454 return result
455
Tim Peterse0b2d7a2001-09-22 06:10:55 +0000456# ----------------------------------------------------------- class helpers
Tim Peterse0b2d7a2001-09-22 06:10:55 +0000457
458def getmro(cls):
459 "Return tuple of base classes (including cls) in method resolution order."
Benjamin Petersonb82c8e52010-11-04 00:38:49 +0000460 return cls.__mro__
Tim Peterse0b2d7a2001-09-22 06:10:55 +0000461
Nick Coghlane8c45d62013-07-28 20:00:01 +1000462# -------------------------------------------------------- function helpers
463
464def unwrap(func, *, stop=None):
465 """Get the object wrapped by *func*.
466
467 Follows the chain of :attr:`__wrapped__` attributes returning the last
468 object in the chain.
469
470 *stop* is an optional callback accepting an object in the wrapper chain
471 as its sole argument that allows the unwrapping to be terminated early if
472 the callback returns a true value. If the callback never returns a true
473 value, the last object in the chain is returned as usual. For example,
474 :func:`signature` uses this to stop unwrapping if any object in the
475 chain has a ``__signature__`` attribute defined.
476
477 :exc:`ValueError` is raised if a cycle is encountered.
478
479 """
480 if stop is None:
481 def _is_wrapper(f):
482 return hasattr(f, '__wrapped__')
483 else:
484 def _is_wrapper(f):
485 return hasattr(f, '__wrapped__') and not stop(f)
486 f = func # remember the original func for error reporting
487 memo = {id(f)} # Memoise by id to tolerate non-hashable objects
488 while _is_wrapper(func):
489 func = func.__wrapped__
490 id_func = id(func)
491 if id_func in memo:
492 raise ValueError('wrapper loop when unwrapping {!r}'.format(f))
493 memo.add(id_func)
494 return func
495
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000496# -------------------------------------------------- source code extraction
497def indentsize(line):
498 """Return the indent size, in spaces, at the start of a line of text."""
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000499 expline = line.expandtabs()
500 return len(expline) - len(expline.lstrip())
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000501
Serhiy Storchaka5cf2b7252015-04-03 22:38:53 +0300502def _findclass(func):
503 cls = sys.modules.get(func.__module__)
504 if cls is None:
505 return None
506 for name in func.__qualname__.split('.')[:-1]:
507 cls = getattr(cls, name)
508 if not isclass(cls):
509 return None
510 return cls
511
512def _finddoc(obj):
513 if isclass(obj):
514 for base in obj.__mro__:
515 if base is not object:
516 try:
517 doc = base.__doc__
518 except AttributeError:
519 continue
520 if doc is not None:
521 return doc
522 return None
523
524 if ismethod(obj):
525 name = obj.__func__.__name__
526 self = obj.__self__
527 if (isclass(self) and
528 getattr(getattr(self, name, None), '__func__') is obj.__func__):
529 # classmethod
530 cls = self
531 else:
532 cls = self.__class__
533 elif isfunction(obj):
534 name = obj.__name__
535 cls = _findclass(obj)
536 if cls is None or getattr(cls, name) is not obj:
537 return None
538 elif isbuiltin(obj):
539 name = obj.__name__
540 self = obj.__self__
541 if (isclass(self) and
542 self.__qualname__ + '.' + name == obj.__qualname__):
543 # classmethod
544 cls = self
545 else:
546 cls = self.__class__
Serhiy Storchakaac4bdcc2015-10-29 08:15:50 +0200547 # Should be tested before isdatadescriptor().
548 elif isinstance(obj, property):
549 func = obj.fget
550 name = func.__name__
551 cls = _findclass(func)
552 if cls is None or getattr(cls, name) is not obj:
553 return None
Serhiy Storchaka5cf2b7252015-04-03 22:38:53 +0300554 elif ismethoddescriptor(obj) or isdatadescriptor(obj):
555 name = obj.__name__
556 cls = obj.__objclass__
557 if getattr(cls, name) is not obj:
558 return None
Serhiy Storchaka5cf2b7252015-04-03 22:38:53 +0300559 else:
560 return None
561
562 for base in cls.__mro__:
563 try:
564 doc = getattr(base, name).__doc__
565 except AttributeError:
566 continue
567 if doc is not None:
568 return doc
569 return None
570
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000571def getdoc(object):
572 """Get the documentation string for an object.
573
574 All tabs are expanded to spaces. To clean up docstrings that are
575 indented to line up with blocks of code, any whitespace than can be
576 uniformly removed from the second line onwards is removed."""
Tim Peters24008312002-03-17 18:56:20 +0000577 try:
578 doc = object.__doc__
579 except AttributeError:
580 return None
Serhiy Storchaka5cf2b7252015-04-03 22:38:53 +0300581 if doc is None:
582 try:
583 doc = _finddoc(object)
584 except (AttributeError, TypeError):
585 return None
Guido van Rossum3172c5d2007-10-16 18:12:55 +0000586 if not isinstance(doc, str):
Tim Peters24008312002-03-17 18:56:20 +0000587 return None
Georg Brandl0c77a822008-06-10 16:37:50 +0000588 return cleandoc(doc)
589
590def cleandoc(doc):
591 """Clean up indentation from docstrings.
592
593 Any whitespace that can be uniformly removed from the second line
594 onwards is removed."""
Tim Peters24008312002-03-17 18:56:20 +0000595 try:
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000596 lines = doc.expandtabs().split('\n')
Tim Peters24008312002-03-17 18:56:20 +0000597 except UnicodeError:
598 return None
599 else:
Ka-Ping Yeea59ef7b2002-11-30 03:53:15 +0000600 # Find minimum indentation of any non-blank lines after first line.
Christian Heimesa37d4c62007-12-04 23:02:19 +0000601 margin = sys.maxsize
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000602 for line in lines[1:]:
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000603 content = len(line.lstrip())
Ka-Ping Yeea59ef7b2002-11-30 03:53:15 +0000604 if content:
605 indent = len(line) - content
606 margin = min(margin, indent)
607 # Remove indentation.
608 if lines:
609 lines[0] = lines[0].lstrip()
Christian Heimesa37d4c62007-12-04 23:02:19 +0000610 if margin < sys.maxsize:
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000611 for i in range(1, len(lines)): lines[i] = lines[i][margin:]
Ka-Ping Yeea59ef7b2002-11-30 03:53:15 +0000612 # Remove any trailing or leading blank lines.
613 while lines and not lines[-1]:
614 lines.pop()
615 while lines and not lines[0]:
616 lines.pop(0)
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000617 return '\n'.join(lines)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000618
619def getfile(object):
Ka-Ping Yeec113c242001-03-02 02:08:53 +0000620 """Work out which source or compiled file an object was defined in."""
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000621 if ismodule(object):
622 if hasattr(object, '__file__'):
623 return object.__file__
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +0000624 raise TypeError('{!r} is a built-in module'.format(object))
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000625 if isclass(object):
Yury Selivanov2eed8b72014-01-27 13:24:56 -0500626 if hasattr(object, '__module__'):
627 object = sys.modules.get(object.__module__)
628 if hasattr(object, '__file__'):
629 return object.__file__
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +0000630 raise TypeError('{!r} is a built-in class'.format(object))
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000631 if ismethod(object):
Christian Heimesff737952007-11-27 10:40:20 +0000632 object = object.__func__
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000633 if isfunction(object):
Neal Norwitz221085d2007-02-25 20:55:47 +0000634 object = object.__code__
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000635 if istraceback(object):
636 object = object.tb_frame
637 if isframe(object):
638 object = object.f_code
639 if iscode(object):
640 return object.co_filename
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +0000641 raise TypeError('{!r} is not a module, class, method, '
642 'function, traceback, frame, or code object'.format(object))
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000643
Ka-Ping Yee4d6fc7f2001-04-10 11:43:00 +0000644def getmodulename(path):
645 """Return the module name for a given file, or None."""
Nick Coghlan76e07702012-07-18 23:14:57 +1000646 fname = os.path.basename(path)
647 # Check for paths that look like an actual module file
648 suffixes = [(-len(suffix), suffix)
649 for suffix in importlib.machinery.all_suffixes()]
650 suffixes.sort() # try longest suffixes first, in case they overlap
651 for neglen, suffix in suffixes:
652 if fname.endswith(suffix):
653 return fname[:neglen]
654 return None
Ka-Ping Yee4d6fc7f2001-04-10 11:43:00 +0000655
Ka-Ping Yeec113c242001-03-02 02:08:53 +0000656def getsourcefile(object):
R. David Murraya1b37402010-06-17 02:04:29 +0000657 """Return the filename that can be used to locate an object's source.
658 Return None if no way can be identified to get the source.
659 """
Ka-Ping Yeec113c242001-03-02 02:08:53 +0000660 filename = getfile(object)
Brett Cannoncb66eb02012-05-11 12:58:42 -0400661 all_bytecode_suffixes = importlib.machinery.DEBUG_BYTECODE_SUFFIXES[:]
662 all_bytecode_suffixes += importlib.machinery.OPTIMIZED_BYTECODE_SUFFIXES[:]
663 if any(filename.endswith(s) for s in all_bytecode_suffixes):
664 filename = (os.path.splitext(filename)[0] +
665 importlib.machinery.SOURCE_SUFFIXES[0])
666 elif any(filename.endswith(s) for s in
667 importlib.machinery.EXTENSION_SUFFIXES):
668 return None
Thomas Wouters477c8d52006-05-27 19:21:47 +0000669 if os.path.exists(filename):
670 return filename
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000671 # only return a non-existent filename if the module has a PEP 302 loader
Brett Cannon4c14b5d2013-05-04 13:56:58 -0400672 if getattr(getmodule(object, filename), '__loader__', None) is not None:
Ka-Ping Yeec113c242001-03-02 02:08:53 +0000673 return filename
R. David Murraya1b37402010-06-17 02:04:29 +0000674 # or it is in the linecache
675 if filename in linecache.cache:
676 return filename
Ka-Ping Yeec113c242001-03-02 02:08:53 +0000677
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000678def getabsfile(object, _filename=None):
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000679 """Return an absolute path to the source or compiled file for an object.
Ka-Ping Yeec113c242001-03-02 02:08:53 +0000680
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000681 The idea is for each object to have a unique origin, so this routine
682 normalizes the result as much as possible."""
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000683 if _filename is None:
684 _filename = getsourcefile(object) or getfile(object)
685 return os.path.normcase(os.path.abspath(_filename))
Ka-Ping Yeec113c242001-03-02 02:08:53 +0000686
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000687modulesbyfile = {}
Thomas Wouters89f507f2006-12-13 04:49:30 +0000688_filesbymodname = {}
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000689
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000690def getmodule(object, _filename=None):
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000691 """Return the module an object was defined in, or None if not found."""
Ka-Ping Yee202c99b2001-04-13 09:15:08 +0000692 if ismodule(object):
693 return object
Johannes Gijsbers93245262004-09-11 15:53:22 +0000694 if hasattr(object, '__module__'):
Ka-Ping Yee8b58b842001-03-01 13:56:16 +0000695 return sys.modules.get(object.__module__)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000696 # Try the filename to modulename cache
697 if _filename is not None and _filename in modulesbyfile:
698 return sys.modules.get(modulesbyfile[_filename])
699 # Try the cache again with the absolute file name
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000700 try:
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000701 file = getabsfile(object, _filename)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000702 except TypeError:
703 return None
Raymond Hettinger54f02222002-06-01 14:18:47 +0000704 if file in modulesbyfile:
Ka-Ping Yeeb38bbbd2003-03-28 16:29:50 +0000705 return sys.modules.get(modulesbyfile[file])
Thomas Wouters89f507f2006-12-13 04:49:30 +0000706 # Update the filename to module name cache and check yet again
707 # Copy sys.modules in order to cope with changes while iterating
Éric Araujoa74f8ef2011-11-29 16:58:53 +0100708 for modname, module in list(sys.modules.items()):
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000709 if ismodule(module) and hasattr(module, '__file__'):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000710 f = module.__file__
711 if f == _filesbymodname.get(modname, None):
712 # Have already mapped this module, so skip it
713 continue
714 _filesbymodname[modname] = f
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000715 f = getabsfile(module)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000716 # Always map to the name the module knows itself by
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000717 modulesbyfile[f] = modulesbyfile[
718 os.path.realpath(f)] = module.__name__
Raymond Hettinger54f02222002-06-01 14:18:47 +0000719 if file in modulesbyfile:
Ka-Ping Yeeb38bbbd2003-03-28 16:29:50 +0000720 return sys.modules.get(modulesbyfile[file])
Thomas Wouters89f507f2006-12-13 04:49:30 +0000721 # Check the main module
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000722 main = sys.modules['__main__']
Brett Cannon4a671fe2003-06-15 22:33:28 +0000723 if not hasattr(object, '__name__'):
724 return None
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000725 if hasattr(main, object.__name__):
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000726 mainobject = getattr(main, object.__name__)
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000727 if mainobject is object:
728 return main
Thomas Wouters89f507f2006-12-13 04:49:30 +0000729 # Check builtins
Georg Brandl1a3284e2007-12-02 09:40:06 +0000730 builtin = sys.modules['builtins']
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000731 if hasattr(builtin, object.__name__):
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000732 builtinobject = getattr(builtin, object.__name__)
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000733 if builtinobject is object:
734 return builtin
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000735
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000736def findsource(object):
737 """Return the entire source file and starting line number for an object.
738
739 The argument may be a module, class, method, function, traceback, frame,
740 or code object. The source code is returned as a list of all the lines
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200741 in the file and the line number indexes a line in that list. An OSError
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000742 is raised if the source code cannot be retrieved."""
Benjamin Peterson9620cc02011-06-11 15:53:11 -0500743
Yury Selivanovef1e7502014-12-08 16:05:34 -0500744 file = getsourcefile(object)
745 if file:
746 # Invalidate cache if needed.
747 linecache.checkcache(file)
748 else:
749 file = getfile(object)
750 # Allow filenames in form of "<something>" to pass through.
751 # `doctest` monkeypatches `linecache` module to enable
752 # inspection, so let `linecache.getlines` to be called.
753 if not (file.startswith('<') and file.endswith('>')):
754 raise OSError('source code not available')
Benjamin Peterson9620cc02011-06-11 15:53:11 -0500755
Thomas Wouters89f507f2006-12-13 04:49:30 +0000756 module = getmodule(object, file)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000757 if module:
758 lines = linecache.getlines(file, module.__dict__)
759 else:
760 lines = linecache.getlines(file)
Neil Schemenauerf06f8532002-03-23 23:51:04 +0000761 if not lines:
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200762 raise OSError('could not get source code')
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000763
764 if ismodule(object):
765 return lines, 0
766
767 if isclass(object):
768 name = object.__name__
Thomas Wouters89f507f2006-12-13 04:49:30 +0000769 pat = re.compile(r'^(\s*)class\s*' + name + r'\b')
770 # make some effort to find the best matching class definition:
771 # use the one with the least indentation, which is the one
772 # that's most probably not inside a function definition.
773 candidates = []
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000774 for i in range(len(lines)):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000775 match = pat.match(lines[i])
776 if match:
777 # if it's at toplevel, it's already the best one
778 if lines[i][0] == 'c':
779 return lines, i
780 # else add whitespace to candidate list
781 candidates.append((match.group(1), i))
782 if candidates:
783 # this will sort by whitespace, and by line number,
784 # less whitespace first
785 candidates.sort()
786 return lines, candidates[0][1]
Jeremy Hyltonab919022003-06-27 18:41:20 +0000787 else:
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200788 raise OSError('could not find class definition')
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000789
790 if ismethod(object):
Christian Heimesff737952007-11-27 10:40:20 +0000791 object = object.__func__
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000792 if isfunction(object):
Neal Norwitz221085d2007-02-25 20:55:47 +0000793 object = object.__code__
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000794 if istraceback(object):
795 object = object.tb_frame
796 if isframe(object):
797 object = object.f_code
798 if iscode(object):
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000799 if not hasattr(object, 'co_firstlineno'):
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200800 raise OSError('could not find function definition')
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000801 lnum = object.co_firstlineno - 1
Yury Selivanove4e811d2015-07-21 19:01:52 +0300802 pat = re.compile(r'^(\s*def\s)|(\s*async\s+def\s)|(.*(?<!\w)lambda(:|\s))|^(\s*@)')
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000803 while lnum > 0:
Ka-Ping Yeea6e59712001-03-10 09:31:55 +0000804 if pat.match(lines[lnum]): break
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000805 lnum = lnum - 1
806 return lines, lnum
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200807 raise OSError('could not find code object')
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000808
809def getcomments(object):
Jeremy Hyltonb4c17c82002-03-28 23:01:56 +0000810 """Get lines of comments immediately preceding an object's source code.
811
812 Returns None when source can't be found.
813 """
814 try:
815 lines, lnum = findsource(object)
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200816 except (OSError, TypeError):
Jeremy Hyltonb4c17c82002-03-28 23:01:56 +0000817 return None
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000818
819 if ismodule(object):
820 # Look for a comment block at the top of the file.
821 start = 0
Ka-Ping Yeeb910efe2001-04-12 13:17:17 +0000822 if lines and lines[0][:2] == '#!': start = 1
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000823 while start < len(lines) and lines[start].strip() in ('', '#'):
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000824 start = start + 1
Ka-Ping Yeeb910efe2001-04-12 13:17:17 +0000825 if start < len(lines) and lines[start][:1] == '#':
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000826 comments = []
827 end = start
828 while end < len(lines) and lines[end][:1] == '#':
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000829 comments.append(lines[end].expandtabs())
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000830 end = end + 1
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000831 return ''.join(comments)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000832
833 # Look for a preceding block of comments at the same indentation.
834 elif lnum > 0:
835 indent = indentsize(lines[lnum])
836 end = lnum - 1
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000837 if end >= 0 and lines[end].lstrip()[:1] == '#' and \
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000838 indentsize(lines[end]) == indent:
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000839 comments = [lines[end].expandtabs().lstrip()]
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000840 if end > 0:
841 end = end - 1
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000842 comment = lines[end].expandtabs().lstrip()
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000843 while comment[:1] == '#' and indentsize(lines[end]) == indent:
844 comments[:0] = [comment]
845 end = end - 1
846 if end < 0: break
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000847 comment = lines[end].expandtabs().lstrip()
848 while comments and comments[0].strip() == '#':
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000849 comments[:1] = []
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000850 while comments and comments[-1].strip() == '#':
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000851 comments[-1:] = []
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000852 return ''.join(comments)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000853
Tim Peters4efb6e92001-06-29 23:51:08 +0000854class EndOfBlock(Exception): pass
855
856class BlockFinder:
857 """Provide a tokeneater() method to detect the end of a code block."""
858 def __init__(self):
859 self.indent = 0
Johannes Gijsbersa5855d52005-03-12 16:37:11 +0000860 self.islambda = False
Johannes Gijsbers1542f342004-12-12 16:46:28 +0000861 self.started = False
862 self.passline = False
Meador Inge5b718d72015-07-23 22:49:37 -0500863 self.indecorator = False
864 self.decoratorhasargs = False
Armin Rigodd5c0232005-09-25 11:45:45 +0000865 self.last = 1
Tim Peters4efb6e92001-06-29 23:51:08 +0000866
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000867 def tokeneater(self, type, token, srowcol, erowcol, line):
Meador Inge5b718d72015-07-23 22:49:37 -0500868 if not self.started and not self.indecorator:
869 # skip any decorators
870 if token == "@":
871 self.indecorator = True
Armin Rigodd5c0232005-09-25 11:45:45 +0000872 # look for the first "def", "class" or "lambda"
Meador Inge5b718d72015-07-23 22:49:37 -0500873 elif token in ("def", "class", "lambda"):
Johannes Gijsbersa5855d52005-03-12 16:37:11 +0000874 if token == "lambda":
875 self.islambda = True
Johannes Gijsbers1542f342004-12-12 16:46:28 +0000876 self.started = True
Armin Rigodd5c0232005-09-25 11:45:45 +0000877 self.passline = True # skip to the end of the line
Meador Inge5b718d72015-07-23 22:49:37 -0500878 elif token == "(":
879 if self.indecorator:
880 self.decoratorhasargs = True
881 elif token == ")":
882 if self.indecorator:
883 self.indecorator = False
884 self.decoratorhasargs = False
Tim Peters4efb6e92001-06-29 23:51:08 +0000885 elif type == tokenize.NEWLINE:
Armin Rigodd5c0232005-09-25 11:45:45 +0000886 self.passline = False # stop skipping when a NEWLINE is seen
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000887 self.last = srowcol[0]
Armin Rigodd5c0232005-09-25 11:45:45 +0000888 if self.islambda: # lambdas always end at the first NEWLINE
889 raise EndOfBlock
Meador Inge5b718d72015-07-23 22:49:37 -0500890 # hitting a NEWLINE when in a decorator without args
891 # ends the decorator
892 if self.indecorator and not self.decoratorhasargs:
893 self.indecorator = False
Johannes Gijsbers1542f342004-12-12 16:46:28 +0000894 elif self.passline:
895 pass
Tim Peters4efb6e92001-06-29 23:51:08 +0000896 elif type == tokenize.INDENT:
897 self.indent = self.indent + 1
Johannes Gijsbers1542f342004-12-12 16:46:28 +0000898 self.passline = True
Tim Peters4efb6e92001-06-29 23:51:08 +0000899 elif type == tokenize.DEDENT:
900 self.indent = self.indent - 1
Armin Rigodd5c0232005-09-25 11:45:45 +0000901 # the end of matching indent/dedent pairs end a block
902 # (note that this only works for "def"/"class" blocks,
903 # not e.g. for "if: else:" or "try: finally:" blocks)
904 if self.indent <= 0:
905 raise EndOfBlock
906 elif self.indent == 0 and type not in (tokenize.COMMENT, tokenize.NL):
907 # any other token on the same indentation level end the previous
908 # block as well, except the pseudo-tokens COMMENT and NL.
909 raise EndOfBlock
Tim Peters4efb6e92001-06-29 23:51:08 +0000910
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000911def getblock(lines):
912 """Extract the block of code at the top of the given list of lines."""
Armin Rigodd5c0232005-09-25 11:45:45 +0000913 blockfinder = BlockFinder()
Tim Peters4efb6e92001-06-29 23:51:08 +0000914 try:
Trent Nelson428de652008-03-18 22:41:35 +0000915 tokens = tokenize.generate_tokens(iter(lines).__next__)
916 for _token in tokens:
917 blockfinder.tokeneater(*_token)
Armin Rigodd5c0232005-09-25 11:45:45 +0000918 except (EndOfBlock, IndentationError):
919 pass
920 return lines[:blockfinder.last]
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000921
922def getsourcelines(object):
923 """Return a list of source lines and starting line number for an object.
924
925 The argument may be a module, class, method, function, traceback, frame,
926 or code object. The source code is returned as a list of the lines
927 corresponding to the object and the line number indicates where in the
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200928 original source file the first line of code was found. An OSError is
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000929 raised if the source code cannot be retrieved."""
Yury Selivanov081bbf62014-09-26 17:34:54 -0400930 object = unwrap(object)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000931 lines, lnum = findsource(object)
932
Meador Inge5b718d72015-07-23 22:49:37 -0500933 if ismodule(object):
934 return lines, 0
935 else:
936 return getblock(lines[lnum:]), lnum + 1
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000937
938def getsource(object):
939 """Return the text of the source code for an object.
940
941 The argument may be a module, class, method, function, traceback, frame,
942 or code object. The source code is returned as a single string. An
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200943 OSError is raised if the source code cannot be retrieved."""
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000944 lines, lnum = getsourcelines(object)
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000945 return ''.join(lines)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000946
947# --------------------------------------------------- class tree extraction
948def walktree(classes, children, parent):
949 """Recursive helper function for getclasstree()."""
950 results = []
Raymond Hettingera1a992c2005-03-11 06:46:45 +0000951 classes.sort(key=attrgetter('__module__', '__name__'))
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000952 for c in classes:
953 results.append((c, c.__bases__))
Raymond Hettinger54f02222002-06-01 14:18:47 +0000954 if c in children:
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000955 results.append(walktree(children[c], children, c))
956 return results
957
Georg Brandl5ce83a02009-06-01 17:23:51 +0000958def getclasstree(classes, unique=False):
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000959 """Arrange the given list of classes into a hierarchy of nested lists.
960
961 Where a nested list appears, it contains classes derived from the class
962 whose entry immediately precedes the list. Each entry is a 2-tuple
963 containing a class and a tuple of its base classes. If the 'unique'
964 argument is true, exactly one entry appears in the returned structure
965 for each class in the given list. Otherwise, classes using multiple
966 inheritance and their descendants will appear multiple times."""
967 children = {}
968 roots = []
969 for c in classes:
970 if c.__bases__:
971 for parent in c.__bases__:
Raymond Hettinger54f02222002-06-01 14:18:47 +0000972 if not parent in children:
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000973 children[parent] = []
Serhiy Storchaka362c1b52013-09-05 17:14:32 +0300974 if c not in children[parent]:
975 children[parent].append(c)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000976 if unique and parent in classes: break
977 elif c not in roots:
978 roots.append(c)
Raymond Hettingere0d49722002-06-02 18:55:56 +0000979 for parent in children:
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000980 if parent not in classes:
981 roots.append(parent)
982 return walktree(roots, children, None)
983
984# ------------------------------------------------ argument list extraction
Christian Heimes25bb7832008-01-11 16:17:00 +0000985Arguments = namedtuple('Arguments', 'args, varargs, varkw')
986
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000987def getargs(co):
988 """Get information about the arguments accepted by a code object.
989
Guido van Rossum2e65f892007-02-28 22:03:49 +0000990 Three things are returned: (args, varargs, varkw), where
Georg Brandlc1c4bf82010-10-15 16:07:41 +0000991 'args' is the list of argument names. Keyword-only arguments are
992 appended. 'varargs' and 'varkw' are the names of the * and **
993 arguments or None."""
Guido van Rossum2e65f892007-02-28 22:03:49 +0000994 args, varargs, kwonlyargs, varkw = _getfullargs(co)
Christian Heimes25bb7832008-01-11 16:17:00 +0000995 return Arguments(args + kwonlyargs, varargs, varkw)
Guido van Rossum2e65f892007-02-28 22:03:49 +0000996
997def _getfullargs(co):
998 """Get information about the arguments accepted by a code object.
999
1000 Four things are returned: (args, varargs, kwonlyargs, varkw), where
Georg Brandlc1c4bf82010-10-15 16:07:41 +00001001 'args' and 'kwonlyargs' are lists of argument names, and 'varargs'
1002 and 'varkw' are the names of the * and ** arguments or None."""
Jeremy Hylton64967882003-06-27 18:14:39 +00001003
1004 if not iscode(co):
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00001005 raise TypeError('{!r} is not a code object'.format(co))
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001006
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001007 nargs = co.co_argcount
1008 names = co.co_varnames
Guido van Rossum2e65f892007-02-28 22:03:49 +00001009 nkwargs = co.co_kwonlyargcount
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001010 args = list(names[:nargs])
Guido van Rossum2e65f892007-02-28 22:03:49 +00001011 kwonlyargs = list(names[nargs:nargs+nkwargs])
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001012 step = 0
1013
Guido van Rossum2e65f892007-02-28 22:03:49 +00001014 nargs += nkwargs
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001015 varargs = None
1016 if co.co_flags & CO_VARARGS:
1017 varargs = co.co_varnames[nargs]
1018 nargs = nargs + 1
1019 varkw = None
1020 if co.co_flags & CO_VARKEYWORDS:
1021 varkw = co.co_varnames[nargs]
Guido van Rossum2e65f892007-02-28 22:03:49 +00001022 return args, varargs, kwonlyargs, varkw
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001023
Yury Selivanov37dc2b22016-01-11 15:15:01 -05001024
1025ArgSpec = namedtuple('ArgSpec', 'args varargs keywords defaults')
1026
1027def getargspec(func):
Nick Coghlan3c35fdb2016-12-02 20:29:57 +10001028 """Get the names and default values of a function's parameters.
Yury Selivanov37dc2b22016-01-11 15:15:01 -05001029
1030 A tuple of four things is returned: (args, varargs, keywords, defaults).
1031 'args' is a list of the argument names, including keyword-only argument names.
Nick Coghlan3c35fdb2016-12-02 20:29:57 +10001032 'varargs' and 'keywords' are the names of the * and ** parameters or None.
1033 'defaults' is an n-tuple of the default values of the last n parameters.
Yury Selivanov37dc2b22016-01-11 15:15:01 -05001034
Nick Coghlan3c35fdb2016-12-02 20:29:57 +10001035 This function is deprecated, as it does not support annotations or
1036 keyword-only parameters and will raise ValueError if either is present
1037 on the supplied callable.
1038
1039 For a more structured introspection API, use inspect.signature() instead.
1040
1041 Alternatively, use getfullargspec() for an API with a similar namedtuple
1042 based interface, but full support for annotations and keyword-only
1043 parameters.
Yury Selivanov37dc2b22016-01-11 15:15:01 -05001044 """
1045 warnings.warn("inspect.getargspec() is deprecated, "
Nick Coghlan3c35fdb2016-12-02 20:29:57 +10001046 "use inspect.signature() or inspect.getfullargspec()",
1047 DeprecationWarning, stacklevel=2)
Yury Selivanov37dc2b22016-01-11 15:15:01 -05001048 args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults, ann = \
1049 getfullargspec(func)
1050 if kwonlyargs or ann:
Nick Coghlan3c35fdb2016-12-02 20:29:57 +10001051 raise ValueError("Function has keyword-only parameters or annotations"
Yury Selivanov37dc2b22016-01-11 15:15:01 -05001052 ", use getfullargspec() API which can support them")
1053 return ArgSpec(args, varargs, varkw, defaults)
1054
Christian Heimes25bb7832008-01-11 16:17:00 +00001055FullArgSpec = namedtuple('FullArgSpec',
Benjamin Peterson3d4ca742008-11-12 21:39:01 +00001056 'args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults, annotations')
Guido van Rossum2e65f892007-02-28 22:03:49 +00001057
1058def getfullargspec(func):
Nick Coghlan3c35fdb2016-12-02 20:29:57 +10001059 """Get the names and default values of a callable object's parameters.
Guido van Rossum2e65f892007-02-28 22:03:49 +00001060
Brett Cannon504d8852007-09-07 02:12:14 +00001061 A tuple of seven things is returned:
Nick Coghlan3c35fdb2016-12-02 20:29:57 +10001062 (args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults, annotations).
1063 'args' is a list of the parameter names.
1064 'varargs' and 'varkw' are the names of the * and ** parameters or None.
1065 'defaults' is an n-tuple of the default values of the last n parameters.
1066 'kwonlyargs' is a list of keyword-only parameter names.
Guido van Rossum2e65f892007-02-28 22:03:49 +00001067 'kwonlydefaults' is a dictionary mapping names from kwonlyargs to defaults.
Nick Coghlan3c35fdb2016-12-02 20:29:57 +10001068 'annotations' is a dictionary mapping parameter names to annotations.
Guido van Rossuma8add0e2007-05-14 22:03:55 +00001069
Nick Coghlan3c35fdb2016-12-02 20:29:57 +10001070 Notable differences from inspect.signature():
1071 - the "self" parameter is always reported, even for bound methods
1072 - wrapper chains defined by __wrapped__ *not* unwrapped automatically
Jeremy Hylton64967882003-06-27 18:14:39 +00001073 """
1074
Yury Selivanov57d240e2014-02-19 16:27:23 -05001075 try:
1076 # Re: `skip_bound_arg=False`
1077 #
Yury Selivanovd82eddc2014-01-29 11:24:39 -05001078 # There is a notable difference in behaviour between getfullargspec
1079 # and Signature: the former always returns 'self' parameter for bound
1080 # methods, whereas the Signature always shows the actual calling
1081 # signature of the passed object.
1082 #
1083 # To simulate this behaviour, we "unbind" bound methods, to trick
1084 # inspect.signature to always return their first parameter ("self",
1085 # usually)
Yury Selivanovd82eddc2014-01-29 11:24:39 -05001086
Yury Selivanov57d240e2014-02-19 16:27:23 -05001087 # Re: `follow_wrapper_chains=False`
1088 #
1089 # getfullargspec() historically ignored __wrapped__ attributes,
1090 # so we ensure that remains the case in 3.3+
Yury Selivanovd82eddc2014-01-29 11:24:39 -05001091
Yury Selivanov5a23bd02014-03-29 13:47:11 -04001092 sig = _signature_from_callable(func,
1093 follow_wrapper_chains=False,
1094 skip_bound_arg=False,
1095 sigcls=Signature)
Yury Selivanovd82eddc2014-01-29 11:24:39 -05001096 except Exception as ex:
1097 # Most of the times 'signature' will raise ValueError.
1098 # But, it can also raise AttributeError, and, maybe something
1099 # else. So to be fully backwards compatible, we catch all
1100 # possible exceptions here, and reraise a TypeError.
1101 raise TypeError('unsupported callable') from ex
1102
1103 args = []
1104 varargs = None
1105 varkw = None
1106 kwonlyargs = []
1107 defaults = ()
1108 annotations = {}
1109 defaults = ()
1110 kwdefaults = {}
1111
1112 if sig.return_annotation is not sig.empty:
1113 annotations['return'] = sig.return_annotation
1114
1115 for param in sig.parameters.values():
1116 kind = param.kind
1117 name = param.name
1118
1119 if kind is _POSITIONAL_ONLY:
1120 args.append(name)
1121 elif kind is _POSITIONAL_OR_KEYWORD:
1122 args.append(name)
1123 if param.default is not param.empty:
1124 defaults += (param.default,)
1125 elif kind is _VAR_POSITIONAL:
1126 varargs = name
1127 elif kind is _KEYWORD_ONLY:
1128 kwonlyargs.append(name)
1129 if param.default is not param.empty:
1130 kwdefaults[name] = param.default
1131 elif kind is _VAR_KEYWORD:
1132 varkw = name
1133
1134 if param.annotation is not param.empty:
1135 annotations[name] = param.annotation
1136
1137 if not kwdefaults:
1138 # compatibility with 'func.__kwdefaults__'
1139 kwdefaults = None
1140
1141 if not defaults:
1142 # compatibility with 'func.__defaults__'
1143 defaults = None
1144
Yury Selivanovd82eddc2014-01-29 11:24:39 -05001145 return FullArgSpec(args, varargs, varkw, defaults,
1146 kwonlyargs, kwdefaults, annotations)
1147
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001148
Christian Heimes25bb7832008-01-11 16:17:00 +00001149ArgInfo = namedtuple('ArgInfo', 'args varargs keywords locals')
1150
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001151def getargvalues(frame):
1152 """Get information about arguments passed into a particular frame.
1153
1154 A tuple of four things is returned: (args, varargs, varkw, locals).
Georg Brandlc1c4bf82010-10-15 16:07:41 +00001155 'args' is a list of the argument names.
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001156 'varargs' and 'varkw' are the names of the * and ** arguments or None.
1157 'locals' is the locals dictionary of the given frame."""
1158 args, varargs, varkw = getargs(frame.f_code)
Benjamin Peterson1a6e0d02008-10-25 15:49:17 +00001159 return ArgInfo(args, varargs, varkw, frame.f_locals)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001160
Guido van Rossum2e65f892007-02-28 22:03:49 +00001161def formatannotation(annotation, base_module=None):
Guido van Rossum52e50042016-10-22 07:55:18 -07001162 if getattr(annotation, '__module__', None) == 'typing':
1163 return repr(annotation).replace('typing.', '')
Guido van Rossum2e65f892007-02-28 22:03:49 +00001164 if isinstance(annotation, type):
Georg Brandl1a3284e2007-12-02 09:40:06 +00001165 if annotation.__module__ in ('builtins', base_module):
Serhiy Storchaka521e5862014-07-22 15:00:37 +03001166 return annotation.__qualname__
1167 return annotation.__module__+'.'+annotation.__qualname__
Guido van Rossum2e65f892007-02-28 22:03:49 +00001168 return repr(annotation)
Guido van Rossuma8add0e2007-05-14 22:03:55 +00001169
Guido van Rossum2e65f892007-02-28 22:03:49 +00001170def formatannotationrelativeto(object):
Guido van Rossuma8add0e2007-05-14 22:03:55 +00001171 module = getattr(object, '__module__', None)
1172 def _formatannotation(annotation):
1173 return formatannotation(annotation, module)
1174 return _formatannotation
Guido van Rossum2e65f892007-02-28 22:03:49 +00001175
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001176def formatargspec(args, varargs=None, varkw=None, defaults=None,
Guido van Rossum2e65f892007-02-28 22:03:49 +00001177 kwonlyargs=(), kwonlydefaults={}, annotations={},
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001178 formatarg=str,
1179 formatvarargs=lambda name: '*' + name,
1180 formatvarkw=lambda name: '**' + name,
1181 formatvalue=lambda value: '=' + repr(value),
Guido van Rossum2e65f892007-02-28 22:03:49 +00001182 formatreturns=lambda text: ' -> ' + text,
Georg Brandlc1c4bf82010-10-15 16:07:41 +00001183 formatannotation=formatannotation):
Berker Peksagfa3922c2015-07-31 04:11:29 +03001184 """Format an argument spec from the values returned by getfullargspec.
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001185
Guido van Rossum2e65f892007-02-28 22:03:49 +00001186 The first seven arguments are (args, varargs, varkw, defaults,
1187 kwonlyargs, kwonlydefaults, annotations). The other five arguments
1188 are the corresponding optional formatting functions that are called to
1189 turn names and values into strings. The last argument is an optional
1190 function to format the sequence of arguments."""
1191 def formatargandannotation(arg):
1192 result = formatarg(arg)
1193 if arg in annotations:
1194 result += ': ' + formatannotation(annotations[arg])
1195 return result
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001196 specs = []
1197 if defaults:
1198 firstdefault = len(args) - len(defaults)
Benjamin Petersonb58dda72009-01-18 22:27:04 +00001199 for i, arg in enumerate(args):
Georg Brandlc1c4bf82010-10-15 16:07:41 +00001200 spec = formatargandannotation(arg)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001201 if defaults and i >= firstdefault:
1202 spec = spec + formatvalue(defaults[i - firstdefault])
1203 specs.append(spec)
Raymond Hettinger936654b2002-06-01 03:06:31 +00001204 if varargs is not None:
Guido van Rossum2e65f892007-02-28 22:03:49 +00001205 specs.append(formatvarargs(formatargandannotation(varargs)))
1206 else:
1207 if kwonlyargs:
1208 specs.append('*')
1209 if kwonlyargs:
1210 for kwonlyarg in kwonlyargs:
1211 spec = formatargandannotation(kwonlyarg)
Benjamin Peterson9953a8d2009-01-17 04:15:01 +00001212 if kwonlydefaults and kwonlyarg in kwonlydefaults:
Guido van Rossum2e65f892007-02-28 22:03:49 +00001213 spec += formatvalue(kwonlydefaults[kwonlyarg])
1214 specs.append(spec)
Raymond Hettinger936654b2002-06-01 03:06:31 +00001215 if varkw is not None:
Guido van Rossum2e65f892007-02-28 22:03:49 +00001216 specs.append(formatvarkw(formatargandannotation(varkw)))
Neal Norwitz9d72bb42007-04-17 08:48:32 +00001217 result = '(' + ', '.join(specs) + ')'
Guido van Rossum2e65f892007-02-28 22:03:49 +00001218 if 'return' in annotations:
1219 result += formatreturns(formatannotation(annotations['return']))
1220 return result
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001221
1222def formatargvalues(args, varargs, varkw, locals,
1223 formatarg=str,
1224 formatvarargs=lambda name: '*' + name,
1225 formatvarkw=lambda name: '**' + name,
Georg Brandlc1c4bf82010-10-15 16:07:41 +00001226 formatvalue=lambda value: '=' + repr(value)):
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001227 """Format an argument spec from the 4 values returned by getargvalues.
1228
1229 The first four arguments are (args, varargs, varkw, locals). The
1230 next four arguments are the corresponding optional formatting functions
1231 that are called to turn names and values into strings. The ninth
1232 argument is an optional function to format the sequence of arguments."""
1233 def convert(name, locals=locals,
1234 formatarg=formatarg, formatvalue=formatvalue):
1235 return formatarg(name) + formatvalue(locals[name])
1236 specs = []
1237 for i in range(len(args)):
Georg Brandlc1c4bf82010-10-15 16:07:41 +00001238 specs.append(convert(args[i]))
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001239 if varargs:
1240 specs.append(formatvarargs(varargs) + formatvalue(locals[varargs]))
1241 if varkw:
1242 specs.append(formatvarkw(varkw) + formatvalue(locals[varkw]))
Neal Norwitz9d72bb42007-04-17 08:48:32 +00001243 return '(' + ', '.join(specs) + ')'
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001244
Benjamin Petersone109c702011-06-24 09:37:26 -05001245def _missing_arguments(f_name, argnames, pos, values):
1246 names = [repr(name) for name in argnames if name not in values]
1247 missing = len(names)
1248 if missing == 1:
1249 s = names[0]
1250 elif missing == 2:
1251 s = "{} and {}".format(*names)
1252 else:
Yury Selivanovdccfa132014-03-27 18:42:52 -04001253 tail = ", {} and {}".format(*names[-2:])
Benjamin Petersone109c702011-06-24 09:37:26 -05001254 del names[-2:]
1255 s = ", ".join(names) + tail
1256 raise TypeError("%s() missing %i required %s argument%s: %s" %
1257 (f_name, missing,
1258 "positional" if pos else "keyword-only",
1259 "" if missing == 1 else "s", s))
1260
1261def _too_many(f_name, args, kwonly, varargs, defcount, given, values):
Benjamin Petersonb204a422011-06-05 22:04:07 -05001262 atleast = len(args) - defcount
Benjamin Petersonb204a422011-06-05 22:04:07 -05001263 kwonly_given = len([arg for arg in kwonly if arg in values])
1264 if varargs:
1265 plural = atleast != 1
1266 sig = "at least %d" % (atleast,)
1267 elif defcount:
1268 plural = True
1269 sig = "from %d to %d" % (atleast, len(args))
1270 else:
1271 plural = len(args) != 1
1272 sig = str(len(args))
1273 kwonly_sig = ""
1274 if kwonly_given:
1275 msg = " positional argument%s (and %d keyword-only argument%s)"
1276 kwonly_sig = (msg % ("s" if given != 1 else "", kwonly_given,
1277 "s" if kwonly_given != 1 else ""))
1278 raise TypeError("%s() takes %s positional argument%s but %d%s %s given" %
1279 (f_name, sig, "s" if plural else "", given, kwonly_sig,
1280 "was" if given == 1 and not kwonly_given else "were"))
1281
Benjamin Peterson3e6ab172014-01-02 12:24:08 -06001282def getcallargs(*func_and_positional, **named):
Benjamin Peterson25cd7eb2010-03-30 18:42:32 +00001283 """Get the mapping of arguments to values.
1284
1285 A dict is returned, with keys the function argument names (including the
1286 names of the * and ** arguments, if any), and values the respective bound
1287 values from 'positional' and 'named'."""
Benjamin Peterson3e6ab172014-01-02 12:24:08 -06001288 func = func_and_positional[0]
1289 positional = func_and_positional[1:]
Benjamin Peterson25cd7eb2010-03-30 18:42:32 +00001290 spec = getfullargspec(func)
1291 args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults, ann = spec
1292 f_name = func.__name__
1293 arg2value = {}
1294
Benjamin Petersonb204a422011-06-05 22:04:07 -05001295
Benjamin Peterson25cd7eb2010-03-30 18:42:32 +00001296 if ismethod(func) and func.__self__ is not None:
1297 # implicit 'self' (or 'cls' for classmethods) argument
1298 positional = (func.__self__,) + positional
1299 num_pos = len(positional)
Benjamin Peterson25cd7eb2010-03-30 18:42:32 +00001300 num_args = len(args)
1301 num_defaults = len(defaults) if defaults else 0
Benjamin Peterson25cd7eb2010-03-30 18:42:32 +00001302
Benjamin Petersonb204a422011-06-05 22:04:07 -05001303 n = min(num_pos, num_args)
1304 for i in range(n):
1305 arg2value[args[i]] = positional[i]
1306 if varargs:
1307 arg2value[varargs] = tuple(positional[n:])
1308 possible_kwargs = set(args + kwonlyargs)
Benjamin Peterson25cd7eb2010-03-30 18:42:32 +00001309 if varkw:
Benjamin Petersonb204a422011-06-05 22:04:07 -05001310 arg2value[varkw] = {}
1311 for kw, value in named.items():
1312 if kw not in possible_kwargs:
1313 if not varkw:
1314 raise TypeError("%s() got an unexpected keyword argument %r" %
1315 (f_name, kw))
1316 arg2value[varkw][kw] = value
1317 continue
1318 if kw in arg2value:
1319 raise TypeError("%s() got multiple values for argument %r" %
1320 (f_name, kw))
1321 arg2value[kw] = value
1322 if num_pos > num_args and not varargs:
Benjamin Petersone109c702011-06-24 09:37:26 -05001323 _too_many(f_name, args, kwonlyargs, varargs, num_defaults,
1324 num_pos, arg2value)
Benjamin Petersonb204a422011-06-05 22:04:07 -05001325 if num_pos < num_args:
Benjamin Petersone109c702011-06-24 09:37:26 -05001326 req = args[:num_args - num_defaults]
1327 for arg in req:
Benjamin Petersonb204a422011-06-05 22:04:07 -05001328 if arg not in arg2value:
Benjamin Petersone109c702011-06-24 09:37:26 -05001329 _missing_arguments(f_name, req, True, arg2value)
Benjamin Petersonb204a422011-06-05 22:04:07 -05001330 for i, arg in enumerate(args[num_args - num_defaults:]):
1331 if arg not in arg2value:
1332 arg2value[arg] = defaults[i]
Benjamin Petersone109c702011-06-24 09:37:26 -05001333 missing = 0
Benjamin Petersonb204a422011-06-05 22:04:07 -05001334 for kwarg in kwonlyargs:
1335 if kwarg not in arg2value:
Yury Selivanov875df202014-03-27 18:23:03 -04001336 if kwonlydefaults and kwarg in kwonlydefaults:
Benjamin Petersone109c702011-06-24 09:37:26 -05001337 arg2value[kwarg] = kwonlydefaults[kwarg]
1338 else:
1339 missing += 1
1340 if missing:
1341 _missing_arguments(f_name, kwonlyargs, False, arg2value)
Benjamin Peterson25cd7eb2010-03-30 18:42:32 +00001342 return arg2value
1343
Nick Coghlan2f92e542012-06-23 19:39:55 +10001344ClosureVars = namedtuple('ClosureVars', 'nonlocals globals builtins unbound')
1345
1346def getclosurevars(func):
1347 """
1348 Get the mapping of free variables to their current values.
1349
Meador Inge8fda3592012-07-19 21:33:21 -05001350 Returns a named tuple of dicts mapping the current nonlocal, global
Nick Coghlan2f92e542012-06-23 19:39:55 +10001351 and builtin references as seen by the body of the function. A final
1352 set of unbound names that could not be resolved is also provided.
1353 """
1354
1355 if ismethod(func):
1356 func = func.__func__
1357
1358 if not isfunction(func):
1359 raise TypeError("'{!r}' is not a Python function".format(func))
1360
1361 code = func.__code__
1362 # Nonlocal references are named in co_freevars and resolved
1363 # by looking them up in __closure__ by positional index
1364 if func.__closure__ is None:
1365 nonlocal_vars = {}
1366 else:
1367 nonlocal_vars = {
1368 var : cell.cell_contents
1369 for var, cell in zip(code.co_freevars, func.__closure__)
1370 }
1371
1372 # Global and builtin references are named in co_names and resolved
1373 # by looking them up in __globals__ or __builtins__
1374 global_ns = func.__globals__
1375 builtin_ns = global_ns.get("__builtins__", builtins.__dict__)
1376 if ismodule(builtin_ns):
1377 builtin_ns = builtin_ns.__dict__
1378 global_vars = {}
1379 builtin_vars = {}
1380 unbound_names = set()
1381 for name in code.co_names:
1382 if name in ("None", "True", "False"):
1383 # Because these used to be builtins instead of keywords, they
1384 # may still show up as name references. We ignore them.
1385 continue
1386 try:
1387 global_vars[name] = global_ns[name]
1388 except KeyError:
1389 try:
1390 builtin_vars[name] = builtin_ns[name]
1391 except KeyError:
1392 unbound_names.add(name)
1393
1394 return ClosureVars(nonlocal_vars, global_vars,
1395 builtin_vars, unbound_names)
1396
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001397# -------------------------------------------------- stack frame extraction
Christian Heimes25bb7832008-01-11 16:17:00 +00001398
1399Traceback = namedtuple('Traceback', 'filename lineno function code_context index')
1400
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001401def getframeinfo(frame, context=1):
1402 """Get information about a frame or traceback object.
1403
1404 A tuple of five things is returned: the filename, the line number of
1405 the current line, the function name, a list of lines of context from
1406 the source code, and the index of the current line within that list.
1407 The optional second argument specifies the number of lines of context
1408 to return, which are centered around the current line."""
1409 if istraceback(frame):
Andrew M. Kuchlingba8b6bc2004-06-05 14:11:59 +00001410 lineno = frame.tb_lineno
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001411 frame = frame.tb_frame
Andrew M. Kuchlingba8b6bc2004-06-05 14:11:59 +00001412 else:
1413 lineno = frame.f_lineno
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001414 if not isframe(frame):
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00001415 raise TypeError('{!r} is not a frame or traceback object'.format(frame))
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001416
Neil Schemenauerf06f8532002-03-23 23:51:04 +00001417 filename = getsourcefile(frame) or getfile(frame)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001418 if context > 0:
Guido van Rossum54e54c62001-09-04 19:14:14 +00001419 start = lineno - 1 - context//2
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001420 try:
1421 lines, lnum = findsource(frame)
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02001422 except OSError:
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +00001423 lines = index = None
1424 else:
Raymond Hettingera0501712004-06-15 11:22:53 +00001425 start = max(0, min(start, len(lines) - context))
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001426 lines = lines[start:start+context]
Ka-Ping Yee59ade082001-03-01 03:55:35 +00001427 index = lineno - 1 - start
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001428 else:
1429 lines = index = None
1430
Christian Heimes25bb7832008-01-11 16:17:00 +00001431 return Traceback(filename, lineno, frame.f_code.co_name, lines, index)
Ka-Ping Yee59ade082001-03-01 03:55:35 +00001432
1433def getlineno(frame):
1434 """Get the line number from a frame object, allowing for optimization."""
Michael W. Hudsondd32a912002-08-15 14:59:02 +00001435 # FrameType.f_lineno is now a descriptor that grovels co_lnotab
1436 return frame.f_lineno
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001437
Antoine Pitroucdcafb72014-08-24 10:50:28 -04001438FrameInfo = namedtuple('FrameInfo', ('frame',) + Traceback._fields)
1439
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001440def getouterframes(frame, context=1):
1441 """Get a list of records for a frame and all higher (calling) frames.
1442
1443 Each record contains a frame object, filename, line number, function
1444 name, a list of lines of context, and index within the context."""
1445 framelist = []
1446 while frame:
Antoine Pitroucdcafb72014-08-24 10:50:28 -04001447 frameinfo = (frame,) + getframeinfo(frame, context)
1448 framelist.append(FrameInfo(*frameinfo))
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001449 frame = frame.f_back
1450 return framelist
1451
1452def getinnerframes(tb, context=1):
1453 """Get a list of records for a traceback's frame and all lower frames.
1454
1455 Each record contains a frame object, filename, line number, function
1456 name, a list of lines of context, and index within the context."""
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001457 framelist = []
1458 while tb:
Antoine Pitroucdcafb72014-08-24 10:50:28 -04001459 frameinfo = (tb.tb_frame,) + getframeinfo(tb, context)
1460 framelist.append(FrameInfo(*frameinfo))
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001461 tb = tb.tb_next
1462 return framelist
1463
Benjamin Peterson42ac4752010-08-09 13:05:35 +00001464def currentframe():
Benjamin Petersona3a3fc62010-08-09 15:49:56 +00001465 """Return the frame of the caller or None if this is not possible."""
Benjamin Peterson42ac4752010-08-09 13:05:35 +00001466 return sys._getframe(1) if hasattr(sys, "_getframe") else None
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001467
1468def stack(context=1):
1469 """Return a list of records for the stack above the caller's frame."""
Jeremy Hyltonab919022003-06-27 18:41:20 +00001470 return getouterframes(sys._getframe(1), context)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001471
1472def trace(context=1):
Tim Peters85ba6732001-02-28 08:26:44 +00001473 """Return a list of records for the stack below the current exception."""
Fred Draked451ec12002-04-26 02:29:55 +00001474 return getinnerframes(sys.exc_info()[2], context)
Michael Foord95fc51d2010-11-20 15:07:30 +00001475
1476
1477# ------------------------------------------------ static version of getattr
1478
1479_sentinel = object()
1480
Michael Foorde5162652010-11-20 16:40:44 +00001481def _static_getmro(klass):
1482 return type.__dict__['__mro__'].__get__(klass)
1483
Michael Foord95fc51d2010-11-20 15:07:30 +00001484def _check_instance(obj, attr):
1485 instance_dict = {}
1486 try:
1487 instance_dict = object.__getattribute__(obj, "__dict__")
1488 except AttributeError:
1489 pass
Michael Foorddcebe0f2011-03-15 19:20:44 -04001490 return dict.get(instance_dict, attr, _sentinel)
Michael Foord95fc51d2010-11-20 15:07:30 +00001491
1492
1493def _check_class(klass, attr):
Michael Foorde5162652010-11-20 16:40:44 +00001494 for entry in _static_getmro(klass):
Michael Foorda51623b2011-12-18 22:01:40 +00001495 if _shadowed_dict(type(entry)) is _sentinel:
Michael Foorddcebe0f2011-03-15 19:20:44 -04001496 try:
1497 return entry.__dict__[attr]
1498 except KeyError:
1499 pass
Michael Foord95fc51d2010-11-20 15:07:30 +00001500 return _sentinel
1501
Michael Foord35184ed2010-11-20 16:58:30 +00001502def _is_type(obj):
1503 try:
1504 _static_getmro(obj)
1505 except TypeError:
1506 return False
1507 return True
1508
Michael Foorddcebe0f2011-03-15 19:20:44 -04001509def _shadowed_dict(klass):
1510 dict_attr = type.__dict__["__dict__"]
1511 for entry in _static_getmro(klass):
1512 try:
1513 class_dict = dict_attr.__get__(entry)["__dict__"]
1514 except KeyError:
1515 pass
1516 else:
1517 if not (type(class_dict) is types.GetSetDescriptorType and
1518 class_dict.__name__ == "__dict__" and
1519 class_dict.__objclass__ is entry):
Michael Foorda51623b2011-12-18 22:01:40 +00001520 return class_dict
1521 return _sentinel
Michael Foord95fc51d2010-11-20 15:07:30 +00001522
1523def getattr_static(obj, attr, default=_sentinel):
1524 """Retrieve attributes without triggering dynamic lookup via the
1525 descriptor protocol, __getattr__ or __getattribute__.
1526
1527 Note: this function may not be able to retrieve all attributes
1528 that getattr can fetch (like dynamically created attributes)
1529 and may find attributes that getattr can't (like descriptors
1530 that raise AttributeError). It can also return descriptor objects
1531 instead of instance members in some cases. See the
1532 documentation for details.
1533 """
1534 instance_result = _sentinel
Michael Foord35184ed2010-11-20 16:58:30 +00001535 if not _is_type(obj):
Michael Foordcc7ebb82010-11-20 16:20:16 +00001536 klass = type(obj)
Michael Foorda51623b2011-12-18 22:01:40 +00001537 dict_attr = _shadowed_dict(klass)
1538 if (dict_attr is _sentinel or
1539 type(dict_attr) is types.MemberDescriptorType):
Michael Foorddcebe0f2011-03-15 19:20:44 -04001540 instance_result = _check_instance(obj, attr)
Michael Foord95fc51d2010-11-20 15:07:30 +00001541 else:
1542 klass = obj
1543
1544 klass_result = _check_class(klass, attr)
1545
1546 if instance_result is not _sentinel and klass_result is not _sentinel:
1547 if (_check_class(type(klass_result), '__get__') is not _sentinel and
1548 _check_class(type(klass_result), '__set__') is not _sentinel):
1549 return klass_result
1550
1551 if instance_result is not _sentinel:
1552 return instance_result
1553 if klass_result is not _sentinel:
1554 return klass_result
1555
1556 if obj is klass:
1557 # for types we check the metaclass too
Michael Foorde5162652010-11-20 16:40:44 +00001558 for entry in _static_getmro(type(klass)):
Michael Foord3ba95f82011-12-22 01:13:37 +00001559 if _shadowed_dict(type(entry)) is _sentinel:
1560 try:
1561 return entry.__dict__[attr]
1562 except KeyError:
1563 pass
Michael Foord95fc51d2010-11-20 15:07:30 +00001564 if default is not _sentinel:
1565 return default
1566 raise AttributeError(attr)
Nick Coghlane0f04652010-11-21 03:44:04 +00001567
1568
Nick Coghlan04e2e3f2012-06-23 19:52:05 +10001569# ------------------------------------------------ generator introspection
1570
Nick Coghlan7921b9f2010-11-30 06:36:04 +00001571GEN_CREATED = 'GEN_CREATED'
1572GEN_RUNNING = 'GEN_RUNNING'
1573GEN_SUSPENDED = 'GEN_SUSPENDED'
1574GEN_CLOSED = 'GEN_CLOSED'
Nick Coghlane0f04652010-11-21 03:44:04 +00001575
1576def getgeneratorstate(generator):
1577 """Get current state of a generator-iterator.
1578
1579 Possible states are:
1580 GEN_CREATED: Waiting to start execution.
1581 GEN_RUNNING: Currently being executed by the interpreter.
1582 GEN_SUSPENDED: Currently suspended at a yield expression.
1583 GEN_CLOSED: Execution has completed.
1584 """
1585 if generator.gi_running:
1586 return GEN_RUNNING
1587 if generator.gi_frame is None:
1588 return GEN_CLOSED
1589 if generator.gi_frame.f_lasti == -1:
1590 return GEN_CREATED
1591 return GEN_SUSPENDED
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07001592
1593
Nick Coghlan04e2e3f2012-06-23 19:52:05 +10001594def getgeneratorlocals(generator):
1595 """
1596 Get the mapping of generator local variables to their current values.
1597
1598 A dict is returned, with the keys the local variable names and values the
1599 bound values."""
1600
1601 if not isgenerator(generator):
1602 raise TypeError("'{!r}' is not a Python generator".format(generator))
1603
1604 frame = getattr(generator, "gi_frame", None)
1605 if frame is not None:
1606 return generator.gi_frame.f_locals
1607 else:
1608 return {}
1609
Yury Selivanov5376ba92015-06-22 12:19:30 -04001610
1611# ------------------------------------------------ coroutine introspection
1612
1613CORO_CREATED = 'CORO_CREATED'
1614CORO_RUNNING = 'CORO_RUNNING'
1615CORO_SUSPENDED = 'CORO_SUSPENDED'
1616CORO_CLOSED = 'CORO_CLOSED'
1617
1618def getcoroutinestate(coroutine):
1619 """Get current state of a coroutine object.
1620
1621 Possible states are:
1622 CORO_CREATED: Waiting to start execution.
1623 CORO_RUNNING: Currently being executed by the interpreter.
1624 CORO_SUSPENDED: Currently suspended at an await expression.
1625 CORO_CLOSED: Execution has completed.
1626 """
1627 if coroutine.cr_running:
1628 return CORO_RUNNING
1629 if coroutine.cr_frame is None:
1630 return CORO_CLOSED
1631 if coroutine.cr_frame.f_lasti == -1:
1632 return CORO_CREATED
1633 return CORO_SUSPENDED
1634
1635
1636def getcoroutinelocals(coroutine):
1637 """
1638 Get the mapping of coroutine local variables to their current values.
1639
1640 A dict is returned, with the keys the local variable names and values the
1641 bound values."""
1642 frame = getattr(coroutine, "cr_frame", None)
1643 if frame is not None:
1644 return frame.f_locals
1645 else:
1646 return {}
1647
1648
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07001649###############################################################################
1650### Function Signature Object (PEP 362)
1651###############################################################################
1652
1653
1654_WrapperDescriptor = type(type.__call__)
1655_MethodWrapper = type(all.__call__)
Larry Hastings5c661892014-01-24 06:17:25 -08001656_ClassMethodWrapper = type(int.__dict__['from_bytes'])
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07001657
1658_NonUserDefinedCallables = (_WrapperDescriptor,
1659 _MethodWrapper,
Larry Hastings5c661892014-01-24 06:17:25 -08001660 _ClassMethodWrapper,
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07001661 types.BuiltinFunctionType)
1662
1663
Yury Selivanov421f0c72014-01-29 12:05:40 -05001664def _signature_get_user_defined_method(cls, method_name):
Yury Selivanov5a23bd02014-03-29 13:47:11 -04001665 """Private helper. Checks if ``cls`` has an attribute
1666 named ``method_name`` and returns it only if it is a
1667 pure python function.
1668 """
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07001669 try:
1670 meth = getattr(cls, method_name)
1671 except AttributeError:
1672 return
1673 else:
1674 if not isinstance(meth, _NonUserDefinedCallables):
1675 # Once '__signature__' will be added to 'C'-level
1676 # callables, this check won't be necessary
1677 return meth
1678
1679
Yury Selivanov62560fb2014-01-28 12:26:24 -05001680def _signature_get_partial(wrapped_sig, partial, extra_args=()):
Yury Selivanov5a23bd02014-03-29 13:47:11 -04001681 """Private helper to calculate how 'wrapped_sig' signature will
1682 look like after applying a 'functools.partial' object (or alike)
1683 on it.
1684 """
Yury Selivanov62560fb2014-01-28 12:26:24 -05001685
Yury Selivanov3f73ca22014-04-08 11:30:45 -04001686 old_params = wrapped_sig.parameters
1687 new_params = OrderedDict(old_params.items())
Yury Selivanovda5fe4f2014-01-27 17:28:37 -05001688
1689 partial_args = partial.args or ()
1690 partial_keywords = partial.keywords or {}
1691
1692 if extra_args:
1693 partial_args = extra_args + partial_args
1694
1695 try:
1696 ba = wrapped_sig.bind_partial(*partial_args, **partial_keywords)
1697 except TypeError as ex:
1698 msg = 'partial object {!r} has incorrect arguments'.format(partial)
1699 raise ValueError(msg) from ex
1700
Yury Selivanovda5fe4f2014-01-27 17:28:37 -05001701
Yury Selivanov3f73ca22014-04-08 11:30:45 -04001702 transform_to_kwonly = False
1703 for param_name, param in old_params.items():
1704 try:
1705 arg_value = ba.arguments[param_name]
1706 except KeyError:
1707 pass
1708 else:
1709 if param.kind is _POSITIONAL_ONLY:
1710 # If positional-only parameter is bound by partial,
1711 # it effectively disappears from the signature
1712 new_params.pop(param_name)
1713 continue
1714
1715 if param.kind is _POSITIONAL_OR_KEYWORD:
1716 if param_name in partial_keywords:
1717 # This means that this parameter, and all parameters
1718 # after it should be keyword-only (and var-positional
1719 # should be removed). Here's why. Consider the following
1720 # function:
1721 # foo(a, b, *args, c):
1722 # pass
1723 #
1724 # "partial(foo, a='spam')" will have the following
1725 # signature: "(*, a='spam', b, c)". Because attempting
1726 # to call that partial with "(10, 20)" arguments will
1727 # raise a TypeError, saying that "a" argument received
1728 # multiple values.
1729 transform_to_kwonly = True
1730 # Set the new default value
1731 new_params[param_name] = param.replace(default=arg_value)
1732 else:
1733 # was passed as a positional argument
1734 new_params.pop(param.name)
1735 continue
1736
1737 if param.kind is _KEYWORD_ONLY:
1738 # Set the new default value
1739 new_params[param_name] = param.replace(default=arg_value)
1740
1741 if transform_to_kwonly:
1742 assert param.kind is not _POSITIONAL_ONLY
1743
1744 if param.kind is _POSITIONAL_OR_KEYWORD:
1745 new_param = new_params[param_name].replace(kind=_KEYWORD_ONLY)
1746 new_params[param_name] = new_param
1747 new_params.move_to_end(param_name)
1748 elif param.kind in (_KEYWORD_ONLY, _VAR_KEYWORD):
1749 new_params.move_to_end(param_name)
1750 elif param.kind is _VAR_POSITIONAL:
1751 new_params.pop(param.name)
Yury Selivanovda5fe4f2014-01-27 17:28:37 -05001752
1753 return wrapped_sig.replace(parameters=new_params.values())
1754
1755
Yury Selivanov62560fb2014-01-28 12:26:24 -05001756def _signature_bound_method(sig):
Yury Selivanov5a23bd02014-03-29 13:47:11 -04001757 """Private helper to transform signatures for unbound
1758 functions to bound methods.
1759 """
Yury Selivanov62560fb2014-01-28 12:26:24 -05001760
1761 params = tuple(sig.parameters.values())
1762
1763 if not params or params[0].kind in (_VAR_KEYWORD, _KEYWORD_ONLY):
1764 raise ValueError('invalid method signature')
1765
1766 kind = params[0].kind
1767 if kind in (_POSITIONAL_OR_KEYWORD, _POSITIONAL_ONLY):
1768 # Drop first parameter:
1769 # '(p1, p2[, ...])' -> '(p2[, ...])'
1770 params = params[1:]
1771 else:
1772 if kind is not _VAR_POSITIONAL:
1773 # Unless we add a new parameter type we never
1774 # get here
1775 raise ValueError('invalid argument type')
1776 # It's a var-positional parameter.
1777 # Do nothing. '(*args[, ...])' -> '(*args[, ...])'
1778
1779 return sig.replace(parameters=params)
1780
1781
Yury Selivanovb77511d2014-01-29 10:46:14 -05001782def _signature_is_builtin(obj):
Yury Selivanov5a23bd02014-03-29 13:47:11 -04001783 """Private helper to test if `obj` is a callable that might
1784 support Argument Clinic's __text_signature__ protocol.
1785 """
Yury Selivanov1d241832014-02-02 12:51:20 -05001786 return (isbuiltin(obj) or
Yury Selivanovb77511d2014-01-29 10:46:14 -05001787 ismethoddescriptor(obj) or
Yury Selivanov1d241832014-02-02 12:51:20 -05001788 isinstance(obj, _NonUserDefinedCallables) or
Yury Selivanovb77511d2014-01-29 10:46:14 -05001789 # Can't test 'isinstance(type)' here, as it would
1790 # also be True for regular python classes
1791 obj in (type, object))
1792
1793
Yury Selivanov63da7c72014-01-31 14:48:37 -05001794def _signature_is_functionlike(obj):
Yury Selivanov5a23bd02014-03-29 13:47:11 -04001795 """Private helper to test if `obj` is a duck type of FunctionType.
1796 A good example of such objects are functions compiled with
1797 Cython, which have all attributes that a pure Python function
1798 would have, but have their code statically compiled.
1799 """
Yury Selivanov63da7c72014-01-31 14:48:37 -05001800
1801 if not callable(obj) or isclass(obj):
1802 # All function-like objects are obviously callables,
1803 # and not classes.
1804 return False
1805
1806 name = getattr(obj, '__name__', None)
1807 code = getattr(obj, '__code__', None)
1808 defaults = getattr(obj, '__defaults__', _void) # Important to use _void ...
1809 kwdefaults = getattr(obj, '__kwdefaults__', _void) # ... and not None here
1810 annotations = getattr(obj, '__annotations__', None)
1811
1812 return (isinstance(code, types.CodeType) and
1813 isinstance(name, str) and
1814 (defaults is None or isinstance(defaults, tuple)) and
1815 (kwdefaults is None or isinstance(kwdefaults, dict)) and
1816 isinstance(annotations, dict))
1817
1818
Yury Selivanovd82eddc2014-01-29 11:24:39 -05001819def _signature_get_bound_param(spec):
Yury Selivanov5a23bd02014-03-29 13:47:11 -04001820 """ Private helper to get first parameter name from a
1821 __text_signature__ of a builtin method, which should
1822 be in the following format: '($param1, ...)'.
1823 Assumptions are that the first argument won't have
1824 a default value or an annotation.
1825 """
Yury Selivanovd82eddc2014-01-29 11:24:39 -05001826
1827 assert spec.startswith('($')
1828
1829 pos = spec.find(',')
1830 if pos == -1:
1831 pos = spec.find(')')
1832
1833 cpos = spec.find(':')
1834 assert cpos == -1 or cpos > pos
1835
1836 cpos = spec.find('=')
1837 assert cpos == -1 or cpos > pos
1838
1839 return spec[2:pos]
1840
1841
Larry Hastings2623c8c2014-02-08 22:15:29 -08001842def _signature_strip_non_python_syntax(signature):
1843 """
Yury Selivanov5a23bd02014-03-29 13:47:11 -04001844 Private helper function. Takes a signature in Argument Clinic's
1845 extended signature format.
1846
Larry Hastings2623c8c2014-02-08 22:15:29 -08001847 Returns a tuple of three things:
1848 * that signature re-rendered in standard Python syntax,
1849 * the index of the "self" parameter (generally 0), or None if
1850 the function does not have a "self" parameter, and
1851 * the index of the last "positional only" parameter,
1852 or None if the signature has no positional-only parameters.
1853 """
1854
1855 if not signature:
1856 return signature, None, None
1857
1858 self_parameter = None
1859 last_positional_only = None
1860
1861 lines = [l.encode('ascii') for l in signature.split('\n')]
1862 generator = iter(lines).__next__
1863 token_stream = tokenize.tokenize(generator)
1864
1865 delayed_comma = False
1866 skip_next_comma = False
1867 text = []
1868 add = text.append
1869
1870 current_parameter = 0
1871 OP = token.OP
1872 ERRORTOKEN = token.ERRORTOKEN
1873
1874 # token stream always starts with ENCODING token, skip it
1875 t = next(token_stream)
1876 assert t.type == tokenize.ENCODING
1877
1878 for t in token_stream:
1879 type, string = t.type, t.string
1880
1881 if type == OP:
1882 if string == ',':
1883 if skip_next_comma:
1884 skip_next_comma = False
1885 else:
1886 assert not delayed_comma
1887 delayed_comma = True
1888 current_parameter += 1
1889 continue
1890
1891 if string == '/':
1892 assert not skip_next_comma
1893 assert last_positional_only is None
1894 skip_next_comma = True
1895 last_positional_only = current_parameter - 1
1896 continue
1897
1898 if (type == ERRORTOKEN) and (string == '$'):
1899 assert self_parameter is None
1900 self_parameter = current_parameter
1901 continue
1902
1903 if delayed_comma:
1904 delayed_comma = False
1905 if not ((type == OP) and (string == ')')):
1906 add(', ')
1907 add(string)
1908 if (string == ','):
1909 add(' ')
1910 clean_signature = ''.join(text)
1911 return clean_signature, self_parameter, last_positional_only
1912
1913
Yury Selivanov57d240e2014-02-19 16:27:23 -05001914def _signature_fromstr(cls, obj, s, skip_bound_arg=True):
Yury Selivanov5a23bd02014-03-29 13:47:11 -04001915 """Private helper to parse content of '__text_signature__'
1916 and return a Signature based on it.
1917 """
1918
Yury Selivanov7d2bfed2014-02-03 02:46:07 -05001919 Parameter = cls._parameter_cls
1920
Larry Hastings2623c8c2014-02-08 22:15:29 -08001921 clean_signature, self_parameter, last_positional_only = \
1922 _signature_strip_non_python_syntax(s)
Yury Selivanov7d2bfed2014-02-03 02:46:07 -05001923
Larry Hastings2623c8c2014-02-08 22:15:29 -08001924 program = "def foo" + clean_signature + ": pass"
Yury Selivanov7d2bfed2014-02-03 02:46:07 -05001925
1926 try:
Larry Hastings2623c8c2014-02-08 22:15:29 -08001927 module = ast.parse(program)
Yury Selivanov7d2bfed2014-02-03 02:46:07 -05001928 except SyntaxError:
1929 module = None
1930
1931 if not isinstance(module, ast.Module):
1932 raise ValueError("{!r} builtin has invalid signature".format(obj))
1933
1934 f = module.body[0]
1935
1936 parameters = []
1937 empty = Parameter.empty
1938 invalid = object()
1939
1940 module = None
1941 module_dict = {}
1942 module_name = getattr(obj, '__module__', None)
1943 if module_name:
1944 module = sys.modules.get(module_name, None)
1945 if module:
1946 module_dict = module.__dict__
1947 sys_module_dict = sys.modules
1948
1949 def parse_name(node):
1950 assert isinstance(node, ast.arg)
1951 if node.annotation != None:
1952 raise ValueError("Annotations are not currently supported")
1953 return node.arg
1954
1955 def wrap_value(s):
1956 try:
1957 value = eval(s, module_dict)
1958 except NameError:
1959 try:
1960 value = eval(s, sys_module_dict)
1961 except NameError:
1962 raise RuntimeError()
1963
1964 if isinstance(value, str):
1965 return ast.Str(value)
1966 if isinstance(value, (int, float)):
1967 return ast.Num(value)
1968 if isinstance(value, bytes):
1969 return ast.Bytes(value)
1970 if value in (True, False, None):
1971 return ast.NameConstant(value)
1972 raise RuntimeError()
1973
1974 class RewriteSymbolics(ast.NodeTransformer):
1975 def visit_Attribute(self, node):
1976 a = []
1977 n = node
1978 while isinstance(n, ast.Attribute):
1979 a.append(n.attr)
1980 n = n.value
1981 if not isinstance(n, ast.Name):
1982 raise RuntimeError()
1983 a.append(n.id)
1984 value = ".".join(reversed(a))
1985 return wrap_value(value)
1986
1987 def visit_Name(self, node):
1988 if not isinstance(node.ctx, ast.Load):
1989 raise ValueError()
1990 return wrap_value(node.id)
1991
1992 def p(name_node, default_node, default=empty):
1993 name = parse_name(name_node)
1994 if name is invalid:
1995 return None
1996 if default_node and default_node is not _empty:
1997 try:
1998 default_node = RewriteSymbolics().visit(default_node)
1999 o = ast.literal_eval(default_node)
2000 except ValueError:
2001 o = invalid
2002 if o is invalid:
2003 return None
2004 default = o if o is not invalid else default
2005 parameters.append(Parameter(name, kind, default=default, annotation=empty))
2006
2007 # non-keyword-only parameters
2008 args = reversed(f.args.args)
2009 defaults = reversed(f.args.defaults)
2010 iter = itertools.zip_longest(args, defaults, fillvalue=None)
Larry Hastings2623c8c2014-02-08 22:15:29 -08002011 if last_positional_only is not None:
2012 kind = Parameter.POSITIONAL_ONLY
2013 else:
2014 kind = Parameter.POSITIONAL_OR_KEYWORD
2015 for i, (name, default) in enumerate(reversed(list(iter))):
Yury Selivanov7d2bfed2014-02-03 02:46:07 -05002016 p(name, default)
Larry Hastings2623c8c2014-02-08 22:15:29 -08002017 if i == last_positional_only:
2018 kind = Parameter.POSITIONAL_OR_KEYWORD
Yury Selivanov7d2bfed2014-02-03 02:46:07 -05002019
2020 # *args
2021 if f.args.vararg:
2022 kind = Parameter.VAR_POSITIONAL
2023 p(f.args.vararg, empty)
2024
2025 # keyword-only arguments
2026 kind = Parameter.KEYWORD_ONLY
2027 for name, default in zip(f.args.kwonlyargs, f.args.kw_defaults):
2028 p(name, default)
2029
2030 # **kwargs
2031 if f.args.kwarg:
2032 kind = Parameter.VAR_KEYWORD
2033 p(f.args.kwarg, empty)
2034
Larry Hastings2623c8c2014-02-08 22:15:29 -08002035 if self_parameter is not None:
Yury Selivanov8c185ee2014-02-21 01:32:42 -05002036 # Possibly strip the bound argument:
2037 # - We *always* strip first bound argument if
2038 # it is a module.
2039 # - We don't strip first bound argument if
2040 # skip_bound_arg is False.
Yury Selivanov7d2bfed2014-02-03 02:46:07 -05002041 assert parameters
Yury Selivanov8c185ee2014-02-21 01:32:42 -05002042 _self = getattr(obj, '__self__', None)
2043 self_isbound = _self is not None
2044 self_ismodule = ismodule(_self)
2045 if self_isbound and (self_ismodule or skip_bound_arg):
Yury Selivanov7d2bfed2014-02-03 02:46:07 -05002046 parameters.pop(0)
2047 else:
2048 # for builtins, self parameter is always positional-only!
2049 p = parameters[0].replace(kind=Parameter.POSITIONAL_ONLY)
2050 parameters[0] = p
2051
2052 return cls(parameters, return_annotation=cls.empty)
2053
2054
Yury Selivanov57d240e2014-02-19 16:27:23 -05002055def _signature_from_builtin(cls, func, skip_bound_arg=True):
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002056 """Private helper function to get signature for
2057 builtin callables.
2058 """
2059
Yury Selivanov57d240e2014-02-19 16:27:23 -05002060 if not _signature_is_builtin(func):
2061 raise TypeError("{!r} is not a Python builtin "
2062 "function".format(func))
2063
2064 s = getattr(func, "__text_signature__", None)
2065 if not s:
2066 raise ValueError("no signature found for builtin {!r}".format(func))
2067
2068 return _signature_fromstr(cls, func, s, skip_bound_arg)
2069
2070
Yury Selivanovcf45f022015-05-20 14:38:50 -04002071def _signature_from_function(cls, func):
2072 """Private helper: constructs Signature for the given python function."""
2073
2074 is_duck_function = False
2075 if not isfunction(func):
2076 if _signature_is_functionlike(func):
2077 is_duck_function = True
2078 else:
2079 # If it's not a pure Python function, and not a duck type
2080 # of pure function:
2081 raise TypeError('{!r} is not a Python function'.format(func))
2082
2083 Parameter = cls._parameter_cls
2084
2085 # Parameter information.
2086 func_code = func.__code__
2087 pos_count = func_code.co_argcount
2088 arg_names = func_code.co_varnames
2089 positional = tuple(arg_names[:pos_count])
2090 keyword_only_count = func_code.co_kwonlyargcount
2091 keyword_only = arg_names[pos_count:(pos_count + keyword_only_count)]
2092 annotations = func.__annotations__
2093 defaults = func.__defaults__
2094 kwdefaults = func.__kwdefaults__
2095
2096 if defaults:
2097 pos_default_count = len(defaults)
2098 else:
2099 pos_default_count = 0
2100
2101 parameters = []
2102
2103 # Non-keyword-only parameters w/o defaults.
2104 non_default_count = pos_count - pos_default_count
2105 for name in positional[:non_default_count]:
2106 annotation = annotations.get(name, _empty)
2107 parameters.append(Parameter(name, annotation=annotation,
2108 kind=_POSITIONAL_OR_KEYWORD))
2109
2110 # ... w/ defaults.
2111 for offset, name in enumerate(positional[non_default_count:]):
2112 annotation = annotations.get(name, _empty)
2113 parameters.append(Parameter(name, annotation=annotation,
2114 kind=_POSITIONAL_OR_KEYWORD,
2115 default=defaults[offset]))
2116
2117 # *args
2118 if func_code.co_flags & CO_VARARGS:
2119 name = arg_names[pos_count + keyword_only_count]
2120 annotation = annotations.get(name, _empty)
2121 parameters.append(Parameter(name, annotation=annotation,
2122 kind=_VAR_POSITIONAL))
2123
2124 # Keyword-only parameters.
2125 for name in keyword_only:
2126 default = _empty
2127 if kwdefaults is not None:
2128 default = kwdefaults.get(name, _empty)
2129
2130 annotation = annotations.get(name, _empty)
2131 parameters.append(Parameter(name, annotation=annotation,
2132 kind=_KEYWORD_ONLY,
2133 default=default))
2134 # **kwargs
2135 if func_code.co_flags & CO_VARKEYWORDS:
2136 index = pos_count + keyword_only_count
2137 if func_code.co_flags & CO_VARARGS:
2138 index += 1
2139
2140 name = arg_names[index]
2141 annotation = annotations.get(name, _empty)
2142 parameters.append(Parameter(name, annotation=annotation,
2143 kind=_VAR_KEYWORD))
2144
2145 # Is 'func' is a pure Python function - don't validate the
2146 # parameters list (for correct order and defaults), it should be OK.
2147 return cls(parameters,
2148 return_annotation=annotations.get('return', _empty),
2149 __validate_parameters__=is_duck_function)
2150
2151
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002152def _signature_from_callable(obj, *,
2153 follow_wrapper_chains=True,
2154 skip_bound_arg=True,
2155 sigcls):
2156
2157 """Private helper function to get signature for arbitrary
2158 callable objects.
2159 """
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002160
2161 if not callable(obj):
2162 raise TypeError('{!r} is not a callable object'.format(obj))
2163
2164 if isinstance(obj, types.MethodType):
2165 # In this case we skip the first parameter of the underlying
2166 # function (usually `self` or `cls`).
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002167 sig = _signature_from_callable(
Yury Selivanovda396452014-03-27 12:09:24 -04002168 obj.__func__,
2169 follow_wrapper_chains=follow_wrapper_chains,
2170 skip_bound_arg=skip_bound_arg,
2171 sigcls=sigcls)
2172
Yury Selivanov57d240e2014-02-19 16:27:23 -05002173 if skip_bound_arg:
2174 return _signature_bound_method(sig)
2175 else:
2176 return sig
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002177
Nick Coghlane8c45d62013-07-28 20:00:01 +10002178 # Was this function wrapped by a decorator?
Yury Selivanov57d240e2014-02-19 16:27:23 -05002179 if follow_wrapper_chains:
2180 obj = unwrap(obj, stop=(lambda f: hasattr(f, "__signature__")))
Yury Selivanov46c759d2015-05-27 21:56:53 -04002181 if isinstance(obj, types.MethodType):
2182 # If the unwrapped object is a *method*, we might want to
2183 # skip its first parameter (self).
2184 # See test_signature_wrapped_bound_method for details.
Yury Selivanov507cd3c2015-05-27 21:59:03 -04002185 return _signature_from_callable(
Yury Selivanov46c759d2015-05-27 21:56:53 -04002186 obj,
2187 follow_wrapper_chains=follow_wrapper_chains,
Yury Selivanov507cd3c2015-05-27 21:59:03 -04002188 skip_bound_arg=skip_bound_arg,
2189 sigcls=sigcls)
Nick Coghlane8c45d62013-07-28 20:00:01 +10002190
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002191 try:
2192 sig = obj.__signature__
2193 except AttributeError:
2194 pass
2195 else:
2196 if sig is not None:
Yury Selivanov42407ab2014-06-23 10:23:50 -07002197 if not isinstance(sig, Signature):
2198 raise TypeError(
2199 'unexpected object {!r} in __signature__ '
2200 'attribute'.format(sig))
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002201 return sig
2202
Yury Selivanovda5fe4f2014-01-27 17:28:37 -05002203 try:
2204 partialmethod = obj._partialmethod
2205 except AttributeError:
2206 pass
2207 else:
Yury Selivanov0486f812014-01-29 12:18:59 -05002208 if isinstance(partialmethod, functools.partialmethod):
2209 # Unbound partialmethod (see functools.partialmethod)
2210 # This means, that we need to calculate the signature
2211 # as if it's a regular partial object, but taking into
2212 # account that the first positional argument
2213 # (usually `self`, or `cls`) will not be passed
2214 # automatically (as for boundmethods)
Yury Selivanovda5fe4f2014-01-27 17:28:37 -05002215
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002216 wrapped_sig = _signature_from_callable(
Yury Selivanovda396452014-03-27 12:09:24 -04002217 partialmethod.func,
2218 follow_wrapper_chains=follow_wrapper_chains,
2219 skip_bound_arg=skip_bound_arg,
2220 sigcls=sigcls)
2221
Yury Selivanov0486f812014-01-29 12:18:59 -05002222 sig = _signature_get_partial(wrapped_sig, partialmethod, (None,))
Yury Selivanovda5fe4f2014-01-27 17:28:37 -05002223
Yury Selivanov0486f812014-01-29 12:18:59 -05002224 first_wrapped_param = tuple(wrapped_sig.parameters.values())[0]
2225 new_params = (first_wrapped_param,) + tuple(sig.parameters.values())
Yury Selivanovda5fe4f2014-01-27 17:28:37 -05002226
Yury Selivanov0486f812014-01-29 12:18:59 -05002227 return sig.replace(parameters=new_params)
Yury Selivanovda5fe4f2014-01-27 17:28:37 -05002228
Yury Selivanov63da7c72014-01-31 14:48:37 -05002229 if isfunction(obj) or _signature_is_functionlike(obj):
2230 # If it's a pure Python function, or an object that is duck type
2231 # of a Python function (Cython functions, for instance), then:
Yury Selivanovcf45f022015-05-20 14:38:50 -04002232 return _signature_from_function(sigcls, obj)
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002233
Yury Selivanova773de02014-02-21 18:30:53 -05002234 if _signature_is_builtin(obj):
Yury Selivanovda396452014-03-27 12:09:24 -04002235 return _signature_from_builtin(sigcls, obj,
Yury Selivanova773de02014-02-21 18:30:53 -05002236 skip_bound_arg=skip_bound_arg)
2237
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002238 if isinstance(obj, functools.partial):
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002239 wrapped_sig = _signature_from_callable(
Yury Selivanovda396452014-03-27 12:09:24 -04002240 obj.func,
2241 follow_wrapper_chains=follow_wrapper_chains,
2242 skip_bound_arg=skip_bound_arg,
2243 sigcls=sigcls)
Yury Selivanov62560fb2014-01-28 12:26:24 -05002244 return _signature_get_partial(wrapped_sig, obj)
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002245
2246 sig = None
2247 if isinstance(obj, type):
2248 # obj is a class or a metaclass
2249
2250 # First, let's see if it has an overloaded __call__ defined
2251 # in its metaclass
Yury Selivanov421f0c72014-01-29 12:05:40 -05002252 call = _signature_get_user_defined_method(type(obj), '__call__')
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002253 if call is not None:
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002254 sig = _signature_from_callable(
Yury Selivanovda396452014-03-27 12:09:24 -04002255 call,
2256 follow_wrapper_chains=follow_wrapper_chains,
2257 skip_bound_arg=skip_bound_arg,
2258 sigcls=sigcls)
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002259 else:
2260 # Now we check if the 'obj' class has a '__new__' method
Yury Selivanov421f0c72014-01-29 12:05:40 -05002261 new = _signature_get_user_defined_method(obj, '__new__')
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002262 if new is not None:
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002263 sig = _signature_from_callable(
Yury Selivanovda396452014-03-27 12:09:24 -04002264 new,
2265 follow_wrapper_chains=follow_wrapper_chains,
2266 skip_bound_arg=skip_bound_arg,
2267 sigcls=sigcls)
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002268 else:
2269 # Finally, we should have at least __init__ implemented
Yury Selivanov421f0c72014-01-29 12:05:40 -05002270 init = _signature_get_user_defined_method(obj, '__init__')
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002271 if init is not None:
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002272 sig = _signature_from_callable(
Yury Selivanovda396452014-03-27 12:09:24 -04002273 init,
2274 follow_wrapper_chains=follow_wrapper_chains,
2275 skip_bound_arg=skip_bound_arg,
2276 sigcls=sigcls)
Yury Selivanove7dcc5e2014-01-27 19:29:45 -05002277
2278 if sig is None:
Yury Selivanov7d2bfed2014-02-03 02:46:07 -05002279 # At this point we know, that `obj` is a class, with no user-
2280 # defined '__init__', '__new__', or class-level '__call__'
2281
Larry Hastings2623c8c2014-02-08 22:15:29 -08002282 for base in obj.__mro__[:-1]:
Yury Selivanov7d2bfed2014-02-03 02:46:07 -05002283 # Since '__text_signature__' is implemented as a
2284 # descriptor that extracts text signature from the
2285 # class docstring, if 'obj' is derived from a builtin
2286 # class, its own '__text_signature__' may be 'None'.
Larry Hastings2623c8c2014-02-08 22:15:29 -08002287 # Therefore, we go through the MRO (except the last
2288 # class in there, which is 'object') to find the first
Yury Selivanov7d2bfed2014-02-03 02:46:07 -05002289 # class with non-empty text signature.
2290 try:
2291 text_sig = base.__text_signature__
2292 except AttributeError:
2293 pass
2294 else:
2295 if text_sig:
2296 # If 'obj' class has a __text_signature__ attribute:
2297 # return a signature based on it
Yury Selivanovda396452014-03-27 12:09:24 -04002298 return _signature_fromstr(sigcls, obj, text_sig)
Yury Selivanov7d2bfed2014-02-03 02:46:07 -05002299
2300 # No '__text_signature__' was found for the 'obj' class.
2301 # Last option is to check if its '__init__' is
2302 # object.__init__ or type.__init__.
Larry Hastings2623c8c2014-02-08 22:15:29 -08002303 if type not in obj.__mro__:
Yury Selivanove7dcc5e2014-01-27 19:29:45 -05002304 # We have a class (not metaclass), but no user-defined
2305 # __init__ or __new__ for it
Yury Selivanovbf304fc2015-05-30 17:08:36 -04002306 if (obj.__init__ is object.__init__ and
2307 obj.__new__ is object.__new__):
Yury Selivanov7d2bfed2014-02-03 02:46:07 -05002308 # Return a signature of 'object' builtin.
2309 return signature(object)
Yury Selivanovbf304fc2015-05-30 17:08:36 -04002310 else:
2311 raise ValueError(
2312 'no signature found for builtin type {!r}'.format(obj))
Yury Selivanove7dcc5e2014-01-27 19:29:45 -05002313
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002314 elif not isinstance(obj, _NonUserDefinedCallables):
2315 # An object with __call__
2316 # We also check that the 'obj' is not an instance of
2317 # _WrapperDescriptor or _MethodWrapper to avoid
2318 # infinite recursion (and even potential segfault)
Yury Selivanov421f0c72014-01-29 12:05:40 -05002319 call = _signature_get_user_defined_method(type(obj), '__call__')
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002320 if call is not None:
Larry Hastings2623c8c2014-02-08 22:15:29 -08002321 try:
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002322 sig = _signature_from_callable(
Yury Selivanovda396452014-03-27 12:09:24 -04002323 call,
2324 follow_wrapper_chains=follow_wrapper_chains,
2325 skip_bound_arg=skip_bound_arg,
2326 sigcls=sigcls)
Larry Hastings2623c8c2014-02-08 22:15:29 -08002327 except ValueError as ex:
2328 msg = 'no signature found for {!r}'.format(obj)
2329 raise ValueError(msg) from ex
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002330
2331 if sig is not None:
2332 # For classes and objects we skip the first parameter of their
2333 # __call__, __new__, or __init__ methods
Yury Selivanov57d240e2014-02-19 16:27:23 -05002334 if skip_bound_arg:
2335 return _signature_bound_method(sig)
2336 else:
2337 return sig
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002338
2339 if isinstance(obj, types.BuiltinFunctionType):
2340 # Raise a nicer error message for builtins
2341 msg = 'no signature found for builtin function {!r}'.format(obj)
2342 raise ValueError(msg)
2343
2344 raise ValueError('callable {!r} is not supported by signature'.format(obj))
2345
2346
2347class _void:
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002348 """A private marker - used in Parameter & Signature."""
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002349
2350
2351class _empty:
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002352 """Marker object for Signature.empty and Parameter.empty."""
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002353
2354
Yury Selivanov21e83a52014-03-27 11:23:13 -04002355class _ParameterKind(enum.IntEnum):
2356 POSITIONAL_ONLY = 0
2357 POSITIONAL_OR_KEYWORD = 1
2358 VAR_POSITIONAL = 2
2359 KEYWORD_ONLY = 3
2360 VAR_KEYWORD = 4
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002361
2362 def __str__(self):
Yury Selivanov21e83a52014-03-27 11:23:13 -04002363 return self._name_
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002364
2365
Yury Selivanov21e83a52014-03-27 11:23:13 -04002366_POSITIONAL_ONLY = _ParameterKind.POSITIONAL_ONLY
2367_POSITIONAL_OR_KEYWORD = _ParameterKind.POSITIONAL_OR_KEYWORD
2368_VAR_POSITIONAL = _ParameterKind.VAR_POSITIONAL
2369_KEYWORD_ONLY = _ParameterKind.KEYWORD_ONLY
2370_VAR_KEYWORD = _ParameterKind.VAR_KEYWORD
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002371
2372
2373class Parameter:
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002374 """Represents a parameter in a function signature.
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002375
2376 Has the following public attributes:
2377
2378 * name : str
2379 The name of the parameter as a string.
2380 * default : object
2381 The default value for the parameter if specified. If the
Yury Selivanov8757ead2014-01-28 16:39:25 -05002382 parameter has no default value, this attribute is set to
2383 `Parameter.empty`.
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002384 * annotation
2385 The annotation for the parameter if specified. If the
Yury Selivanov8757ead2014-01-28 16:39:25 -05002386 parameter has no annotation, this attribute is set to
2387 `Parameter.empty`.
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002388 * kind : str
2389 Describes how argument values are bound to the parameter.
2390 Possible values: `Parameter.POSITIONAL_ONLY`,
2391 `Parameter.POSITIONAL_OR_KEYWORD`, `Parameter.VAR_POSITIONAL`,
2392 `Parameter.KEYWORD_ONLY`, `Parameter.VAR_KEYWORD`.
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002393 """
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002394
Yury Selivanov3f73ca22014-04-08 11:30:45 -04002395 __slots__ = ('_name', '_kind', '_default', '_annotation')
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002396
2397 POSITIONAL_ONLY = _POSITIONAL_ONLY
2398 POSITIONAL_OR_KEYWORD = _POSITIONAL_OR_KEYWORD
2399 VAR_POSITIONAL = _VAR_POSITIONAL
2400 KEYWORD_ONLY = _KEYWORD_ONLY
2401 VAR_KEYWORD = _VAR_KEYWORD
2402
2403 empty = _empty
2404
Yury Selivanov3f73ca22014-04-08 11:30:45 -04002405 def __init__(self, name, kind, *, default=_empty, annotation=_empty):
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002406
2407 if kind not in (_POSITIONAL_ONLY, _POSITIONAL_OR_KEYWORD,
2408 _VAR_POSITIONAL, _KEYWORD_ONLY, _VAR_KEYWORD):
2409 raise ValueError("invalid value for 'Parameter.kind' attribute")
2410 self._kind = kind
2411
2412 if default is not _empty:
2413 if kind in (_VAR_POSITIONAL, _VAR_KEYWORD):
2414 msg = '{} parameters cannot have default values'.format(kind)
2415 raise ValueError(msg)
2416 self._default = default
2417 self._annotation = annotation
2418
Yury Selivanov2393dca2014-01-27 15:07:58 -05002419 if name is _empty:
2420 raise ValueError('name is a required attribute for Parameter')
2421
2422 if not isinstance(name, str):
2423 raise TypeError("name must be a str, not a {!r}".format(name))
2424
Nick Coghlanb4b966e2016-06-04 14:40:03 -07002425 if name[0] == '.' and name[1:].isdigit():
2426 # These are implicit arguments generated by comprehensions. In
2427 # order to provide a friendlier interface to users, we recast
2428 # their name as "implicitN" and treat them as positional-only.
2429 # See issue 19611.
2430 if kind != _POSITIONAL_OR_KEYWORD:
2431 raise ValueError(
2432 'implicit arguments must be passed in as {}'.format(
2433 _POSITIONAL_OR_KEYWORD
2434 )
2435 )
2436 self._kind = _POSITIONAL_ONLY
2437 name = 'implicit{}'.format(name[1:])
2438
Yury Selivanov2393dca2014-01-27 15:07:58 -05002439 if not name.isidentifier():
2440 raise ValueError('{!r} is not a valid parameter name'.format(name))
2441
2442 self._name = name
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002443
Yury Selivanova5d63dd2014-03-27 11:31:43 -04002444 def __reduce__(self):
2445 return (type(self),
2446 (self._name, self._kind),
Yury Selivanov3f73ca22014-04-08 11:30:45 -04002447 {'_default': self._default,
Yury Selivanova5d63dd2014-03-27 11:31:43 -04002448 '_annotation': self._annotation})
2449
2450 def __setstate__(self, state):
Yury Selivanova5d63dd2014-03-27 11:31:43 -04002451 self._default = state['_default']
2452 self._annotation = state['_annotation']
2453
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002454 @property
2455 def name(self):
2456 return self._name
2457
2458 @property
2459 def default(self):
2460 return self._default
2461
2462 @property
2463 def annotation(self):
2464 return self._annotation
2465
2466 @property
2467 def kind(self):
2468 return self._kind
2469
Yury Selivanov3f73ca22014-04-08 11:30:45 -04002470 def replace(self, *, name=_void, kind=_void,
2471 annotation=_void, default=_void):
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002472 """Creates a customized copy of the Parameter."""
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002473
2474 if name is _void:
2475 name = self._name
2476
2477 if kind is _void:
2478 kind = self._kind
2479
2480 if annotation is _void:
2481 annotation = self._annotation
2482
2483 if default is _void:
2484 default = self._default
2485
Yury Selivanov3f73ca22014-04-08 11:30:45 -04002486 return type(self)(name, kind, default=default, annotation=annotation)
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002487
2488 def __str__(self):
2489 kind = self.kind
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002490 formatted = self._name
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002491
2492 # Add annotation and default value
2493 if self._annotation is not _empty:
2494 formatted = '{}:{}'.format(formatted,
2495 formatannotation(self._annotation))
2496
2497 if self._default is not _empty:
2498 formatted = '{}={}'.format(formatted, repr(self._default))
2499
2500 if kind == _VAR_POSITIONAL:
2501 formatted = '*' + formatted
2502 elif kind == _VAR_KEYWORD:
2503 formatted = '**' + formatted
2504
2505 return formatted
2506
2507 def __repr__(self):
Yury Selivanovf229bc52015-05-15 12:53:56 -04002508 return '<{} "{}">'.format(self.__class__.__name__, self)
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002509
Yury Selivanov67ae50e2014-04-08 11:46:50 -04002510 def __hash__(self):
Yury Selivanov08d4a4f2014-09-12 15:48:02 -04002511 return hash((self.name, self.kind, self.annotation, self.default))
Yury Selivanov67ae50e2014-04-08 11:46:50 -04002512
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002513 def __eq__(self, other):
Serhiy Storchaka2489bd52015-07-18 23:20:50 +03002514 if self is other:
2515 return True
Serhiy Storchaka3018cc42015-07-18 23:19:05 +03002516 if not isinstance(other, Parameter):
2517 return NotImplemented
2518 return (self._name == other._name and
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002519 self._kind == other._kind and
2520 self._default == other._default and
2521 self._annotation == other._annotation)
2522
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002523
2524class BoundArguments:
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002525 """Result of `Signature.bind` call. Holds the mapping of arguments
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002526 to the function's parameters.
2527
2528 Has the following public attributes:
2529
2530 * arguments : OrderedDict
2531 An ordered mutable mapping of parameters' names to arguments' values.
2532 Does not contain arguments' default values.
2533 * signature : Signature
2534 The Signature object that created this instance.
2535 * args : tuple
2536 Tuple of positional arguments values.
2537 * kwargs : dict
2538 Dict of keyword arguments values.
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002539 """
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002540
Yury Selivanov6abe0322015-05-13 17:18:41 -04002541 __slots__ = ('arguments', '_signature', '__weakref__')
2542
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002543 def __init__(self, signature, arguments):
2544 self.arguments = arguments
2545 self._signature = signature
2546
2547 @property
2548 def signature(self):
2549 return self._signature
2550
2551 @property
2552 def args(self):
2553 args = []
2554 for param_name, param in self._signature.parameters.items():
Yury Selivanov3f73ca22014-04-08 11:30:45 -04002555 if param.kind in (_VAR_KEYWORD, _KEYWORD_ONLY):
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002556 break
2557
2558 try:
2559 arg = self.arguments[param_name]
2560 except KeyError:
2561 # We're done here. Other arguments
2562 # will be mapped in 'BoundArguments.kwargs'
2563 break
2564 else:
2565 if param.kind == _VAR_POSITIONAL:
2566 # *args
2567 args.extend(arg)
2568 else:
2569 # plain argument
2570 args.append(arg)
2571
2572 return tuple(args)
2573
2574 @property
2575 def kwargs(self):
2576 kwargs = {}
2577 kwargs_started = False
2578 for param_name, param in self._signature.parameters.items():
2579 if not kwargs_started:
Yury Selivanov3f73ca22014-04-08 11:30:45 -04002580 if param.kind in (_VAR_KEYWORD, _KEYWORD_ONLY):
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002581 kwargs_started = True
2582 else:
2583 if param_name not in self.arguments:
2584 kwargs_started = True
2585 continue
2586
2587 if not kwargs_started:
2588 continue
2589
2590 try:
2591 arg = self.arguments[param_name]
2592 except KeyError:
2593 pass
2594 else:
2595 if param.kind == _VAR_KEYWORD:
2596 # **kwargs
2597 kwargs.update(arg)
2598 else:
2599 # plain keyword argument
2600 kwargs[param_name] = arg
2601
2602 return kwargs
2603
Yury Selivanovb907a512015-05-16 13:45:09 -04002604 def apply_defaults(self):
2605 """Set default values for missing arguments.
2606
2607 For variable-positional arguments (*args) the default is an
2608 empty tuple.
2609
2610 For variable-keyword arguments (**kwargs) the default is an
2611 empty dict.
2612 """
2613 arguments = self.arguments
Yury Selivanovb907a512015-05-16 13:45:09 -04002614 new_arguments = []
2615 for name, param in self._signature.parameters.items():
2616 try:
2617 new_arguments.append((name, arguments[name]))
2618 except KeyError:
2619 if param.default is not _empty:
2620 val = param.default
2621 elif param.kind is _VAR_POSITIONAL:
2622 val = ()
2623 elif param.kind is _VAR_KEYWORD:
2624 val = {}
2625 else:
2626 # This BoundArguments was likely produced by
2627 # Signature.bind_partial().
2628 continue
2629 new_arguments.append((name, val))
2630 self.arguments = OrderedDict(new_arguments)
2631
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002632 def __eq__(self, other):
Serhiy Storchaka2489bd52015-07-18 23:20:50 +03002633 if self is other:
2634 return True
Serhiy Storchaka3018cc42015-07-18 23:19:05 +03002635 if not isinstance(other, BoundArguments):
2636 return NotImplemented
2637 return (self.signature == other.signature and
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002638 self.arguments == other.arguments)
2639
Yury Selivanov6abe0322015-05-13 17:18:41 -04002640 def __setstate__(self, state):
2641 self._signature = state['_signature']
2642 self.arguments = state['arguments']
2643
2644 def __getstate__(self):
2645 return {'_signature': self._signature, 'arguments': self.arguments}
2646
Yury Selivanov3f6538f2015-05-14 18:47:17 -04002647 def __repr__(self):
2648 args = []
2649 for arg, value in self.arguments.items():
2650 args.append('{}={!r}'.format(arg, value))
Yury Selivanovf229bc52015-05-15 12:53:56 -04002651 return '<{} ({})>'.format(self.__class__.__name__, ', '.join(args))
Yury Selivanov3f6538f2015-05-14 18:47:17 -04002652
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002653
2654class Signature:
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002655 """A Signature object represents the overall signature of a function.
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002656 It stores a Parameter object for each parameter accepted by the
2657 function, as well as information specific to the function itself.
2658
2659 A Signature object has the following public attributes and methods:
2660
2661 * parameters : OrderedDict
2662 An ordered mapping of parameters' names to the corresponding
2663 Parameter objects (keyword-only arguments are in the same order
2664 as listed in `code.co_varnames`).
2665 * return_annotation : object
2666 The annotation for the return type of the function if specified.
2667 If the function has no annotation for its return type, this
Yury Selivanov8757ead2014-01-28 16:39:25 -05002668 attribute is set to `Signature.empty`.
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002669 * bind(*args, **kwargs) -> BoundArguments
2670 Creates a mapping from positional and keyword arguments to
2671 parameters.
2672 * bind_partial(*args, **kwargs) -> BoundArguments
2673 Creates a partial mapping from positional and keyword arguments
2674 to parameters (simulating 'functools.partial' behavior.)
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002675 """
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002676
2677 __slots__ = ('_return_annotation', '_parameters')
2678
2679 _parameter_cls = Parameter
2680 _bound_arguments_cls = BoundArguments
2681
2682 empty = _empty
2683
2684 def __init__(self, parameters=None, *, return_annotation=_empty,
2685 __validate_parameters__=True):
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002686 """Constructs Signature from the given list of Parameter
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002687 objects and 'return_annotation'. All arguments are optional.
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002688 """
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002689
2690 if parameters is None:
2691 params = OrderedDict()
2692 else:
2693 if __validate_parameters__:
2694 params = OrderedDict()
2695 top_kind = _POSITIONAL_ONLY
Yury Selivanov07a9e452014-01-29 10:58:16 -05002696 kind_defaults = False
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002697
2698 for idx, param in enumerate(parameters):
2699 kind = param.kind
Yury Selivanov2393dca2014-01-27 15:07:58 -05002700 name = param.name
2701
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002702 if kind < top_kind:
Yury Selivanov3f73ca22014-04-08 11:30:45 -04002703 msg = 'wrong parameter order: {!r} before {!r}'
Yury Selivanov2393dca2014-01-27 15:07:58 -05002704 msg = msg.format(top_kind, kind)
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002705 raise ValueError(msg)
Yury Selivanov07a9e452014-01-29 10:58:16 -05002706 elif kind > top_kind:
2707 kind_defaults = False
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002708 top_kind = kind
2709
Yury Selivanov3f73ca22014-04-08 11:30:45 -04002710 if kind in (_POSITIONAL_ONLY, _POSITIONAL_OR_KEYWORD):
Yury Selivanov07a9e452014-01-29 10:58:16 -05002711 if param.default is _empty:
2712 if kind_defaults:
2713 # No default for this parameter, but the
2714 # previous parameter of the same kind had
2715 # a default
2716 msg = 'non-default argument follows default ' \
2717 'argument'
2718 raise ValueError(msg)
2719 else:
2720 # There is a default for this parameter.
2721 kind_defaults = True
2722
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002723 if name in params:
2724 msg = 'duplicate parameter name: {!r}'.format(name)
2725 raise ValueError(msg)
Yury Selivanov2393dca2014-01-27 15:07:58 -05002726
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002727 params[name] = param
2728 else:
2729 params = OrderedDict(((param.name, param)
2730 for param in parameters))
2731
2732 self._parameters = types.MappingProxyType(params)
2733 self._return_annotation = return_annotation
2734
2735 @classmethod
2736 def from_function(cls, func):
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002737 """Constructs Signature for the given python function."""
Yury Selivanov57c74fc2015-05-20 23:07:02 -04002738
2739 warnings.warn("inspect.Signature.from_function() is deprecated, "
Berker Peksagb5601582015-05-21 23:40:54 +03002740 "use Signature.from_callable()",
2741 DeprecationWarning, stacklevel=2)
Yury Selivanovcf45f022015-05-20 14:38:50 -04002742 return _signature_from_function(cls, func)
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002743
Larry Hastings44e2eaa2013-11-23 15:37:55 -08002744 @classmethod
2745 def from_builtin(cls, func):
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002746 """Constructs Signature for the given builtin function."""
Yury Selivanov57c74fc2015-05-20 23:07:02 -04002747
2748 warnings.warn("inspect.Signature.from_builtin() is deprecated, "
Berker Peksagb5601582015-05-21 23:40:54 +03002749 "use Signature.from_callable()",
2750 DeprecationWarning, stacklevel=2)
Yury Selivanov57d240e2014-02-19 16:27:23 -05002751 return _signature_from_builtin(cls, func)
Larry Hastings44e2eaa2013-11-23 15:37:55 -08002752
Yury Selivanovda396452014-03-27 12:09:24 -04002753 @classmethod
Yury Selivanovbcd4fc12015-05-20 14:30:08 -04002754 def from_callable(cls, obj, *, follow_wrapped=True):
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002755 """Constructs Signature for the given callable object."""
Yury Selivanovbcd4fc12015-05-20 14:30:08 -04002756 return _signature_from_callable(obj, sigcls=cls,
2757 follow_wrapper_chains=follow_wrapped)
Yury Selivanovda396452014-03-27 12:09:24 -04002758
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002759 @property
2760 def parameters(self):
2761 return self._parameters
2762
2763 @property
2764 def return_annotation(self):
2765 return self._return_annotation
2766
2767 def replace(self, *, parameters=_void, return_annotation=_void):
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002768 """Creates a customized copy of the Signature.
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002769 Pass 'parameters' and/or 'return_annotation' arguments
2770 to override them in the new copy.
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002771 """
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002772
2773 if parameters is _void:
2774 parameters = self.parameters.values()
2775
2776 if return_annotation is _void:
2777 return_annotation = self._return_annotation
2778
2779 return type(self)(parameters,
2780 return_annotation=return_annotation)
2781
Yury Selivanov08d4a4f2014-09-12 15:48:02 -04002782 def _hash_basis(self):
2783 params = tuple(param for param in self.parameters.values()
2784 if param.kind != _KEYWORD_ONLY)
2785
2786 kwo_params = {param.name: param for param in self.parameters.values()
2787 if param.kind == _KEYWORD_ONLY}
2788
2789 return params, kwo_params, self.return_annotation
2790
Yury Selivanov67ae50e2014-04-08 11:46:50 -04002791 def __hash__(self):
Yury Selivanov08d4a4f2014-09-12 15:48:02 -04002792 params, kwo_params, return_annotation = self._hash_basis()
2793 kwo_params = frozenset(kwo_params.values())
2794 return hash((params, kwo_params, return_annotation))
Yury Selivanov67ae50e2014-04-08 11:46:50 -04002795
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002796 def __eq__(self, other):
Serhiy Storchaka2489bd52015-07-18 23:20:50 +03002797 if self is other:
2798 return True
Serhiy Storchaka3018cc42015-07-18 23:19:05 +03002799 if not isinstance(other, Signature):
2800 return NotImplemented
Serhiy Storchaka2489bd52015-07-18 23:20:50 +03002801 return self._hash_basis() == other._hash_basis()
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002802
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002803 def _bind(self, args, kwargs, *, partial=False):
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002804 """Private method. Don't use directly."""
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002805
2806 arguments = OrderedDict()
2807
2808 parameters = iter(self.parameters.values())
2809 parameters_ex = ()
2810 arg_vals = iter(args)
2811
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002812 while True:
2813 # Let's iterate through the positional arguments and corresponding
2814 # parameters
2815 try:
2816 arg_val = next(arg_vals)
2817 except StopIteration:
2818 # No more positional arguments
2819 try:
2820 param = next(parameters)
2821 except StopIteration:
2822 # No more parameters. That's it. Just need to check that
2823 # we have no `kwargs` after this while loop
2824 break
2825 else:
2826 if param.kind == _VAR_POSITIONAL:
2827 # That's OK, just empty *args. Let's start parsing
2828 # kwargs
2829 break
2830 elif param.name in kwargs:
2831 if param.kind == _POSITIONAL_ONLY:
2832 msg = '{arg!r} parameter is positional only, ' \
2833 'but was passed as a keyword'
2834 msg = msg.format(arg=param.name)
2835 raise TypeError(msg) from None
2836 parameters_ex = (param,)
2837 break
2838 elif (param.kind == _VAR_KEYWORD or
2839 param.default is not _empty):
2840 # That's fine too - we have a default value for this
2841 # parameter. So, lets start parsing `kwargs`, starting
2842 # with the current parameter
2843 parameters_ex = (param,)
2844 break
2845 else:
Yury Selivanov38b0d5a2014-01-28 17:27:39 -05002846 # No default, not VAR_KEYWORD, not VAR_POSITIONAL,
2847 # not in `kwargs`
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002848 if partial:
2849 parameters_ex = (param,)
2850 break
2851 else:
Yury Selivanov86872752015-05-19 00:27:49 -04002852 msg = 'missing a required argument: {arg!r}'
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002853 msg = msg.format(arg=param.name)
2854 raise TypeError(msg) from None
2855 else:
2856 # We have a positional argument to process
2857 try:
2858 param = next(parameters)
2859 except StopIteration:
2860 raise TypeError('too many positional arguments') from None
2861 else:
2862 if param.kind in (_VAR_KEYWORD, _KEYWORD_ONLY):
2863 # Looks like we have no parameter for this positional
2864 # argument
Yury Selivanov86872752015-05-19 00:27:49 -04002865 raise TypeError(
2866 'too many positional arguments') from None
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002867
2868 if param.kind == _VAR_POSITIONAL:
2869 # We have an '*args'-like argument, let's fill it with
2870 # all positional arguments we have left and move on to
2871 # the next phase
2872 values = [arg_val]
2873 values.extend(arg_vals)
2874 arguments[param.name] = tuple(values)
2875 break
2876
2877 if param.name in kwargs:
Yury Selivanov86872752015-05-19 00:27:49 -04002878 raise TypeError(
2879 'multiple values for argument {arg!r}'.format(
2880 arg=param.name)) from None
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002881
2882 arguments[param.name] = arg_val
2883
2884 # Now, we iterate through the remaining parameters to process
2885 # keyword arguments
2886 kwargs_param = None
2887 for param in itertools.chain(parameters_ex, parameters):
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002888 if param.kind == _VAR_KEYWORD:
2889 # Memorize that we have a '**kwargs'-like parameter
2890 kwargs_param = param
2891 continue
2892
Yury Selivanov38b0d5a2014-01-28 17:27:39 -05002893 if param.kind == _VAR_POSITIONAL:
2894 # Named arguments don't refer to '*args'-like parameters.
2895 # We only arrive here if the positional arguments ended
2896 # before reaching the last parameter before *args.
2897 continue
2898
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002899 param_name = param.name
2900 try:
2901 arg_val = kwargs.pop(param_name)
2902 except KeyError:
2903 # We have no value for this parameter. It's fine though,
2904 # if it has a default value, or it is an '*args'-like
2905 # parameter, left alone by the processing of positional
2906 # arguments.
2907 if (not partial and param.kind != _VAR_POSITIONAL and
2908 param.default is _empty):
Yury Selivanov86872752015-05-19 00:27:49 -04002909 raise TypeError('missing a required argument: {arg!r}'. \
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002910 format(arg=param_name)) from None
2911
2912 else:
Yury Selivanov9b9ac952014-01-28 20:54:28 -05002913 if param.kind == _POSITIONAL_ONLY:
2914 # This should never happen in case of a properly built
2915 # Signature object (but let's have this check here
2916 # to ensure correct behaviour just in case)
2917 raise TypeError('{arg!r} parameter is positional only, '
2918 'but was passed as a keyword'. \
2919 format(arg=param.name))
2920
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002921 arguments[param_name] = arg_val
2922
2923 if kwargs:
2924 if kwargs_param is not None:
2925 # Process our '**kwargs'-like parameter
2926 arguments[kwargs_param.name] = kwargs
2927 else:
Yury Selivanov86872752015-05-19 00:27:49 -04002928 raise TypeError(
2929 'got an unexpected keyword argument {arg!r}'.format(
2930 arg=next(iter(kwargs))))
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002931
2932 return self._bound_arguments_cls(self, arguments)
2933
Yury Selivanovc45873e2014-01-29 12:10:27 -05002934 def bind(*args, **kwargs):
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002935 """Get a BoundArguments object, that maps the passed `args`
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002936 and `kwargs` to the function's signature. Raises `TypeError`
2937 if the passed arguments can not be bound.
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002938 """
Yury Selivanovc45873e2014-01-29 12:10:27 -05002939 return args[0]._bind(args[1:], kwargs)
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002940
Yury Selivanovc45873e2014-01-29 12:10:27 -05002941 def bind_partial(*args, **kwargs):
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002942 """Get a BoundArguments object, that partially maps the
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002943 passed `args` and `kwargs` to the function's signature.
2944 Raises `TypeError` if the passed arguments can not be bound.
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002945 """
Yury Selivanovc45873e2014-01-29 12:10:27 -05002946 return args[0]._bind(args[1:], kwargs, partial=True)
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002947
Yury Selivanova5d63dd2014-03-27 11:31:43 -04002948 def __reduce__(self):
2949 return (type(self),
2950 (tuple(self._parameters.values()),),
2951 {'_return_annotation': self._return_annotation})
2952
2953 def __setstate__(self, state):
2954 self._return_annotation = state['_return_annotation']
2955
Yury Selivanov374375d2014-03-27 12:41:53 -04002956 def __repr__(self):
Yury Selivanovf229bc52015-05-15 12:53:56 -04002957 return '<{} {}>'.format(self.__class__.__name__, self)
Yury Selivanov374375d2014-03-27 12:41:53 -04002958
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002959 def __str__(self):
2960 result = []
Yury Selivanov2393dca2014-01-27 15:07:58 -05002961 render_pos_only_separator = False
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002962 render_kw_only_separator = True
Yury Selivanov2393dca2014-01-27 15:07:58 -05002963 for param in self.parameters.values():
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002964 formatted = str(param)
2965
2966 kind = param.kind
Yury Selivanov2393dca2014-01-27 15:07:58 -05002967
2968 if kind == _POSITIONAL_ONLY:
2969 render_pos_only_separator = True
2970 elif render_pos_only_separator:
2971 # It's not a positional-only parameter, and the flag
2972 # is set to 'True' (there were pos-only params before.)
2973 result.append('/')
2974 render_pos_only_separator = False
2975
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002976 if kind == _VAR_POSITIONAL:
2977 # OK, we have an '*args'-like parameter, so we won't need
2978 # a '*' to separate keyword-only arguments
2979 render_kw_only_separator = False
2980 elif kind == _KEYWORD_ONLY and render_kw_only_separator:
2981 # We have a keyword-only parameter to render and we haven't
2982 # rendered an '*args'-like parameter before, so add a '*'
2983 # separator to the parameters list ("foo(arg1, *, arg2)" case)
2984 result.append('*')
2985 # This condition should be only triggered once, so
2986 # reset the flag
2987 render_kw_only_separator = False
2988
2989 result.append(formatted)
2990
Yury Selivanov2393dca2014-01-27 15:07:58 -05002991 if render_pos_only_separator:
2992 # There were only positional-only parameters, hence the
2993 # flag was not reset to 'False'
2994 result.append('/')
2995
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002996 rendered = '({})'.format(', '.join(result))
2997
2998 if self.return_annotation is not _empty:
2999 anno = formatannotation(self.return_annotation)
3000 rendered += ' -> {}'.format(anno)
3001
3002 return rendered
Nick Coghlanf94a16b2013-09-22 22:46:49 +10003003
Yury Selivanovda396452014-03-27 12:09:24 -04003004
Yury Selivanovbcd4fc12015-05-20 14:30:08 -04003005def signature(obj, *, follow_wrapped=True):
Yury Selivanov5a23bd02014-03-29 13:47:11 -04003006 """Get a signature object for the passed callable."""
Yury Selivanovbcd4fc12015-05-20 14:30:08 -04003007 return Signature.from_callable(obj, follow_wrapped=follow_wrapped)
Yury Selivanovda396452014-03-27 12:09:24 -04003008
3009
Nick Coghlanf94a16b2013-09-22 22:46:49 +10003010def _main():
3011 """ Logic for inspecting an object given at command line """
3012 import argparse
3013 import importlib
3014
3015 parser = argparse.ArgumentParser()
3016 parser.add_argument(
3017 'object',
3018 help="The object to be analysed. "
3019 "It supports the 'module:qualname' syntax")
3020 parser.add_argument(
3021 '-d', '--details', action='store_true',
3022 help='Display info about the module rather than its source code')
3023
3024 args = parser.parse_args()
3025
3026 target = args.object
3027 mod_name, has_attrs, attrs = target.partition(":")
3028 try:
3029 obj = module = importlib.import_module(mod_name)
3030 except Exception as exc:
3031 msg = "Failed to import {} ({}: {})".format(mod_name,
3032 type(exc).__name__,
3033 exc)
3034 print(msg, file=sys.stderr)
3035 exit(2)
3036
3037 if has_attrs:
3038 parts = attrs.split(".")
3039 obj = module
3040 for part in parts:
3041 obj = getattr(obj, part)
3042
3043 if module.__name__ in sys.builtin_module_names:
3044 print("Can't get info for builtin modules.", file=sys.stderr)
3045 exit(1)
3046
3047 if args.details:
3048 print('Target: {}'.format(target))
3049 print('Origin: {}'.format(getsourcefile(module)))
3050 print('Cached: {}'.format(module.__cached__))
3051 if obj is module:
3052 print('Loader: {}'.format(repr(module.__loader__)))
3053 if hasattr(module, '__path__'):
3054 print('Submodule search path: {}'.format(module.__path__))
3055 else:
3056 try:
3057 __, lineno = findsource(obj)
3058 except Exception:
3059 pass
3060 else:
3061 print('Line: {}'.format(lineno))
3062
3063 print('\n')
3064 else:
3065 print(getsource(obj))
3066
3067
3068if __name__ == "__main__":
3069 _main()