blob: 60890f2eec07789eb6329fb4e55634ca4eca3791 [file] [log] [blame]
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001"""Get useful information from live Python objects.
2
3This module encapsulates the interface provided by the internal special
Neal Norwitz221085d2007-02-25 20:55:47 +00004attributes (co_*, im_*, tb_*, etc.) in a friendlier fashion.
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00005It also provides some help for examining source code and class layout.
6
7Here are some of the useful functions provided by this module:
8
Christian Heimes7131fd92008-02-19 14:21:46 +00009 ismodule(), isclass(), ismethod(), isfunction(), isgeneratorfunction(),
10 isgenerator(), istraceback(), isframe(), iscode(), isbuiltin(),
11 isroutine() - check object types
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +000012 getmembers() - get members of an object that satisfy a given condition
13
14 getfile(), getsourcefile(), getsource() - find an object's source code
15 getdoc(), getcomments() - get documentation on an object
16 getmodule() - determine the module that an object came from
17 getclasstree() - arrange classes so as to represent their hierarchy
18
Benjamin Peterson25cd7eb2010-03-30 18:42:32 +000019 getargspec(), getargvalues(), getcallargs() - get info about function arguments
Yury Selivanov0cf3ed62014-04-01 10:17:08 -040020 getfullargspec() - same, with support for Python 3 features
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +000021 formatargspec(), formatargvalues() - format an argument spec
22 getouterframes(), getinnerframes() - get info about frames
23 currentframe() - get the current stack frame
24 stack(), trace() - get info about frames on the stack or in a traceback
Larry Hastings7c7cbfc2012-06-22 15:19:35 -070025
26 signature() - get a Signature object for the callable
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +000027"""
28
29# This module is in the public domain. No warranties.
30
Larry Hastings7c7cbfc2012-06-22 15:19:35 -070031__author__ = ('Ka-Ping Yee <ping@lfw.org>',
32 'Yury Selivanov <yselivanov@sprymix.com>')
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +000033
Larry Hastings44e2eaa2013-11-23 15:37:55 -080034import ast
Antoine Pitroua8723a02015-04-15 00:41:29 +020035import dis
Yury Selivanov21e83a52014-03-27 11:23:13 -040036import enum
Brett Cannoncb66eb02012-05-11 12:58:42 -040037import importlib.machinery
38import itertools
Christian Heimes7131fd92008-02-19 14:21:46 +000039import linecache
Brett Cannoncb66eb02012-05-11 12:58:42 -040040import os
41import re
42import sys
43import tokenize
Larry Hastings2623c8c2014-02-08 22:15:29 -080044import token
Brett Cannoncb66eb02012-05-11 12:58:42 -040045import types
Brett Cannon2b88fcf2012-06-02 22:28:42 -040046import warnings
Larry Hastings7c7cbfc2012-06-22 15:19:35 -070047import functools
Nick Coghlan2f92e542012-06-23 19:39:55 +100048import builtins
Raymond Hettingera1a992c2005-03-11 06:46:45 +000049from operator import attrgetter
Larry Hastings7c7cbfc2012-06-22 15:19:35 -070050from collections import namedtuple, OrderedDict
Nick Coghlan09c81232010-08-17 10:18:16 +000051
52# Create constants for the compiler flags in Include/code.h
Antoine Pitroua8723a02015-04-15 00:41:29 +020053# We try to get them from dis to avoid duplication
54mod_dict = globals()
55for k, v in dis.COMPILER_FLAG_NAMES.items():
56 mod_dict["CO_" + v] = k
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +000057
Christian Heimesbe5b30b2008-03-03 19:18:51 +000058# See Include/object.h
59TPFLAGS_IS_ABSTRACT = 1 << 20
60
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +000061# ----------------------------------------------------------- type-checking
62def ismodule(object):
63 """Return true if the object is a module.
64
65 Module objects provide these attributes:
Barry Warsaw28a691b2010-04-17 00:19:56 +000066 __cached__ pathname to byte compiled file
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +000067 __doc__ documentation string
68 __file__ filename (missing for built-in modules)"""
Tim Peters28bc59f2001-09-16 08:40:16 +000069 return isinstance(object, types.ModuleType)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +000070
71def isclass(object):
72 """Return true if the object is a class.
73
74 Class objects provide these attributes:
75 __doc__ documentation string
76 __module__ name of module in which this class was defined"""
Benjamin Petersonc4656002009-01-17 22:41:18 +000077 return isinstance(object, type)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +000078
79def ismethod(object):
80 """Return true if the object is an instance method.
81
82 Instance method objects provide these attributes:
83 __doc__ documentation string
84 __name__ name with which this method was defined
Christian Heimesff737952007-11-27 10:40:20 +000085 __func__ function object containing implementation of method
86 __self__ instance to which this method is bound"""
Tim Peters28bc59f2001-09-16 08:40:16 +000087 return isinstance(object, types.MethodType)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +000088
Tim Peters536d2262001-09-20 05:13:38 +000089def ismethoddescriptor(object):
Tim Petersf1d90b92001-09-20 05:47:55 +000090 """Return true if the object is a method descriptor.
91
92 But not if ismethod() or isclass() or isfunction() are true.
Tim Peters536d2262001-09-20 05:13:38 +000093
94 This is new in Python 2.2, and, for example, is true of int.__add__.
95 An object passing this test has a __get__ attribute but not a __set__
96 attribute, but beyond that the set of attributes varies. __name__ is
97 usually sensible, and __doc__ often is.
98
Tim Petersf1d90b92001-09-20 05:47:55 +000099 Methods implemented via descriptors that also pass one of the other
100 tests return false from the ismethoddescriptor() test, simply because
101 the other tests promise more -- you can, e.g., count on having the
Christian Heimesff737952007-11-27 10:40:20 +0000102 __func__ attribute (etc) when an object passes ismethod()."""
Antoine Pitrou86a8a9a2011-12-21 09:57:40 +0100103 if isclass(object) or ismethod(object) or isfunction(object):
104 # mutual exclusion
105 return False
106 tp = type(object)
107 return hasattr(tp, "__get__") and not hasattr(tp, "__set__")
Tim Peters536d2262001-09-20 05:13:38 +0000108
Martin v. Löwise59e2ba2003-05-03 09:09:02 +0000109def isdatadescriptor(object):
110 """Return true if the object is a data descriptor.
111
112 Data descriptors have both a __get__ and a __set__ attribute. Examples are
113 properties (defined in Python) and getsets and members (defined in C).
114 Typically, data descriptors will also have __name__ and __doc__ attributes
115 (properties, getsets, and members have both of these attributes), but this
116 is not guaranteed."""
Antoine Pitrou86a8a9a2011-12-21 09:57:40 +0100117 if isclass(object) or ismethod(object) or isfunction(object):
118 # mutual exclusion
119 return False
120 tp = type(object)
121 return hasattr(tp, "__set__") and hasattr(tp, "__get__")
Martin v. Löwise59e2ba2003-05-03 09:09:02 +0000122
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000123if hasattr(types, 'MemberDescriptorType'):
124 # CPython and equivalent
125 def ismemberdescriptor(object):
126 """Return true if the object is a member descriptor.
127
128 Member descriptors are specialized descriptors defined in extension
129 modules."""
130 return isinstance(object, types.MemberDescriptorType)
131else:
132 # Other implementations
133 def ismemberdescriptor(object):
134 """Return true if the object is a member descriptor.
135
136 Member descriptors are specialized descriptors defined in extension
137 modules."""
138 return False
139
140if hasattr(types, 'GetSetDescriptorType'):
141 # CPython and equivalent
142 def isgetsetdescriptor(object):
143 """Return true if the object is a getset descriptor.
144
145 getset descriptors are specialized descriptors defined in extension
146 modules."""
147 return isinstance(object, types.GetSetDescriptorType)
148else:
149 # Other implementations
150 def isgetsetdescriptor(object):
151 """Return true if the object is a getset descriptor.
152
153 getset descriptors are specialized descriptors defined in extension
154 modules."""
155 return False
156
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000157def isfunction(object):
158 """Return true if the object is a user-defined function.
159
160 Function objects provide these attributes:
161 __doc__ documentation string
162 __name__ name with which this function was defined
Neal Norwitz221085d2007-02-25 20:55:47 +0000163 __code__ code object containing compiled function bytecode
164 __defaults__ tuple of any default values for arguments
165 __globals__ global namespace in which this function was defined
166 __annotations__ dict of parameter annotations
167 __kwdefaults__ dict of keyword only parameters with defaults"""
Tim Peters28bc59f2001-09-16 08:40:16 +0000168 return isinstance(object, types.FunctionType)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000169
Christian Heimes7131fd92008-02-19 14:21:46 +0000170def isgeneratorfunction(object):
171 """Return true if the object is a user-defined generator function.
172
173 Generator function objects provides same attributes as functions.
174
Alexander Belopolsky977a6842010-08-16 20:17:07 +0000175 See help(isfunction) for attributes listing."""
Georg Brandlb1441c72009-01-03 22:33:39 +0000176 return bool((isfunction(object) or ismethod(object)) and
177 object.__code__.co_flags & CO_GENERATOR)
Christian Heimes7131fd92008-02-19 14:21:46 +0000178
179def isgenerator(object):
180 """Return true if the object is a generator.
181
182 Generator objects provide these attributes:
Ezio Melotti30b9d5d2013-08-17 15:50:46 +0300183 __iter__ defined to support iteration over container
Christian Heimes7131fd92008-02-19 14:21:46 +0000184 close raises a new GeneratorExit exception inside the
185 generator to terminate the iteration
186 gi_code code object
187 gi_frame frame object or possibly None once the generator has
188 been exhausted
189 gi_running set to 1 when generator is executing, 0 otherwise
190 next return the next item from the container
191 send resumes the generator and "sends" a value that becomes
192 the result of the current yield-expression
193 throw used to raise an exception inside the generator"""
194 return isinstance(object, types.GeneratorType)
195
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000196def istraceback(object):
197 """Return true if the object is a traceback.
198
199 Traceback objects provide these attributes:
200 tb_frame frame object at this level
201 tb_lasti index of last attempted instruction in bytecode
202 tb_lineno current line number in Python source code
203 tb_next next inner traceback object (called by this level)"""
Tim Peters28bc59f2001-09-16 08:40:16 +0000204 return isinstance(object, types.TracebackType)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000205
206def isframe(object):
207 """Return true if the object is a frame object.
208
209 Frame objects provide these attributes:
210 f_back next outer frame object (this frame's caller)
211 f_builtins built-in namespace seen by this frame
212 f_code code object being executed in this frame
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000213 f_globals global namespace seen by this frame
214 f_lasti index of last attempted instruction in bytecode
215 f_lineno current line number in Python source code
216 f_locals local namespace seen by this frame
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000217 f_trace tracing function for this frame, or None"""
Tim Peters28bc59f2001-09-16 08:40:16 +0000218 return isinstance(object, types.FrameType)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000219
220def iscode(object):
221 """Return true if the object is a code object.
222
223 Code objects provide these attributes:
224 co_argcount number of arguments (not including * or ** args)
225 co_code string of raw compiled bytecode
226 co_consts tuple of constants used in the bytecode
227 co_filename name of file in which this code object was created
228 co_firstlineno number of first line in Python source code
229 co_flags bitmap: 1=optimized | 2=newlocals | 4=*arg | 8=**arg
230 co_lnotab encoded mapping of line numbers to bytecode indices
231 co_name name with which this code object was defined
232 co_names tuple of names of local variables
233 co_nlocals number of local variables
234 co_stacksize virtual machine stack space required
235 co_varnames tuple of names of arguments and local variables"""
Tim Peters28bc59f2001-09-16 08:40:16 +0000236 return isinstance(object, types.CodeType)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000237
238def isbuiltin(object):
239 """Return true if the object is a built-in function or method.
240
241 Built-in functions and methods provide these attributes:
242 __doc__ documentation string
243 __name__ original name of this function or method
244 __self__ instance to which a method is bound, or None"""
Tim Peters28bc59f2001-09-16 08:40:16 +0000245 return isinstance(object, types.BuiltinFunctionType)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000246
247def isroutine(object):
248 """Return true if the object is any kind of function or method."""
Tim Peters536d2262001-09-20 05:13:38 +0000249 return (isbuiltin(object)
250 or isfunction(object)
251 or ismethod(object)
252 or ismethoddescriptor(object))
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000253
Christian Heimesbe5b30b2008-03-03 19:18:51 +0000254def isabstract(object):
255 """Return true if the object is an abstract base class (ABC)."""
Benjamin Petersona0dfa822009-11-13 02:25:08 +0000256 return bool(isinstance(object, type) and object.__flags__ & TPFLAGS_IS_ABSTRACT)
Christian Heimesbe5b30b2008-03-03 19:18:51 +0000257
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000258def getmembers(object, predicate=None):
259 """Return all members of an object as (name, value) pairs sorted by name.
260 Optionally, only return members that satisfy a given predicate."""
Antoine Pitrou86a8a9a2011-12-21 09:57:40 +0100261 if isclass(object):
262 mro = (object,) + getmro(object)
263 else:
264 mro = ()
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000265 results = []
Ethan Furmane03ea372013-09-25 07:14:41 -0700266 processed = set()
267 names = dir(object)
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700268 # :dd any DynamicClassAttributes to the list of names if object is a class;
Ethan Furmane03ea372013-09-25 07:14:41 -0700269 # this may result in duplicate entries if, for example, a virtual
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700270 # attribute with the same name as a DynamicClassAttribute exists
Ethan Furmane03ea372013-09-25 07:14:41 -0700271 try:
272 for base in object.__bases__:
273 for k, v in base.__dict__.items():
274 if isinstance(v, types.DynamicClassAttribute):
275 names.append(k)
276 except AttributeError:
277 pass
278 for key in names:
Ethan Furman63c141c2013-10-18 00:27:39 -0700279 # First try to get the value via getattr. Some descriptors don't
280 # like calling their __get__ (see bug #1785), so fall back to
281 # looking in the __dict__.
282 try:
283 value = getattr(object, key)
284 # handle the duplicate key
285 if key in processed:
286 raise AttributeError
287 except AttributeError:
288 for base in mro:
289 if key in base.__dict__:
290 value = base.__dict__[key]
291 break
292 else:
293 # could be a (currently) missing slot member, or a buggy
294 # __dir__; discard and move on
Antoine Pitrou86a8a9a2011-12-21 09:57:40 +0100295 continue
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000296 if not predicate or predicate(value):
297 results.append((key, value))
Ethan Furmane03ea372013-09-25 07:14:41 -0700298 processed.add(key)
299 results.sort(key=lambda pair: pair[0])
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000300 return results
301
Christian Heimes25bb7832008-01-11 16:17:00 +0000302Attribute = namedtuple('Attribute', 'name kind defining_class object')
303
Tim Peters13b49d32001-09-23 02:00:29 +0000304def classify_class_attrs(cls):
305 """Return list of attribute-descriptor tuples.
306
307 For each name in dir(cls), the return list contains a 4-tuple
308 with these elements:
309
310 0. The name (a string).
311
312 1. The kind of attribute this is, one of these strings:
313 'class method' created via classmethod()
314 'static method' created via staticmethod()
315 'property' created via property()
Ethan Furmane03ea372013-09-25 07:14:41 -0700316 'method' any other flavor of method or descriptor
Tim Peters13b49d32001-09-23 02:00:29 +0000317 'data' not a method
318
319 2. The class which defined this attribute (a class).
320
Ethan Furmane03ea372013-09-25 07:14:41 -0700321 3. The object as obtained by calling getattr; if this fails, or if the
322 resulting object does not live anywhere in the class' mro (including
323 metaclasses) then the object is looked up in the defining class's
324 dict (found by walking the mro).
Ethan Furman668dede2013-09-14 18:53:26 -0700325
326 If one of the items in dir(cls) is stored in the metaclass it will now
327 be discovered and not have None be listed as the class in which it was
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700328 defined. Any items whose home class cannot be discovered are skipped.
Tim Peters13b49d32001-09-23 02:00:29 +0000329 """
330
331 mro = getmro(cls)
Ethan Furman668dede2013-09-14 18:53:26 -0700332 metamro = getmro(type(cls)) # for attributes stored in the metaclass
Ethan Furmane03ea372013-09-25 07:14:41 -0700333 metamro = tuple([cls for cls in metamro if cls not in (type, object)])
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700334 class_bases = (cls,) + mro
335 all_bases = class_bases + metamro
Tim Peters13b49d32001-09-23 02:00:29 +0000336 names = dir(cls)
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700337 # :dd any DynamicClassAttributes to the list of names;
Ethan Furmane03ea372013-09-25 07:14:41 -0700338 # this may result in duplicate entries if, for example, a virtual
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700339 # attribute with the same name as a DynamicClassAttribute exists.
Ethan Furman63c141c2013-10-18 00:27:39 -0700340 for base in mro:
Ethan Furmane03ea372013-09-25 07:14:41 -0700341 for k, v in base.__dict__.items():
342 if isinstance(v, types.DynamicClassAttribute):
343 names.append(k)
Tim Peters13b49d32001-09-23 02:00:29 +0000344 result = []
Ethan Furmane03ea372013-09-25 07:14:41 -0700345 processed = set()
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700346
Tim Peters13b49d32001-09-23 02:00:29 +0000347 for name in names:
Antoine Pitrou86a8a9a2011-12-21 09:57:40 +0100348 # Get the object associated with the name, and where it was defined.
Ethan Furmane03ea372013-09-25 07:14:41 -0700349 # Normal objects will be looked up with both getattr and directly in
350 # its class' dict (in case getattr fails [bug #1785], and also to look
351 # for a docstring).
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700352 # For DynamicClassAttributes on the second pass we only look in the
Ethan Furmane03ea372013-09-25 07:14:41 -0700353 # class's dict.
354 #
Tim Peters13b49d32001-09-23 02:00:29 +0000355 # Getting an obj from the __dict__ sometimes reveals more than
356 # using getattr. Static and class methods are dramatic examples.
Antoine Pitrou86a8a9a2011-12-21 09:57:40 +0100357 homecls = None
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700358 get_obj = None
359 dict_obj = None
Ethan Furmane03ea372013-09-25 07:14:41 -0700360 if name not in processed:
361 try:
Ethan Furmana8b07072013-10-18 01:22:08 -0700362 if name == '__dict__':
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700363 raise Exception("__dict__ is special, don't want the proxy")
Ethan Furmane03ea372013-09-25 07:14:41 -0700364 get_obj = getattr(cls, name)
365 except Exception as exc:
366 pass
367 else:
Ethan Furmane03ea372013-09-25 07:14:41 -0700368 homecls = getattr(get_obj, "__objclass__", homecls)
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700369 if homecls not in class_bases:
Ethan Furmane03ea372013-09-25 07:14:41 -0700370 # if the resulting object does not live somewhere in the
Ethan Furman63c141c2013-10-18 00:27:39 -0700371 # mro, drop it and search the mro manually
Ethan Furmane03ea372013-09-25 07:14:41 -0700372 homecls = None
Ethan Furman63c141c2013-10-18 00:27:39 -0700373 last_cls = None
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700374 # first look in the classes
375 for srch_cls in class_bases:
Ethan Furman63c141c2013-10-18 00:27:39 -0700376 srch_obj = getattr(srch_cls, name, None)
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700377 if srch_obj == get_obj:
Ethan Furman63c141c2013-10-18 00:27:39 -0700378 last_cls = srch_cls
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700379 # then check the metaclasses
380 for srch_cls in metamro:
381 try:
382 srch_obj = srch_cls.__getattr__(cls, name)
383 except AttributeError:
384 continue
385 if srch_obj == get_obj:
386 last_cls = srch_cls
Ethan Furman63c141c2013-10-18 00:27:39 -0700387 if last_cls is not None:
388 homecls = last_cls
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700389 for base in all_bases:
Ethan Furmane03ea372013-09-25 07:14:41 -0700390 if name in base.__dict__:
391 dict_obj = base.__dict__[name]
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700392 if homecls not in metamro:
393 homecls = base
Ethan Furmane03ea372013-09-25 07:14:41 -0700394 break
Ethan Furman63c141c2013-10-18 00:27:39 -0700395 if homecls is None:
396 # unable to locate the attribute anywhere, most likely due to
397 # buggy custom __dir__; discard and move on
398 continue
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700399 obj = get_obj or dict_obj
Ethan Furmane03ea372013-09-25 07:14:41 -0700400 # Classify the object or its descriptor.
Ethan Furman63c141c2013-10-18 00:27:39 -0700401 if isinstance(dict_obj, staticmethod):
Tim Peters13b49d32001-09-23 02:00:29 +0000402 kind = "static method"
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700403 obj = dict_obj
Ethan Furman63c141c2013-10-18 00:27:39 -0700404 elif isinstance(dict_obj, classmethod):
Tim Peters13b49d32001-09-23 02:00:29 +0000405 kind = "class method"
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700406 obj = dict_obj
407 elif isinstance(dict_obj, property):
Tim Peters13b49d32001-09-23 02:00:29 +0000408 kind = "property"
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700409 obj = dict_obj
Yury Selivanov0860a0b2014-01-31 14:28:44 -0500410 elif isroutine(obj):
Tim Peters13b49d32001-09-23 02:00:29 +0000411 kind = "method"
Antoine Pitrou86a8a9a2011-12-21 09:57:40 +0100412 else:
Ethan Furmane03ea372013-09-25 07:14:41 -0700413 kind = "data"
Christian Heimes25bb7832008-01-11 16:17:00 +0000414 result.append(Attribute(name, kind, homecls, obj))
Ethan Furmane03ea372013-09-25 07:14:41 -0700415 processed.add(name)
Tim Peters13b49d32001-09-23 02:00:29 +0000416 return result
417
Tim Peterse0b2d7a2001-09-22 06:10:55 +0000418# ----------------------------------------------------------- class helpers
Tim Peterse0b2d7a2001-09-22 06:10:55 +0000419
420def getmro(cls):
421 "Return tuple of base classes (including cls) in method resolution order."
Benjamin Petersonb82c8e52010-11-04 00:38:49 +0000422 return cls.__mro__
Tim Peterse0b2d7a2001-09-22 06:10:55 +0000423
Nick Coghlane8c45d62013-07-28 20:00:01 +1000424# -------------------------------------------------------- function helpers
425
426def unwrap(func, *, stop=None):
427 """Get the object wrapped by *func*.
428
429 Follows the chain of :attr:`__wrapped__` attributes returning the last
430 object in the chain.
431
432 *stop* is an optional callback accepting an object in the wrapper chain
433 as its sole argument that allows the unwrapping to be terminated early if
434 the callback returns a true value. If the callback never returns a true
435 value, the last object in the chain is returned as usual. For example,
436 :func:`signature` uses this to stop unwrapping if any object in the
437 chain has a ``__signature__`` attribute defined.
438
439 :exc:`ValueError` is raised if a cycle is encountered.
440
441 """
442 if stop is None:
443 def _is_wrapper(f):
444 return hasattr(f, '__wrapped__')
445 else:
446 def _is_wrapper(f):
447 return hasattr(f, '__wrapped__') and not stop(f)
448 f = func # remember the original func for error reporting
449 memo = {id(f)} # Memoise by id to tolerate non-hashable objects
450 while _is_wrapper(func):
451 func = func.__wrapped__
452 id_func = id(func)
453 if id_func in memo:
454 raise ValueError('wrapper loop when unwrapping {!r}'.format(f))
455 memo.add(id_func)
456 return func
457
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000458# -------------------------------------------------- source code extraction
459def indentsize(line):
460 """Return the indent size, in spaces, at the start of a line of text."""
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000461 expline = line.expandtabs()
462 return len(expline) - len(expline.lstrip())
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000463
Serhiy Storchaka5cf2b722015-04-03 22:38:53 +0300464def _findclass(func):
465 cls = sys.modules.get(func.__module__)
466 if cls is None:
467 return None
468 for name in func.__qualname__.split('.')[:-1]:
469 cls = getattr(cls, name)
470 if not isclass(cls):
471 return None
472 return cls
473
474def _finddoc(obj):
475 if isclass(obj):
476 for base in obj.__mro__:
477 if base is not object:
478 try:
479 doc = base.__doc__
480 except AttributeError:
481 continue
482 if doc is not None:
483 return doc
484 return None
485
486 if ismethod(obj):
487 name = obj.__func__.__name__
488 self = obj.__self__
489 if (isclass(self) and
490 getattr(getattr(self, name, None), '__func__') is obj.__func__):
491 # classmethod
492 cls = self
493 else:
494 cls = self.__class__
495 elif isfunction(obj):
496 name = obj.__name__
497 cls = _findclass(obj)
498 if cls is None or getattr(cls, name) is not obj:
499 return None
500 elif isbuiltin(obj):
501 name = obj.__name__
502 self = obj.__self__
503 if (isclass(self) and
504 self.__qualname__ + '.' + name == obj.__qualname__):
505 # classmethod
506 cls = self
507 else:
508 cls = self.__class__
509 elif ismethoddescriptor(obj) or isdatadescriptor(obj):
510 name = obj.__name__
511 cls = obj.__objclass__
512 if getattr(cls, name) is not obj:
513 return None
514 elif isinstance(obj, property):
515 func = f.fget
516 name = func.__name__
517 cls = _findclass(func)
518 if cls is None or getattr(cls, name) is not obj:
519 return None
520 else:
521 return None
522
523 for base in cls.__mro__:
524 try:
525 doc = getattr(base, name).__doc__
526 except AttributeError:
527 continue
528 if doc is not None:
529 return doc
530 return None
531
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000532def getdoc(object):
533 """Get the documentation string for an object.
534
535 All tabs are expanded to spaces. To clean up docstrings that are
536 indented to line up with blocks of code, any whitespace than can be
537 uniformly removed from the second line onwards is removed."""
Tim Peters24008312002-03-17 18:56:20 +0000538 try:
539 doc = object.__doc__
540 except AttributeError:
541 return None
Serhiy Storchaka5cf2b722015-04-03 22:38:53 +0300542 if doc is None:
543 try:
544 doc = _finddoc(object)
545 except (AttributeError, TypeError):
546 return None
Guido van Rossum3172c5d2007-10-16 18:12:55 +0000547 if not isinstance(doc, str):
Tim Peters24008312002-03-17 18:56:20 +0000548 return None
Georg Brandl0c77a822008-06-10 16:37:50 +0000549 return cleandoc(doc)
550
551def cleandoc(doc):
552 """Clean up indentation from docstrings.
553
554 Any whitespace that can be uniformly removed from the second line
555 onwards is removed."""
Tim Peters24008312002-03-17 18:56:20 +0000556 try:
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000557 lines = doc.expandtabs().split('\n')
Tim Peters24008312002-03-17 18:56:20 +0000558 except UnicodeError:
559 return None
560 else:
Ka-Ping Yeea59ef7b2002-11-30 03:53:15 +0000561 # Find minimum indentation of any non-blank lines after first line.
Christian Heimesa37d4c62007-12-04 23:02:19 +0000562 margin = sys.maxsize
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000563 for line in lines[1:]:
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000564 content = len(line.lstrip())
Ka-Ping Yeea59ef7b2002-11-30 03:53:15 +0000565 if content:
566 indent = len(line) - content
567 margin = min(margin, indent)
568 # Remove indentation.
569 if lines:
570 lines[0] = lines[0].lstrip()
Christian Heimesa37d4c62007-12-04 23:02:19 +0000571 if margin < sys.maxsize:
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000572 for i in range(1, len(lines)): lines[i] = lines[i][margin:]
Ka-Ping Yeea59ef7b2002-11-30 03:53:15 +0000573 # Remove any trailing or leading blank lines.
574 while lines and not lines[-1]:
575 lines.pop()
576 while lines and not lines[0]:
577 lines.pop(0)
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000578 return '\n'.join(lines)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000579
580def getfile(object):
Ka-Ping Yeec113c242001-03-02 02:08:53 +0000581 """Work out which source or compiled file an object was defined in."""
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000582 if ismodule(object):
583 if hasattr(object, '__file__'):
584 return object.__file__
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +0000585 raise TypeError('{!r} is a built-in module'.format(object))
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000586 if isclass(object):
Yury Selivanov2eed8b72014-01-27 13:24:56 -0500587 if hasattr(object, '__module__'):
588 object = sys.modules.get(object.__module__)
589 if hasattr(object, '__file__'):
590 return object.__file__
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +0000591 raise TypeError('{!r} is a built-in class'.format(object))
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000592 if ismethod(object):
Christian Heimesff737952007-11-27 10:40:20 +0000593 object = object.__func__
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000594 if isfunction(object):
Neal Norwitz221085d2007-02-25 20:55:47 +0000595 object = object.__code__
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000596 if istraceback(object):
597 object = object.tb_frame
598 if isframe(object):
599 object = object.f_code
600 if iscode(object):
601 return object.co_filename
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +0000602 raise TypeError('{!r} is not a module, class, method, '
603 'function, traceback, frame, or code object'.format(object))
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000604
Christian Heimes25bb7832008-01-11 16:17:00 +0000605ModuleInfo = namedtuple('ModuleInfo', 'name suffix mode module_type')
606
Ka-Ping Yee4d6fc7f2001-04-10 11:43:00 +0000607def getmoduleinfo(path):
608 """Get the module name, suffix, mode, and module type for a given file."""
Brett Cannoncb66eb02012-05-11 12:58:42 -0400609 warnings.warn('inspect.getmoduleinfo() is deprecated', DeprecationWarning,
610 2)
Brett Cannone4f41de2013-06-16 13:13:40 -0400611 with warnings.catch_warnings():
612 warnings.simplefilter('ignore', PendingDeprecationWarning)
613 import imp
Ka-Ping Yee4d6fc7f2001-04-10 11:43:00 +0000614 filename = os.path.basename(path)
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000615 suffixes = [(-len(suffix), suffix, mode, mtype)
616 for suffix, mode, mtype in imp.get_suffixes()]
Ka-Ping Yee4d6fc7f2001-04-10 11:43:00 +0000617 suffixes.sort() # try longest suffixes first, in case they overlap
618 for neglen, suffix, mode, mtype in suffixes:
619 if filename[neglen:] == suffix:
Christian Heimes25bb7832008-01-11 16:17:00 +0000620 return ModuleInfo(filename[:neglen], suffix, mode, mtype)
Ka-Ping Yee4d6fc7f2001-04-10 11:43:00 +0000621
622def getmodulename(path):
623 """Return the module name for a given file, or None."""
Nick Coghlan76e07702012-07-18 23:14:57 +1000624 fname = os.path.basename(path)
625 # Check for paths that look like an actual module file
626 suffixes = [(-len(suffix), suffix)
627 for suffix in importlib.machinery.all_suffixes()]
628 suffixes.sort() # try longest suffixes first, in case they overlap
629 for neglen, suffix in suffixes:
630 if fname.endswith(suffix):
631 return fname[:neglen]
632 return None
Ka-Ping Yee4d6fc7f2001-04-10 11:43:00 +0000633
Ka-Ping Yeec113c242001-03-02 02:08:53 +0000634def getsourcefile(object):
R. David Murraya1b37402010-06-17 02:04:29 +0000635 """Return the filename that can be used to locate an object's source.
636 Return None if no way can be identified to get the source.
637 """
Ka-Ping Yeec113c242001-03-02 02:08:53 +0000638 filename = getfile(object)
Brett Cannoncb66eb02012-05-11 12:58:42 -0400639 all_bytecode_suffixes = importlib.machinery.DEBUG_BYTECODE_SUFFIXES[:]
640 all_bytecode_suffixes += importlib.machinery.OPTIMIZED_BYTECODE_SUFFIXES[:]
641 if any(filename.endswith(s) for s in all_bytecode_suffixes):
642 filename = (os.path.splitext(filename)[0] +
643 importlib.machinery.SOURCE_SUFFIXES[0])
644 elif any(filename.endswith(s) for s in
645 importlib.machinery.EXTENSION_SUFFIXES):
646 return None
Thomas Wouters477c8d52006-05-27 19:21:47 +0000647 if os.path.exists(filename):
648 return filename
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000649 # only return a non-existent filename if the module has a PEP 302 loader
Brett Cannon4c14b5d2013-05-04 13:56:58 -0400650 if getattr(getmodule(object, filename), '__loader__', None) is not None:
Ka-Ping Yeec113c242001-03-02 02:08:53 +0000651 return filename
R. David Murraya1b37402010-06-17 02:04:29 +0000652 # or it is in the linecache
653 if filename in linecache.cache:
654 return filename
Ka-Ping Yeec113c242001-03-02 02:08:53 +0000655
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000656def getabsfile(object, _filename=None):
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000657 """Return an absolute path to the source or compiled file for an object.
Ka-Ping Yeec113c242001-03-02 02:08:53 +0000658
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000659 The idea is for each object to have a unique origin, so this routine
660 normalizes the result as much as possible."""
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000661 if _filename is None:
662 _filename = getsourcefile(object) or getfile(object)
663 return os.path.normcase(os.path.abspath(_filename))
Ka-Ping Yeec113c242001-03-02 02:08:53 +0000664
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000665modulesbyfile = {}
Thomas Wouters89f507f2006-12-13 04:49:30 +0000666_filesbymodname = {}
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000667
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000668def getmodule(object, _filename=None):
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000669 """Return the module an object was defined in, or None if not found."""
Ka-Ping Yee202c99b2001-04-13 09:15:08 +0000670 if ismodule(object):
671 return object
Johannes Gijsbers93245262004-09-11 15:53:22 +0000672 if hasattr(object, '__module__'):
Ka-Ping Yee8b58b842001-03-01 13:56:16 +0000673 return sys.modules.get(object.__module__)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000674 # Try the filename to modulename cache
675 if _filename is not None and _filename in modulesbyfile:
676 return sys.modules.get(modulesbyfile[_filename])
677 # Try the cache again with the absolute file name
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000678 try:
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000679 file = getabsfile(object, _filename)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000680 except TypeError:
681 return None
Raymond Hettinger54f02222002-06-01 14:18:47 +0000682 if file in modulesbyfile:
Ka-Ping Yeeb38bbbd2003-03-28 16:29:50 +0000683 return sys.modules.get(modulesbyfile[file])
Thomas Wouters89f507f2006-12-13 04:49:30 +0000684 # Update the filename to module name cache and check yet again
685 # Copy sys.modules in order to cope with changes while iterating
Éric Araujoa74f8ef2011-11-29 16:58:53 +0100686 for modname, module in list(sys.modules.items()):
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000687 if ismodule(module) and hasattr(module, '__file__'):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000688 f = module.__file__
689 if f == _filesbymodname.get(modname, None):
690 # Have already mapped this module, so skip it
691 continue
692 _filesbymodname[modname] = f
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000693 f = getabsfile(module)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000694 # Always map to the name the module knows itself by
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000695 modulesbyfile[f] = modulesbyfile[
696 os.path.realpath(f)] = module.__name__
Raymond Hettinger54f02222002-06-01 14:18:47 +0000697 if file in modulesbyfile:
Ka-Ping Yeeb38bbbd2003-03-28 16:29:50 +0000698 return sys.modules.get(modulesbyfile[file])
Thomas Wouters89f507f2006-12-13 04:49:30 +0000699 # Check the main module
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000700 main = sys.modules['__main__']
Brett Cannon4a671fe2003-06-15 22:33:28 +0000701 if not hasattr(object, '__name__'):
702 return None
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000703 if hasattr(main, object.__name__):
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000704 mainobject = getattr(main, object.__name__)
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000705 if mainobject is object:
706 return main
Thomas Wouters89f507f2006-12-13 04:49:30 +0000707 # Check builtins
Georg Brandl1a3284e2007-12-02 09:40:06 +0000708 builtin = sys.modules['builtins']
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000709 if hasattr(builtin, object.__name__):
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000710 builtinobject = getattr(builtin, object.__name__)
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000711 if builtinobject is object:
712 return builtin
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000713
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000714def findsource(object):
715 """Return the entire source file and starting line number for an object.
716
717 The argument may be a module, class, method, function, traceback, frame,
718 or code object. The source code is returned as a list of all the lines
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200719 in the file and the line number indexes a line in that list. An OSError
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000720 is raised if the source code cannot be retrieved."""
Benjamin Peterson9620cc02011-06-11 15:53:11 -0500721
Yury Selivanovef1e7502014-12-08 16:05:34 -0500722 file = getsourcefile(object)
723 if file:
724 # Invalidate cache if needed.
725 linecache.checkcache(file)
726 else:
727 file = getfile(object)
728 # Allow filenames in form of "<something>" to pass through.
729 # `doctest` monkeypatches `linecache` module to enable
730 # inspection, so let `linecache.getlines` to be called.
731 if not (file.startswith('<') and file.endswith('>')):
732 raise OSError('source code not available')
Benjamin Peterson9620cc02011-06-11 15:53:11 -0500733
Thomas Wouters89f507f2006-12-13 04:49:30 +0000734 module = getmodule(object, file)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000735 if module:
736 lines = linecache.getlines(file, module.__dict__)
737 else:
738 lines = linecache.getlines(file)
Neil Schemenauerf06f8532002-03-23 23:51:04 +0000739 if not lines:
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200740 raise OSError('could not get source code')
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000741
742 if ismodule(object):
743 return lines, 0
744
745 if isclass(object):
746 name = object.__name__
Thomas Wouters89f507f2006-12-13 04:49:30 +0000747 pat = re.compile(r'^(\s*)class\s*' + name + r'\b')
748 # make some effort to find the best matching class definition:
749 # use the one with the least indentation, which is the one
750 # that's most probably not inside a function definition.
751 candidates = []
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000752 for i in range(len(lines)):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000753 match = pat.match(lines[i])
754 if match:
755 # if it's at toplevel, it's already the best one
756 if lines[i][0] == 'c':
757 return lines, i
758 # else add whitespace to candidate list
759 candidates.append((match.group(1), i))
760 if candidates:
761 # this will sort by whitespace, and by line number,
762 # less whitespace first
763 candidates.sort()
764 return lines, candidates[0][1]
Jeremy Hyltonab919022003-06-27 18:41:20 +0000765 else:
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200766 raise OSError('could not find class definition')
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000767
768 if ismethod(object):
Christian Heimesff737952007-11-27 10:40:20 +0000769 object = object.__func__
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000770 if isfunction(object):
Neal Norwitz221085d2007-02-25 20:55:47 +0000771 object = object.__code__
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000772 if istraceback(object):
773 object = object.tb_frame
774 if isframe(object):
775 object = object.f_code
776 if iscode(object):
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000777 if not hasattr(object, 'co_firstlineno'):
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200778 raise OSError('could not find function definition')
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000779 lnum = object.co_firstlineno - 1
Johannes Gijsbers1542f342004-12-12 16:46:28 +0000780 pat = re.compile(r'^(\s*def\s)|(.*(?<!\w)lambda(:|\s))|^(\s*@)')
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000781 while lnum > 0:
Ka-Ping Yeea6e59712001-03-10 09:31:55 +0000782 if pat.match(lines[lnum]): break
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000783 lnum = lnum - 1
784 return lines, lnum
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200785 raise OSError('could not find code object')
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000786
787def getcomments(object):
Jeremy Hyltonb4c17c82002-03-28 23:01:56 +0000788 """Get lines of comments immediately preceding an object's source code.
789
790 Returns None when source can't be found.
791 """
792 try:
793 lines, lnum = findsource(object)
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200794 except (OSError, TypeError):
Jeremy Hyltonb4c17c82002-03-28 23:01:56 +0000795 return None
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000796
797 if ismodule(object):
798 # Look for a comment block at the top of the file.
799 start = 0
Ka-Ping Yeeb910efe2001-04-12 13:17:17 +0000800 if lines and lines[0][:2] == '#!': start = 1
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000801 while start < len(lines) and lines[start].strip() in ('', '#'):
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000802 start = start + 1
Ka-Ping Yeeb910efe2001-04-12 13:17:17 +0000803 if start < len(lines) and lines[start][:1] == '#':
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000804 comments = []
805 end = start
806 while end < len(lines) and lines[end][:1] == '#':
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000807 comments.append(lines[end].expandtabs())
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000808 end = end + 1
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000809 return ''.join(comments)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000810
811 # Look for a preceding block of comments at the same indentation.
812 elif lnum > 0:
813 indent = indentsize(lines[lnum])
814 end = lnum - 1
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000815 if end >= 0 and lines[end].lstrip()[:1] == '#' and \
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000816 indentsize(lines[end]) == indent:
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000817 comments = [lines[end].expandtabs().lstrip()]
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000818 if end > 0:
819 end = end - 1
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000820 comment = lines[end].expandtabs().lstrip()
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000821 while comment[:1] == '#' and indentsize(lines[end]) == indent:
822 comments[:0] = [comment]
823 end = end - 1
824 if end < 0: break
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000825 comment = lines[end].expandtabs().lstrip()
826 while comments and comments[0].strip() == '#':
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000827 comments[:1] = []
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000828 while comments and comments[-1].strip() == '#':
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000829 comments[-1:] = []
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000830 return ''.join(comments)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000831
Tim Peters4efb6e92001-06-29 23:51:08 +0000832class EndOfBlock(Exception): pass
833
834class BlockFinder:
835 """Provide a tokeneater() method to detect the end of a code block."""
836 def __init__(self):
837 self.indent = 0
Johannes Gijsbersa5855d52005-03-12 16:37:11 +0000838 self.islambda = False
Johannes Gijsbers1542f342004-12-12 16:46:28 +0000839 self.started = False
840 self.passline = False
Armin Rigodd5c0232005-09-25 11:45:45 +0000841 self.last = 1
Tim Peters4efb6e92001-06-29 23:51:08 +0000842
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000843 def tokeneater(self, type, token, srowcol, erowcol, line):
Tim Peters4efb6e92001-06-29 23:51:08 +0000844 if not self.started:
Armin Rigodd5c0232005-09-25 11:45:45 +0000845 # look for the first "def", "class" or "lambda"
Johannes Gijsbers1542f342004-12-12 16:46:28 +0000846 if token in ("def", "class", "lambda"):
Johannes Gijsbersa5855d52005-03-12 16:37:11 +0000847 if token == "lambda":
848 self.islambda = True
Johannes Gijsbers1542f342004-12-12 16:46:28 +0000849 self.started = True
Armin Rigodd5c0232005-09-25 11:45:45 +0000850 self.passline = True # skip to the end of the line
Tim Peters4efb6e92001-06-29 23:51:08 +0000851 elif type == tokenize.NEWLINE:
Armin Rigodd5c0232005-09-25 11:45:45 +0000852 self.passline = False # stop skipping when a NEWLINE is seen
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000853 self.last = srowcol[0]
Armin Rigodd5c0232005-09-25 11:45:45 +0000854 if self.islambda: # lambdas always end at the first NEWLINE
855 raise EndOfBlock
Johannes Gijsbers1542f342004-12-12 16:46:28 +0000856 elif self.passline:
857 pass
Tim Peters4efb6e92001-06-29 23:51:08 +0000858 elif type == tokenize.INDENT:
859 self.indent = self.indent + 1
Johannes Gijsbers1542f342004-12-12 16:46:28 +0000860 self.passline = True
Tim Peters4efb6e92001-06-29 23:51:08 +0000861 elif type == tokenize.DEDENT:
862 self.indent = self.indent - 1
Armin Rigodd5c0232005-09-25 11:45:45 +0000863 # the end of matching indent/dedent pairs end a block
864 # (note that this only works for "def"/"class" blocks,
865 # not e.g. for "if: else:" or "try: finally:" blocks)
866 if self.indent <= 0:
867 raise EndOfBlock
868 elif self.indent == 0 and type not in (tokenize.COMMENT, tokenize.NL):
869 # any other token on the same indentation level end the previous
870 # block as well, except the pseudo-tokens COMMENT and NL.
871 raise EndOfBlock
Tim Peters4efb6e92001-06-29 23:51:08 +0000872
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000873def getblock(lines):
874 """Extract the block of code at the top of the given list of lines."""
Armin Rigodd5c0232005-09-25 11:45:45 +0000875 blockfinder = BlockFinder()
Tim Peters4efb6e92001-06-29 23:51:08 +0000876 try:
Trent Nelson428de652008-03-18 22:41:35 +0000877 tokens = tokenize.generate_tokens(iter(lines).__next__)
878 for _token in tokens:
879 blockfinder.tokeneater(*_token)
Armin Rigodd5c0232005-09-25 11:45:45 +0000880 except (EndOfBlock, IndentationError):
881 pass
882 return lines[:blockfinder.last]
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000883
Antoine Pitroua8723a02015-04-15 00:41:29 +0200884def _line_number_helper(code_obj, lines, lnum):
885 """Return a list of source lines and starting line number for a code object.
886
887 The arguments must be a code object with lines and lnum from findsource.
888 """
889 _, end_line = list(dis.findlinestarts(code_obj))[-1]
890 return lines[lnum:end_line], lnum + 1
891
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000892def getsourcelines(object):
893 """Return a list of source lines and starting line number for an object.
894
895 The argument may be a module, class, method, function, traceback, frame,
896 or code object. The source code is returned as a list of the lines
897 corresponding to the object and the line number indicates where in the
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200898 original source file the first line of code was found. An OSError is
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000899 raised if the source code cannot be retrieved."""
Yury Selivanov081bbf62014-09-26 17:34:54 -0400900 object = unwrap(object)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000901 lines, lnum = findsource(object)
902
Antoine Pitroua8723a02015-04-15 00:41:29 +0200903 if ismodule(object):
904 return lines, 0
905 elif iscode(object):
906 return _line_number_helper(object, lines, lnum)
907 elif isfunction(object):
908 return _line_number_helper(object.__code__, lines, lnum)
909 elif ismethod(object):
910 return _line_number_helper(object.__func__.__code__, lines, lnum)
911 else:
912 return getblock(lines[lnum:]), lnum + 1
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000913
914def getsource(object):
915 """Return the text of the source code for an object.
916
917 The argument may be a module, class, method, function, traceback, frame,
918 or code object. The source code is returned as a single string. An
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200919 OSError is raised if the source code cannot be retrieved."""
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000920 lines, lnum = getsourcelines(object)
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000921 return ''.join(lines)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000922
923# --------------------------------------------------- class tree extraction
924def walktree(classes, children, parent):
925 """Recursive helper function for getclasstree()."""
926 results = []
Raymond Hettingera1a992c2005-03-11 06:46:45 +0000927 classes.sort(key=attrgetter('__module__', '__name__'))
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000928 for c in classes:
929 results.append((c, c.__bases__))
Raymond Hettinger54f02222002-06-01 14:18:47 +0000930 if c in children:
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000931 results.append(walktree(children[c], children, c))
932 return results
933
Georg Brandl5ce83a02009-06-01 17:23:51 +0000934def getclasstree(classes, unique=False):
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000935 """Arrange the given list of classes into a hierarchy of nested lists.
936
937 Where a nested list appears, it contains classes derived from the class
938 whose entry immediately precedes the list. Each entry is a 2-tuple
939 containing a class and a tuple of its base classes. If the 'unique'
940 argument is true, exactly one entry appears in the returned structure
941 for each class in the given list. Otherwise, classes using multiple
942 inheritance and their descendants will appear multiple times."""
943 children = {}
944 roots = []
945 for c in classes:
946 if c.__bases__:
947 for parent in c.__bases__:
Raymond Hettinger54f02222002-06-01 14:18:47 +0000948 if not parent in children:
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000949 children[parent] = []
Serhiy Storchaka362c1b52013-09-05 17:14:32 +0300950 if c not in children[parent]:
951 children[parent].append(c)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000952 if unique and parent in classes: break
953 elif c not in roots:
954 roots.append(c)
Raymond Hettingere0d49722002-06-02 18:55:56 +0000955 for parent in children:
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000956 if parent not in classes:
957 roots.append(parent)
958 return walktree(roots, children, None)
959
960# ------------------------------------------------ argument list extraction
Christian Heimes25bb7832008-01-11 16:17:00 +0000961Arguments = namedtuple('Arguments', 'args, varargs, varkw')
962
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000963def getargs(co):
964 """Get information about the arguments accepted by a code object.
965
Guido van Rossum2e65f892007-02-28 22:03:49 +0000966 Three things are returned: (args, varargs, varkw), where
Georg Brandlc1c4bf82010-10-15 16:07:41 +0000967 'args' is the list of argument names. Keyword-only arguments are
968 appended. 'varargs' and 'varkw' are the names of the * and **
969 arguments or None."""
Guido van Rossum2e65f892007-02-28 22:03:49 +0000970 args, varargs, kwonlyargs, varkw = _getfullargs(co)
Christian Heimes25bb7832008-01-11 16:17:00 +0000971 return Arguments(args + kwonlyargs, varargs, varkw)
Guido van Rossum2e65f892007-02-28 22:03:49 +0000972
973def _getfullargs(co):
974 """Get information about the arguments accepted by a code object.
975
976 Four things are returned: (args, varargs, kwonlyargs, varkw), where
Georg Brandlc1c4bf82010-10-15 16:07:41 +0000977 'args' and 'kwonlyargs' are lists of argument names, and 'varargs'
978 and 'varkw' are the names of the * and ** arguments or None."""
Jeremy Hylton64967882003-06-27 18:14:39 +0000979
980 if not iscode(co):
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +0000981 raise TypeError('{!r} is not a code object'.format(co))
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000982
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000983 nargs = co.co_argcount
984 names = co.co_varnames
Guido van Rossum2e65f892007-02-28 22:03:49 +0000985 nkwargs = co.co_kwonlyargcount
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000986 args = list(names[:nargs])
Guido van Rossum2e65f892007-02-28 22:03:49 +0000987 kwonlyargs = list(names[nargs:nargs+nkwargs])
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000988 step = 0
989
Guido van Rossum2e65f892007-02-28 22:03:49 +0000990 nargs += nkwargs
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000991 varargs = None
992 if co.co_flags & CO_VARARGS:
993 varargs = co.co_varnames[nargs]
994 nargs = nargs + 1
995 varkw = None
996 if co.co_flags & CO_VARKEYWORDS:
997 varkw = co.co_varnames[nargs]
Guido van Rossum2e65f892007-02-28 22:03:49 +0000998 return args, varargs, kwonlyargs, varkw
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000999
Christian Heimes25bb7832008-01-11 16:17:00 +00001000
1001ArgSpec = namedtuple('ArgSpec', 'args varargs keywords defaults')
1002
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001003def getargspec(func):
1004 """Get the names and default values of a function's arguments.
1005
Guido van Rossume82881c2014-07-15 12:29:11 -07001006 A tuple of four things is returned: (args, varargs, keywords, defaults).
1007 'args' is a list of the argument names, including keyword-only argument names.
1008 'varargs' and 'keywords' are the names of the * and ** arguments or None.
Jeremy Hylton64967882003-06-27 18:14:39 +00001009 'defaults' is an n-tuple of the default values of the last n arguments.
Guido van Rossuma8add0e2007-05-14 22:03:55 +00001010
Yury Selivanov0cf3ed62014-04-01 10:17:08 -04001011 Use the getfullargspec() API for Python 3 code, as annotations
Guido van Rossum2e65f892007-02-28 22:03:49 +00001012 and keyword arguments are supported. getargspec() will raise ValueError
1013 if the func has either annotations or keyword arguments.
1014 """
1015
1016 args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults, ann = \
1017 getfullargspec(func)
1018 if kwonlyargs or ann:
Collin Winterce36ad82007-08-30 01:19:48 +00001019 raise ValueError("Function has keyword-only arguments or annotations"
1020 ", use getfullargspec() API which can support them")
Christian Heimes25bb7832008-01-11 16:17:00 +00001021 return ArgSpec(args, varargs, varkw, defaults)
1022
1023FullArgSpec = namedtuple('FullArgSpec',
Benjamin Peterson3d4ca742008-11-12 21:39:01 +00001024 'args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults, annotations')
Guido van Rossum2e65f892007-02-28 22:03:49 +00001025
1026def getfullargspec(func):
Yury Selivanovd82eddc2014-01-29 11:24:39 -05001027 """Get the names and default values of a callable object's arguments.
Guido van Rossum2e65f892007-02-28 22:03:49 +00001028
Brett Cannon504d8852007-09-07 02:12:14 +00001029 A tuple of seven things is returned:
1030 (args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults annotations).
Georg Brandlc1c4bf82010-10-15 16:07:41 +00001031 'args' is a list of the argument names.
Guido van Rossum2e65f892007-02-28 22:03:49 +00001032 'varargs' and 'varkw' are the names of the * and ** arguments or None.
1033 'defaults' is an n-tuple of the default values of the last n arguments.
1034 'kwonlyargs' is a list of keyword-only argument names.
1035 'kwonlydefaults' is a dictionary mapping names from kwonlyargs to defaults.
1036 'annotations' is a dictionary mapping argument names to annotations.
Guido van Rossuma8add0e2007-05-14 22:03:55 +00001037
Guido van Rossum2e65f892007-02-28 22:03:49 +00001038 The first four items in the tuple correspond to getargspec().
Jeremy Hylton64967882003-06-27 18:14:39 +00001039 """
1040
Yury Selivanov57d240e2014-02-19 16:27:23 -05001041 try:
1042 # Re: `skip_bound_arg=False`
1043 #
Yury Selivanovd82eddc2014-01-29 11:24:39 -05001044 # There is a notable difference in behaviour between getfullargspec
1045 # and Signature: the former always returns 'self' parameter for bound
1046 # methods, whereas the Signature always shows the actual calling
1047 # signature of the passed object.
1048 #
1049 # To simulate this behaviour, we "unbind" bound methods, to trick
1050 # inspect.signature to always return their first parameter ("self",
1051 # usually)
Yury Selivanovd82eddc2014-01-29 11:24:39 -05001052
Yury Selivanov57d240e2014-02-19 16:27:23 -05001053 # Re: `follow_wrapper_chains=False`
1054 #
1055 # getfullargspec() historically ignored __wrapped__ attributes,
1056 # so we ensure that remains the case in 3.3+
Yury Selivanovd82eddc2014-01-29 11:24:39 -05001057
Yury Selivanov5a23bd02014-03-29 13:47:11 -04001058 sig = _signature_from_callable(func,
1059 follow_wrapper_chains=False,
1060 skip_bound_arg=False,
1061 sigcls=Signature)
Yury Selivanovd82eddc2014-01-29 11:24:39 -05001062 except Exception as ex:
1063 # Most of the times 'signature' will raise ValueError.
1064 # But, it can also raise AttributeError, and, maybe something
1065 # else. So to be fully backwards compatible, we catch all
1066 # possible exceptions here, and reraise a TypeError.
1067 raise TypeError('unsupported callable') from ex
1068
1069 args = []
1070 varargs = None
1071 varkw = None
1072 kwonlyargs = []
1073 defaults = ()
1074 annotations = {}
1075 defaults = ()
1076 kwdefaults = {}
1077
1078 if sig.return_annotation is not sig.empty:
1079 annotations['return'] = sig.return_annotation
1080
1081 for param in sig.parameters.values():
1082 kind = param.kind
1083 name = param.name
1084
1085 if kind is _POSITIONAL_ONLY:
1086 args.append(name)
1087 elif kind is _POSITIONAL_OR_KEYWORD:
1088 args.append(name)
1089 if param.default is not param.empty:
1090 defaults += (param.default,)
1091 elif kind is _VAR_POSITIONAL:
1092 varargs = name
1093 elif kind is _KEYWORD_ONLY:
1094 kwonlyargs.append(name)
1095 if param.default is not param.empty:
1096 kwdefaults[name] = param.default
1097 elif kind is _VAR_KEYWORD:
1098 varkw = name
1099
1100 if param.annotation is not param.empty:
1101 annotations[name] = param.annotation
1102
1103 if not kwdefaults:
1104 # compatibility with 'func.__kwdefaults__'
1105 kwdefaults = None
1106
1107 if not defaults:
1108 # compatibility with 'func.__defaults__'
1109 defaults = None
1110
Yury Selivanovd82eddc2014-01-29 11:24:39 -05001111 return FullArgSpec(args, varargs, varkw, defaults,
1112 kwonlyargs, kwdefaults, annotations)
1113
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001114
Christian Heimes25bb7832008-01-11 16:17:00 +00001115ArgInfo = namedtuple('ArgInfo', 'args varargs keywords locals')
1116
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001117def getargvalues(frame):
1118 """Get information about arguments passed into a particular frame.
1119
1120 A tuple of four things is returned: (args, varargs, varkw, locals).
Georg Brandlc1c4bf82010-10-15 16:07:41 +00001121 'args' is a list of the argument names.
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001122 'varargs' and 'varkw' are the names of the * and ** arguments or None.
1123 'locals' is the locals dictionary of the given frame."""
1124 args, varargs, varkw = getargs(frame.f_code)
Benjamin Peterson1a6e0d02008-10-25 15:49:17 +00001125 return ArgInfo(args, varargs, varkw, frame.f_locals)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001126
Guido van Rossum2e65f892007-02-28 22:03:49 +00001127def formatannotation(annotation, base_module=None):
1128 if isinstance(annotation, type):
Georg Brandl1a3284e2007-12-02 09:40:06 +00001129 if annotation.__module__ in ('builtins', base_module):
Serhiy Storchaka521e5862014-07-22 15:00:37 +03001130 return annotation.__qualname__
1131 return annotation.__module__+'.'+annotation.__qualname__
Guido van Rossum2e65f892007-02-28 22:03:49 +00001132 return repr(annotation)
Guido van Rossuma8add0e2007-05-14 22:03:55 +00001133
Guido van Rossum2e65f892007-02-28 22:03:49 +00001134def formatannotationrelativeto(object):
Guido van Rossuma8add0e2007-05-14 22:03:55 +00001135 module = getattr(object, '__module__', None)
1136 def _formatannotation(annotation):
1137 return formatannotation(annotation, module)
1138 return _formatannotation
Guido van Rossum2e65f892007-02-28 22:03:49 +00001139
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001140def formatargspec(args, varargs=None, varkw=None, defaults=None,
Guido van Rossum2e65f892007-02-28 22:03:49 +00001141 kwonlyargs=(), kwonlydefaults={}, annotations={},
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001142 formatarg=str,
1143 formatvarargs=lambda name: '*' + name,
1144 formatvarkw=lambda name: '**' + name,
1145 formatvalue=lambda value: '=' + repr(value),
Guido van Rossum2e65f892007-02-28 22:03:49 +00001146 formatreturns=lambda text: ' -> ' + text,
Georg Brandlc1c4bf82010-10-15 16:07:41 +00001147 formatannotation=formatannotation):
Guido van Rossuma8add0e2007-05-14 22:03:55 +00001148 """Format an argument spec from the values returned by getargspec
Guido van Rossum2e65f892007-02-28 22:03:49 +00001149 or getfullargspec.
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001150
Guido van Rossum2e65f892007-02-28 22:03:49 +00001151 The first seven arguments are (args, varargs, varkw, defaults,
1152 kwonlyargs, kwonlydefaults, annotations). The other five arguments
1153 are the corresponding optional formatting functions that are called to
1154 turn names and values into strings. The last argument is an optional
1155 function to format the sequence of arguments."""
1156 def formatargandannotation(arg):
1157 result = formatarg(arg)
1158 if arg in annotations:
1159 result += ': ' + formatannotation(annotations[arg])
1160 return result
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001161 specs = []
1162 if defaults:
1163 firstdefault = len(args) - len(defaults)
Benjamin Petersonb58dda72009-01-18 22:27:04 +00001164 for i, arg in enumerate(args):
Georg Brandlc1c4bf82010-10-15 16:07:41 +00001165 spec = formatargandannotation(arg)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001166 if defaults and i >= firstdefault:
1167 spec = spec + formatvalue(defaults[i - firstdefault])
1168 specs.append(spec)
Raymond Hettinger936654b2002-06-01 03:06:31 +00001169 if varargs is not None:
Guido van Rossum2e65f892007-02-28 22:03:49 +00001170 specs.append(formatvarargs(formatargandannotation(varargs)))
1171 else:
1172 if kwonlyargs:
1173 specs.append('*')
1174 if kwonlyargs:
1175 for kwonlyarg in kwonlyargs:
1176 spec = formatargandannotation(kwonlyarg)
Benjamin Peterson9953a8d2009-01-17 04:15:01 +00001177 if kwonlydefaults and kwonlyarg in kwonlydefaults:
Guido van Rossum2e65f892007-02-28 22:03:49 +00001178 spec += formatvalue(kwonlydefaults[kwonlyarg])
1179 specs.append(spec)
Raymond Hettinger936654b2002-06-01 03:06:31 +00001180 if varkw is not None:
Guido van Rossum2e65f892007-02-28 22:03:49 +00001181 specs.append(formatvarkw(formatargandannotation(varkw)))
Neal Norwitz9d72bb42007-04-17 08:48:32 +00001182 result = '(' + ', '.join(specs) + ')'
Guido van Rossum2e65f892007-02-28 22:03:49 +00001183 if 'return' in annotations:
1184 result += formatreturns(formatannotation(annotations['return']))
1185 return result
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001186
1187def formatargvalues(args, varargs, varkw, locals,
1188 formatarg=str,
1189 formatvarargs=lambda name: '*' + name,
1190 formatvarkw=lambda name: '**' + name,
Georg Brandlc1c4bf82010-10-15 16:07:41 +00001191 formatvalue=lambda value: '=' + repr(value)):
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001192 """Format an argument spec from the 4 values returned by getargvalues.
1193
1194 The first four arguments are (args, varargs, varkw, locals). The
1195 next four arguments are the corresponding optional formatting functions
1196 that are called to turn names and values into strings. The ninth
1197 argument is an optional function to format the sequence of arguments."""
1198 def convert(name, locals=locals,
1199 formatarg=formatarg, formatvalue=formatvalue):
1200 return formatarg(name) + formatvalue(locals[name])
1201 specs = []
1202 for i in range(len(args)):
Georg Brandlc1c4bf82010-10-15 16:07:41 +00001203 specs.append(convert(args[i]))
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001204 if varargs:
1205 specs.append(formatvarargs(varargs) + formatvalue(locals[varargs]))
1206 if varkw:
1207 specs.append(formatvarkw(varkw) + formatvalue(locals[varkw]))
Neal Norwitz9d72bb42007-04-17 08:48:32 +00001208 return '(' + ', '.join(specs) + ')'
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001209
Benjamin Petersone109c702011-06-24 09:37:26 -05001210def _missing_arguments(f_name, argnames, pos, values):
1211 names = [repr(name) for name in argnames if name not in values]
1212 missing = len(names)
1213 if missing == 1:
1214 s = names[0]
1215 elif missing == 2:
1216 s = "{} and {}".format(*names)
1217 else:
Yury Selivanovdccfa132014-03-27 18:42:52 -04001218 tail = ", {} and {}".format(*names[-2:])
Benjamin Petersone109c702011-06-24 09:37:26 -05001219 del names[-2:]
1220 s = ", ".join(names) + tail
1221 raise TypeError("%s() missing %i required %s argument%s: %s" %
1222 (f_name, missing,
1223 "positional" if pos else "keyword-only",
1224 "" if missing == 1 else "s", s))
1225
1226def _too_many(f_name, args, kwonly, varargs, defcount, given, values):
Benjamin Petersonb204a422011-06-05 22:04:07 -05001227 atleast = len(args) - defcount
Benjamin Petersonb204a422011-06-05 22:04:07 -05001228 kwonly_given = len([arg for arg in kwonly if arg in values])
1229 if varargs:
1230 plural = atleast != 1
1231 sig = "at least %d" % (atleast,)
1232 elif defcount:
1233 plural = True
1234 sig = "from %d to %d" % (atleast, len(args))
1235 else:
1236 plural = len(args) != 1
1237 sig = str(len(args))
1238 kwonly_sig = ""
1239 if kwonly_given:
1240 msg = " positional argument%s (and %d keyword-only argument%s)"
1241 kwonly_sig = (msg % ("s" if given != 1 else "", kwonly_given,
1242 "s" if kwonly_given != 1 else ""))
1243 raise TypeError("%s() takes %s positional argument%s but %d%s %s given" %
1244 (f_name, sig, "s" if plural else "", given, kwonly_sig,
1245 "was" if given == 1 and not kwonly_given else "were"))
1246
Benjamin Peterson3e6ab172014-01-02 12:24:08 -06001247def getcallargs(*func_and_positional, **named):
Benjamin Peterson25cd7eb2010-03-30 18:42:32 +00001248 """Get the mapping of arguments to values.
1249
1250 A dict is returned, with keys the function argument names (including the
1251 names of the * and ** arguments, if any), and values the respective bound
1252 values from 'positional' and 'named'."""
Benjamin Peterson3e6ab172014-01-02 12:24:08 -06001253 func = func_and_positional[0]
1254 positional = func_and_positional[1:]
Benjamin Peterson25cd7eb2010-03-30 18:42:32 +00001255 spec = getfullargspec(func)
1256 args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults, ann = spec
1257 f_name = func.__name__
1258 arg2value = {}
1259
Benjamin Petersonb204a422011-06-05 22:04:07 -05001260
Benjamin Peterson25cd7eb2010-03-30 18:42:32 +00001261 if ismethod(func) and func.__self__ is not None:
1262 # implicit 'self' (or 'cls' for classmethods) argument
1263 positional = (func.__self__,) + positional
1264 num_pos = len(positional)
Benjamin Peterson25cd7eb2010-03-30 18:42:32 +00001265 num_args = len(args)
1266 num_defaults = len(defaults) if defaults else 0
Benjamin Peterson25cd7eb2010-03-30 18:42:32 +00001267
Benjamin Petersonb204a422011-06-05 22:04:07 -05001268 n = min(num_pos, num_args)
1269 for i in range(n):
1270 arg2value[args[i]] = positional[i]
1271 if varargs:
1272 arg2value[varargs] = tuple(positional[n:])
1273 possible_kwargs = set(args + kwonlyargs)
Benjamin Peterson25cd7eb2010-03-30 18:42:32 +00001274 if varkw:
Benjamin Petersonb204a422011-06-05 22:04:07 -05001275 arg2value[varkw] = {}
1276 for kw, value in named.items():
1277 if kw not in possible_kwargs:
1278 if not varkw:
1279 raise TypeError("%s() got an unexpected keyword argument %r" %
1280 (f_name, kw))
1281 arg2value[varkw][kw] = value
1282 continue
1283 if kw in arg2value:
1284 raise TypeError("%s() got multiple values for argument %r" %
1285 (f_name, kw))
1286 arg2value[kw] = value
1287 if num_pos > num_args and not varargs:
Benjamin Petersone109c702011-06-24 09:37:26 -05001288 _too_many(f_name, args, kwonlyargs, varargs, num_defaults,
1289 num_pos, arg2value)
Benjamin Petersonb204a422011-06-05 22:04:07 -05001290 if num_pos < num_args:
Benjamin Petersone109c702011-06-24 09:37:26 -05001291 req = args[:num_args - num_defaults]
1292 for arg in req:
Benjamin Petersonb204a422011-06-05 22:04:07 -05001293 if arg not in arg2value:
Benjamin Petersone109c702011-06-24 09:37:26 -05001294 _missing_arguments(f_name, req, True, arg2value)
Benjamin Petersonb204a422011-06-05 22:04:07 -05001295 for i, arg in enumerate(args[num_args - num_defaults:]):
1296 if arg not in arg2value:
1297 arg2value[arg] = defaults[i]
Benjamin Petersone109c702011-06-24 09:37:26 -05001298 missing = 0
Benjamin Petersonb204a422011-06-05 22:04:07 -05001299 for kwarg in kwonlyargs:
1300 if kwarg not in arg2value:
Yury Selivanov875df202014-03-27 18:23:03 -04001301 if kwonlydefaults and kwarg in kwonlydefaults:
Benjamin Petersone109c702011-06-24 09:37:26 -05001302 arg2value[kwarg] = kwonlydefaults[kwarg]
1303 else:
1304 missing += 1
1305 if missing:
1306 _missing_arguments(f_name, kwonlyargs, False, arg2value)
Benjamin Peterson25cd7eb2010-03-30 18:42:32 +00001307 return arg2value
1308
Nick Coghlan2f92e542012-06-23 19:39:55 +10001309ClosureVars = namedtuple('ClosureVars', 'nonlocals globals builtins unbound')
1310
1311def getclosurevars(func):
1312 """
1313 Get the mapping of free variables to their current values.
1314
Meador Inge8fda3592012-07-19 21:33:21 -05001315 Returns a named tuple of dicts mapping the current nonlocal, global
Nick Coghlan2f92e542012-06-23 19:39:55 +10001316 and builtin references as seen by the body of the function. A final
1317 set of unbound names that could not be resolved is also provided.
1318 """
1319
1320 if ismethod(func):
1321 func = func.__func__
1322
1323 if not isfunction(func):
1324 raise TypeError("'{!r}' is not a Python function".format(func))
1325
1326 code = func.__code__
1327 # Nonlocal references are named in co_freevars and resolved
1328 # by looking them up in __closure__ by positional index
1329 if func.__closure__ is None:
1330 nonlocal_vars = {}
1331 else:
1332 nonlocal_vars = {
1333 var : cell.cell_contents
1334 for var, cell in zip(code.co_freevars, func.__closure__)
1335 }
1336
1337 # Global and builtin references are named in co_names and resolved
1338 # by looking them up in __globals__ or __builtins__
1339 global_ns = func.__globals__
1340 builtin_ns = global_ns.get("__builtins__", builtins.__dict__)
1341 if ismodule(builtin_ns):
1342 builtin_ns = builtin_ns.__dict__
1343 global_vars = {}
1344 builtin_vars = {}
1345 unbound_names = set()
1346 for name in code.co_names:
1347 if name in ("None", "True", "False"):
1348 # Because these used to be builtins instead of keywords, they
1349 # may still show up as name references. We ignore them.
1350 continue
1351 try:
1352 global_vars[name] = global_ns[name]
1353 except KeyError:
1354 try:
1355 builtin_vars[name] = builtin_ns[name]
1356 except KeyError:
1357 unbound_names.add(name)
1358
1359 return ClosureVars(nonlocal_vars, global_vars,
1360 builtin_vars, unbound_names)
1361
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001362# -------------------------------------------------- stack frame extraction
Christian Heimes25bb7832008-01-11 16:17:00 +00001363
1364Traceback = namedtuple('Traceback', 'filename lineno function code_context index')
1365
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001366def getframeinfo(frame, context=1):
1367 """Get information about a frame or traceback object.
1368
1369 A tuple of five things is returned: the filename, the line number of
1370 the current line, the function name, a list of lines of context from
1371 the source code, and the index of the current line within that list.
1372 The optional second argument specifies the number of lines of context
1373 to return, which are centered around the current line."""
1374 if istraceback(frame):
Andrew M. Kuchlingba8b6bc2004-06-05 14:11:59 +00001375 lineno = frame.tb_lineno
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001376 frame = frame.tb_frame
Andrew M. Kuchlingba8b6bc2004-06-05 14:11:59 +00001377 else:
1378 lineno = frame.f_lineno
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001379 if not isframe(frame):
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00001380 raise TypeError('{!r} is not a frame or traceback object'.format(frame))
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001381
Neil Schemenauerf06f8532002-03-23 23:51:04 +00001382 filename = getsourcefile(frame) or getfile(frame)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001383 if context > 0:
Guido van Rossum54e54c62001-09-04 19:14:14 +00001384 start = lineno - 1 - context//2
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001385 try:
1386 lines, lnum = findsource(frame)
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02001387 except OSError:
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +00001388 lines = index = None
1389 else:
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001390 start = max(start, 1)
Raymond Hettingera0501712004-06-15 11:22:53 +00001391 start = max(0, min(start, len(lines) - context))
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001392 lines = lines[start:start+context]
Ka-Ping Yee59ade082001-03-01 03:55:35 +00001393 index = lineno - 1 - start
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001394 else:
1395 lines = index = None
1396
Christian Heimes25bb7832008-01-11 16:17:00 +00001397 return Traceback(filename, lineno, frame.f_code.co_name, lines, index)
Ka-Ping Yee59ade082001-03-01 03:55:35 +00001398
1399def getlineno(frame):
1400 """Get the line number from a frame object, allowing for optimization."""
Michael W. Hudsondd32a912002-08-15 14:59:02 +00001401 # FrameType.f_lineno is now a descriptor that grovels co_lnotab
1402 return frame.f_lineno
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001403
Antoine Pitroucdcafb72014-08-24 10:50:28 -04001404FrameInfo = namedtuple('FrameInfo', ('frame',) + Traceback._fields)
1405
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001406def getouterframes(frame, context=1):
1407 """Get a list of records for a frame and all higher (calling) frames.
1408
1409 Each record contains a frame object, filename, line number, function
1410 name, a list of lines of context, and index within the context."""
1411 framelist = []
1412 while frame:
Antoine Pitroucdcafb72014-08-24 10:50:28 -04001413 frameinfo = (frame,) + getframeinfo(frame, context)
1414 framelist.append(FrameInfo(*frameinfo))
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001415 frame = frame.f_back
1416 return framelist
1417
1418def getinnerframes(tb, context=1):
1419 """Get a list of records for a traceback's frame and all lower frames.
1420
1421 Each record contains a frame object, filename, line number, function
1422 name, a list of lines of context, and index within the context."""
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001423 framelist = []
1424 while tb:
Antoine Pitroucdcafb72014-08-24 10:50:28 -04001425 frameinfo = (tb.tb_frame,) + getframeinfo(tb, context)
1426 framelist.append(FrameInfo(*frameinfo))
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001427 tb = tb.tb_next
1428 return framelist
1429
Benjamin Peterson42ac4752010-08-09 13:05:35 +00001430def currentframe():
Benjamin Petersona3a3fc62010-08-09 15:49:56 +00001431 """Return the frame of the caller or None if this is not possible."""
Benjamin Peterson42ac4752010-08-09 13:05:35 +00001432 return sys._getframe(1) if hasattr(sys, "_getframe") else None
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001433
1434def stack(context=1):
1435 """Return a list of records for the stack above the caller's frame."""
Jeremy Hyltonab919022003-06-27 18:41:20 +00001436 return getouterframes(sys._getframe(1), context)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001437
1438def trace(context=1):
Tim Peters85ba6732001-02-28 08:26:44 +00001439 """Return a list of records for the stack below the current exception."""
Fred Draked451ec12002-04-26 02:29:55 +00001440 return getinnerframes(sys.exc_info()[2], context)
Michael Foord95fc51d2010-11-20 15:07:30 +00001441
1442
1443# ------------------------------------------------ static version of getattr
1444
1445_sentinel = object()
1446
Michael Foorde5162652010-11-20 16:40:44 +00001447def _static_getmro(klass):
1448 return type.__dict__['__mro__'].__get__(klass)
1449
Michael Foord95fc51d2010-11-20 15:07:30 +00001450def _check_instance(obj, attr):
1451 instance_dict = {}
1452 try:
1453 instance_dict = object.__getattribute__(obj, "__dict__")
1454 except AttributeError:
1455 pass
Michael Foorddcebe0f2011-03-15 19:20:44 -04001456 return dict.get(instance_dict, attr, _sentinel)
Michael Foord95fc51d2010-11-20 15:07:30 +00001457
1458
1459def _check_class(klass, attr):
Michael Foorde5162652010-11-20 16:40:44 +00001460 for entry in _static_getmro(klass):
Michael Foorda51623b2011-12-18 22:01:40 +00001461 if _shadowed_dict(type(entry)) is _sentinel:
Michael Foorddcebe0f2011-03-15 19:20:44 -04001462 try:
1463 return entry.__dict__[attr]
1464 except KeyError:
1465 pass
Michael Foord95fc51d2010-11-20 15:07:30 +00001466 return _sentinel
1467
Michael Foord35184ed2010-11-20 16:58:30 +00001468def _is_type(obj):
1469 try:
1470 _static_getmro(obj)
1471 except TypeError:
1472 return False
1473 return True
1474
Michael Foorddcebe0f2011-03-15 19:20:44 -04001475def _shadowed_dict(klass):
1476 dict_attr = type.__dict__["__dict__"]
1477 for entry in _static_getmro(klass):
1478 try:
1479 class_dict = dict_attr.__get__(entry)["__dict__"]
1480 except KeyError:
1481 pass
1482 else:
1483 if not (type(class_dict) is types.GetSetDescriptorType and
1484 class_dict.__name__ == "__dict__" and
1485 class_dict.__objclass__ is entry):
Michael Foorda51623b2011-12-18 22:01:40 +00001486 return class_dict
1487 return _sentinel
Michael Foord95fc51d2010-11-20 15:07:30 +00001488
1489def getattr_static(obj, attr, default=_sentinel):
1490 """Retrieve attributes without triggering dynamic lookup via the
1491 descriptor protocol, __getattr__ or __getattribute__.
1492
1493 Note: this function may not be able to retrieve all attributes
1494 that getattr can fetch (like dynamically created attributes)
1495 and may find attributes that getattr can't (like descriptors
1496 that raise AttributeError). It can also return descriptor objects
1497 instead of instance members in some cases. See the
1498 documentation for details.
1499 """
1500 instance_result = _sentinel
Michael Foord35184ed2010-11-20 16:58:30 +00001501 if not _is_type(obj):
Michael Foordcc7ebb82010-11-20 16:20:16 +00001502 klass = type(obj)
Michael Foorda51623b2011-12-18 22:01:40 +00001503 dict_attr = _shadowed_dict(klass)
1504 if (dict_attr is _sentinel or
1505 type(dict_attr) is types.MemberDescriptorType):
Michael Foorddcebe0f2011-03-15 19:20:44 -04001506 instance_result = _check_instance(obj, attr)
Michael Foord95fc51d2010-11-20 15:07:30 +00001507 else:
1508 klass = obj
1509
1510 klass_result = _check_class(klass, attr)
1511
1512 if instance_result is not _sentinel and klass_result is not _sentinel:
1513 if (_check_class(type(klass_result), '__get__') is not _sentinel and
1514 _check_class(type(klass_result), '__set__') is not _sentinel):
1515 return klass_result
1516
1517 if instance_result is not _sentinel:
1518 return instance_result
1519 if klass_result is not _sentinel:
1520 return klass_result
1521
1522 if obj is klass:
1523 # for types we check the metaclass too
Michael Foorde5162652010-11-20 16:40:44 +00001524 for entry in _static_getmro(type(klass)):
Michael Foord3ba95f82011-12-22 01:13:37 +00001525 if _shadowed_dict(type(entry)) is _sentinel:
1526 try:
1527 return entry.__dict__[attr]
1528 except KeyError:
1529 pass
Michael Foord95fc51d2010-11-20 15:07:30 +00001530 if default is not _sentinel:
1531 return default
1532 raise AttributeError(attr)
Nick Coghlane0f04652010-11-21 03:44:04 +00001533
1534
Nick Coghlan04e2e3f2012-06-23 19:52:05 +10001535# ------------------------------------------------ generator introspection
1536
Nick Coghlan7921b9f2010-11-30 06:36:04 +00001537GEN_CREATED = 'GEN_CREATED'
1538GEN_RUNNING = 'GEN_RUNNING'
1539GEN_SUSPENDED = 'GEN_SUSPENDED'
1540GEN_CLOSED = 'GEN_CLOSED'
Nick Coghlane0f04652010-11-21 03:44:04 +00001541
1542def getgeneratorstate(generator):
1543 """Get current state of a generator-iterator.
1544
1545 Possible states are:
1546 GEN_CREATED: Waiting to start execution.
1547 GEN_RUNNING: Currently being executed by the interpreter.
1548 GEN_SUSPENDED: Currently suspended at a yield expression.
1549 GEN_CLOSED: Execution has completed.
1550 """
1551 if generator.gi_running:
1552 return GEN_RUNNING
1553 if generator.gi_frame is None:
1554 return GEN_CLOSED
1555 if generator.gi_frame.f_lasti == -1:
1556 return GEN_CREATED
1557 return GEN_SUSPENDED
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07001558
1559
Nick Coghlan04e2e3f2012-06-23 19:52:05 +10001560def getgeneratorlocals(generator):
1561 """
1562 Get the mapping of generator local variables to their current values.
1563
1564 A dict is returned, with the keys the local variable names and values the
1565 bound values."""
1566
1567 if not isgenerator(generator):
1568 raise TypeError("'{!r}' is not a Python generator".format(generator))
1569
1570 frame = getattr(generator, "gi_frame", None)
1571 if frame is not None:
1572 return generator.gi_frame.f_locals
1573 else:
1574 return {}
1575
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07001576###############################################################################
1577### Function Signature Object (PEP 362)
1578###############################################################################
1579
1580
1581_WrapperDescriptor = type(type.__call__)
1582_MethodWrapper = type(all.__call__)
Larry Hastings5c661892014-01-24 06:17:25 -08001583_ClassMethodWrapper = type(int.__dict__['from_bytes'])
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07001584
1585_NonUserDefinedCallables = (_WrapperDescriptor,
1586 _MethodWrapper,
Larry Hastings5c661892014-01-24 06:17:25 -08001587 _ClassMethodWrapper,
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07001588 types.BuiltinFunctionType)
1589
1590
Yury Selivanov421f0c72014-01-29 12:05:40 -05001591def _signature_get_user_defined_method(cls, method_name):
Yury Selivanov5a23bd02014-03-29 13:47:11 -04001592 """Private helper. Checks if ``cls`` has an attribute
1593 named ``method_name`` and returns it only if it is a
1594 pure python function.
1595 """
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07001596 try:
1597 meth = getattr(cls, method_name)
1598 except AttributeError:
1599 return
1600 else:
1601 if not isinstance(meth, _NonUserDefinedCallables):
1602 # Once '__signature__' will be added to 'C'-level
1603 # callables, this check won't be necessary
1604 return meth
1605
1606
Yury Selivanov62560fb2014-01-28 12:26:24 -05001607def _signature_get_partial(wrapped_sig, partial, extra_args=()):
Yury Selivanov5a23bd02014-03-29 13:47:11 -04001608 """Private helper to calculate how 'wrapped_sig' signature will
1609 look like after applying a 'functools.partial' object (or alike)
1610 on it.
1611 """
Yury Selivanov62560fb2014-01-28 12:26:24 -05001612
Yury Selivanov3f73ca22014-04-08 11:30:45 -04001613 old_params = wrapped_sig.parameters
1614 new_params = OrderedDict(old_params.items())
Yury Selivanovda5fe4f2014-01-27 17:28:37 -05001615
1616 partial_args = partial.args or ()
1617 partial_keywords = partial.keywords or {}
1618
1619 if extra_args:
1620 partial_args = extra_args + partial_args
1621
1622 try:
1623 ba = wrapped_sig.bind_partial(*partial_args, **partial_keywords)
1624 except TypeError as ex:
1625 msg = 'partial object {!r} has incorrect arguments'.format(partial)
1626 raise ValueError(msg) from ex
1627
Yury Selivanovda5fe4f2014-01-27 17:28:37 -05001628
Yury Selivanov3f73ca22014-04-08 11:30:45 -04001629 transform_to_kwonly = False
1630 for param_name, param in old_params.items():
1631 try:
1632 arg_value = ba.arguments[param_name]
1633 except KeyError:
1634 pass
1635 else:
1636 if param.kind is _POSITIONAL_ONLY:
1637 # If positional-only parameter is bound by partial,
1638 # it effectively disappears from the signature
1639 new_params.pop(param_name)
1640 continue
1641
1642 if param.kind is _POSITIONAL_OR_KEYWORD:
1643 if param_name in partial_keywords:
1644 # This means that this parameter, and all parameters
1645 # after it should be keyword-only (and var-positional
1646 # should be removed). Here's why. Consider the following
1647 # function:
1648 # foo(a, b, *args, c):
1649 # pass
1650 #
1651 # "partial(foo, a='spam')" will have the following
1652 # signature: "(*, a='spam', b, c)". Because attempting
1653 # to call that partial with "(10, 20)" arguments will
1654 # raise a TypeError, saying that "a" argument received
1655 # multiple values.
1656 transform_to_kwonly = True
1657 # Set the new default value
1658 new_params[param_name] = param.replace(default=arg_value)
1659 else:
1660 # was passed as a positional argument
1661 new_params.pop(param.name)
1662 continue
1663
1664 if param.kind is _KEYWORD_ONLY:
1665 # Set the new default value
1666 new_params[param_name] = param.replace(default=arg_value)
1667
1668 if transform_to_kwonly:
1669 assert param.kind is not _POSITIONAL_ONLY
1670
1671 if param.kind is _POSITIONAL_OR_KEYWORD:
1672 new_param = new_params[param_name].replace(kind=_KEYWORD_ONLY)
1673 new_params[param_name] = new_param
1674 new_params.move_to_end(param_name)
1675 elif param.kind in (_KEYWORD_ONLY, _VAR_KEYWORD):
1676 new_params.move_to_end(param_name)
1677 elif param.kind is _VAR_POSITIONAL:
1678 new_params.pop(param.name)
Yury Selivanovda5fe4f2014-01-27 17:28:37 -05001679
1680 return wrapped_sig.replace(parameters=new_params.values())
1681
1682
Yury Selivanov62560fb2014-01-28 12:26:24 -05001683def _signature_bound_method(sig):
Yury Selivanov5a23bd02014-03-29 13:47:11 -04001684 """Private helper to transform signatures for unbound
1685 functions to bound methods.
1686 """
Yury Selivanov62560fb2014-01-28 12:26:24 -05001687
1688 params = tuple(sig.parameters.values())
1689
1690 if not params or params[0].kind in (_VAR_KEYWORD, _KEYWORD_ONLY):
1691 raise ValueError('invalid method signature')
1692
1693 kind = params[0].kind
1694 if kind in (_POSITIONAL_OR_KEYWORD, _POSITIONAL_ONLY):
1695 # Drop first parameter:
1696 # '(p1, p2[, ...])' -> '(p2[, ...])'
1697 params = params[1:]
1698 else:
1699 if kind is not _VAR_POSITIONAL:
1700 # Unless we add a new parameter type we never
1701 # get here
1702 raise ValueError('invalid argument type')
1703 # It's a var-positional parameter.
1704 # Do nothing. '(*args[, ...])' -> '(*args[, ...])'
1705
1706 return sig.replace(parameters=params)
1707
1708
Yury Selivanovb77511d2014-01-29 10:46:14 -05001709def _signature_is_builtin(obj):
Yury Selivanov5a23bd02014-03-29 13:47:11 -04001710 """Private helper to test if `obj` is a callable that might
1711 support Argument Clinic's __text_signature__ protocol.
1712 """
Yury Selivanov1d241832014-02-02 12:51:20 -05001713 return (isbuiltin(obj) or
Yury Selivanovb77511d2014-01-29 10:46:14 -05001714 ismethoddescriptor(obj) or
Yury Selivanov1d241832014-02-02 12:51:20 -05001715 isinstance(obj, _NonUserDefinedCallables) or
Yury Selivanovb77511d2014-01-29 10:46:14 -05001716 # Can't test 'isinstance(type)' here, as it would
1717 # also be True for regular python classes
1718 obj in (type, object))
1719
1720
Yury Selivanov63da7c72014-01-31 14:48:37 -05001721def _signature_is_functionlike(obj):
Yury Selivanov5a23bd02014-03-29 13:47:11 -04001722 """Private helper to test if `obj` is a duck type of FunctionType.
1723 A good example of such objects are functions compiled with
1724 Cython, which have all attributes that a pure Python function
1725 would have, but have their code statically compiled.
1726 """
Yury Selivanov63da7c72014-01-31 14:48:37 -05001727
1728 if not callable(obj) or isclass(obj):
1729 # All function-like objects are obviously callables,
1730 # and not classes.
1731 return False
1732
1733 name = getattr(obj, '__name__', None)
1734 code = getattr(obj, '__code__', None)
1735 defaults = getattr(obj, '__defaults__', _void) # Important to use _void ...
1736 kwdefaults = getattr(obj, '__kwdefaults__', _void) # ... and not None here
1737 annotations = getattr(obj, '__annotations__', None)
1738
1739 return (isinstance(code, types.CodeType) and
1740 isinstance(name, str) and
1741 (defaults is None or isinstance(defaults, tuple)) and
1742 (kwdefaults is None or isinstance(kwdefaults, dict)) and
1743 isinstance(annotations, dict))
1744
1745
Yury Selivanovd82eddc2014-01-29 11:24:39 -05001746def _signature_get_bound_param(spec):
Yury Selivanov5a23bd02014-03-29 13:47:11 -04001747 """ Private helper to get first parameter name from a
1748 __text_signature__ of a builtin method, which should
1749 be in the following format: '($param1, ...)'.
1750 Assumptions are that the first argument won't have
1751 a default value or an annotation.
1752 """
Yury Selivanovd82eddc2014-01-29 11:24:39 -05001753
1754 assert spec.startswith('($')
1755
1756 pos = spec.find(',')
1757 if pos == -1:
1758 pos = spec.find(')')
1759
1760 cpos = spec.find(':')
1761 assert cpos == -1 or cpos > pos
1762
1763 cpos = spec.find('=')
1764 assert cpos == -1 or cpos > pos
1765
1766 return spec[2:pos]
1767
1768
Larry Hastings2623c8c2014-02-08 22:15:29 -08001769def _signature_strip_non_python_syntax(signature):
1770 """
Yury Selivanov5a23bd02014-03-29 13:47:11 -04001771 Private helper function. Takes a signature in Argument Clinic's
1772 extended signature format.
1773
Larry Hastings2623c8c2014-02-08 22:15:29 -08001774 Returns a tuple of three things:
1775 * that signature re-rendered in standard Python syntax,
1776 * the index of the "self" parameter (generally 0), or None if
1777 the function does not have a "self" parameter, and
1778 * the index of the last "positional only" parameter,
1779 or None if the signature has no positional-only parameters.
1780 """
1781
1782 if not signature:
1783 return signature, None, None
1784
1785 self_parameter = None
1786 last_positional_only = None
1787
1788 lines = [l.encode('ascii') for l in signature.split('\n')]
1789 generator = iter(lines).__next__
1790 token_stream = tokenize.tokenize(generator)
1791
1792 delayed_comma = False
1793 skip_next_comma = False
1794 text = []
1795 add = text.append
1796
1797 current_parameter = 0
1798 OP = token.OP
1799 ERRORTOKEN = token.ERRORTOKEN
1800
1801 # token stream always starts with ENCODING token, skip it
1802 t = next(token_stream)
1803 assert t.type == tokenize.ENCODING
1804
1805 for t in token_stream:
1806 type, string = t.type, t.string
1807
1808 if type == OP:
1809 if string == ',':
1810 if skip_next_comma:
1811 skip_next_comma = False
1812 else:
1813 assert not delayed_comma
1814 delayed_comma = True
1815 current_parameter += 1
1816 continue
1817
1818 if string == '/':
1819 assert not skip_next_comma
1820 assert last_positional_only is None
1821 skip_next_comma = True
1822 last_positional_only = current_parameter - 1
1823 continue
1824
1825 if (type == ERRORTOKEN) and (string == '$'):
1826 assert self_parameter is None
1827 self_parameter = current_parameter
1828 continue
1829
1830 if delayed_comma:
1831 delayed_comma = False
1832 if not ((type == OP) and (string == ')')):
1833 add(', ')
1834 add(string)
1835 if (string == ','):
1836 add(' ')
1837 clean_signature = ''.join(text)
1838 return clean_signature, self_parameter, last_positional_only
1839
1840
Yury Selivanov57d240e2014-02-19 16:27:23 -05001841def _signature_fromstr(cls, obj, s, skip_bound_arg=True):
Yury Selivanov5a23bd02014-03-29 13:47:11 -04001842 """Private helper to parse content of '__text_signature__'
1843 and return a Signature based on it.
1844 """
1845
Yury Selivanov7d2bfed2014-02-03 02:46:07 -05001846 Parameter = cls._parameter_cls
1847
Larry Hastings2623c8c2014-02-08 22:15:29 -08001848 clean_signature, self_parameter, last_positional_only = \
1849 _signature_strip_non_python_syntax(s)
Yury Selivanov7d2bfed2014-02-03 02:46:07 -05001850
Larry Hastings2623c8c2014-02-08 22:15:29 -08001851 program = "def foo" + clean_signature + ": pass"
Yury Selivanov7d2bfed2014-02-03 02:46:07 -05001852
1853 try:
Larry Hastings2623c8c2014-02-08 22:15:29 -08001854 module = ast.parse(program)
Yury Selivanov7d2bfed2014-02-03 02:46:07 -05001855 except SyntaxError:
1856 module = None
1857
1858 if not isinstance(module, ast.Module):
1859 raise ValueError("{!r} builtin has invalid signature".format(obj))
1860
1861 f = module.body[0]
1862
1863 parameters = []
1864 empty = Parameter.empty
1865 invalid = object()
1866
1867 module = None
1868 module_dict = {}
1869 module_name = getattr(obj, '__module__', None)
1870 if module_name:
1871 module = sys.modules.get(module_name, None)
1872 if module:
1873 module_dict = module.__dict__
1874 sys_module_dict = sys.modules
1875
1876 def parse_name(node):
1877 assert isinstance(node, ast.arg)
1878 if node.annotation != None:
1879 raise ValueError("Annotations are not currently supported")
1880 return node.arg
1881
1882 def wrap_value(s):
1883 try:
1884 value = eval(s, module_dict)
1885 except NameError:
1886 try:
1887 value = eval(s, sys_module_dict)
1888 except NameError:
1889 raise RuntimeError()
1890
1891 if isinstance(value, str):
1892 return ast.Str(value)
1893 if isinstance(value, (int, float)):
1894 return ast.Num(value)
1895 if isinstance(value, bytes):
1896 return ast.Bytes(value)
1897 if value in (True, False, None):
1898 return ast.NameConstant(value)
1899 raise RuntimeError()
1900
1901 class RewriteSymbolics(ast.NodeTransformer):
1902 def visit_Attribute(self, node):
1903 a = []
1904 n = node
1905 while isinstance(n, ast.Attribute):
1906 a.append(n.attr)
1907 n = n.value
1908 if not isinstance(n, ast.Name):
1909 raise RuntimeError()
1910 a.append(n.id)
1911 value = ".".join(reversed(a))
1912 return wrap_value(value)
1913
1914 def visit_Name(self, node):
1915 if not isinstance(node.ctx, ast.Load):
1916 raise ValueError()
1917 return wrap_value(node.id)
1918
1919 def p(name_node, default_node, default=empty):
1920 name = parse_name(name_node)
1921 if name is invalid:
1922 return None
1923 if default_node and default_node is not _empty:
1924 try:
1925 default_node = RewriteSymbolics().visit(default_node)
1926 o = ast.literal_eval(default_node)
1927 except ValueError:
1928 o = invalid
1929 if o is invalid:
1930 return None
1931 default = o if o is not invalid else default
1932 parameters.append(Parameter(name, kind, default=default, annotation=empty))
1933
1934 # non-keyword-only parameters
1935 args = reversed(f.args.args)
1936 defaults = reversed(f.args.defaults)
1937 iter = itertools.zip_longest(args, defaults, fillvalue=None)
Larry Hastings2623c8c2014-02-08 22:15:29 -08001938 if last_positional_only is not None:
1939 kind = Parameter.POSITIONAL_ONLY
1940 else:
1941 kind = Parameter.POSITIONAL_OR_KEYWORD
1942 for i, (name, default) in enumerate(reversed(list(iter))):
Yury Selivanov7d2bfed2014-02-03 02:46:07 -05001943 p(name, default)
Larry Hastings2623c8c2014-02-08 22:15:29 -08001944 if i == last_positional_only:
1945 kind = Parameter.POSITIONAL_OR_KEYWORD
Yury Selivanov7d2bfed2014-02-03 02:46:07 -05001946
1947 # *args
1948 if f.args.vararg:
1949 kind = Parameter.VAR_POSITIONAL
1950 p(f.args.vararg, empty)
1951
1952 # keyword-only arguments
1953 kind = Parameter.KEYWORD_ONLY
1954 for name, default in zip(f.args.kwonlyargs, f.args.kw_defaults):
1955 p(name, default)
1956
1957 # **kwargs
1958 if f.args.kwarg:
1959 kind = Parameter.VAR_KEYWORD
1960 p(f.args.kwarg, empty)
1961
Larry Hastings2623c8c2014-02-08 22:15:29 -08001962 if self_parameter is not None:
Yury Selivanov8c185ee2014-02-21 01:32:42 -05001963 # Possibly strip the bound argument:
1964 # - We *always* strip first bound argument if
1965 # it is a module.
1966 # - We don't strip first bound argument if
1967 # skip_bound_arg is False.
Yury Selivanov7d2bfed2014-02-03 02:46:07 -05001968 assert parameters
Yury Selivanov8c185ee2014-02-21 01:32:42 -05001969 _self = getattr(obj, '__self__', None)
1970 self_isbound = _self is not None
1971 self_ismodule = ismodule(_self)
1972 if self_isbound and (self_ismodule or skip_bound_arg):
Yury Selivanov7d2bfed2014-02-03 02:46:07 -05001973 parameters.pop(0)
1974 else:
1975 # for builtins, self parameter is always positional-only!
1976 p = parameters[0].replace(kind=Parameter.POSITIONAL_ONLY)
1977 parameters[0] = p
1978
1979 return cls(parameters, return_annotation=cls.empty)
1980
1981
Yury Selivanov57d240e2014-02-19 16:27:23 -05001982def _signature_from_builtin(cls, func, skip_bound_arg=True):
Yury Selivanov5a23bd02014-03-29 13:47:11 -04001983 """Private helper function to get signature for
1984 builtin callables.
1985 """
1986
Yury Selivanov57d240e2014-02-19 16:27:23 -05001987 if not _signature_is_builtin(func):
1988 raise TypeError("{!r} is not a Python builtin "
1989 "function".format(func))
1990
1991 s = getattr(func, "__text_signature__", None)
1992 if not s:
1993 raise ValueError("no signature found for builtin {!r}".format(func))
1994
1995 return _signature_fromstr(cls, func, s, skip_bound_arg)
1996
1997
Yury Selivanov5a23bd02014-03-29 13:47:11 -04001998def _signature_from_callable(obj, *,
1999 follow_wrapper_chains=True,
2000 skip_bound_arg=True,
2001 sigcls):
2002
2003 """Private helper function to get signature for arbitrary
2004 callable objects.
2005 """
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002006
2007 if not callable(obj):
2008 raise TypeError('{!r} is not a callable object'.format(obj))
2009
2010 if isinstance(obj, types.MethodType):
2011 # In this case we skip the first parameter of the underlying
2012 # function (usually `self` or `cls`).
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002013 sig = _signature_from_callable(
Yury Selivanovda396452014-03-27 12:09:24 -04002014 obj.__func__,
2015 follow_wrapper_chains=follow_wrapper_chains,
2016 skip_bound_arg=skip_bound_arg,
2017 sigcls=sigcls)
2018
Yury Selivanov57d240e2014-02-19 16:27:23 -05002019 if skip_bound_arg:
2020 return _signature_bound_method(sig)
2021 else:
2022 return sig
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002023
Nick Coghlane8c45d62013-07-28 20:00:01 +10002024 # Was this function wrapped by a decorator?
Yury Selivanov57d240e2014-02-19 16:27:23 -05002025 if follow_wrapper_chains:
2026 obj = unwrap(obj, stop=(lambda f: hasattr(f, "__signature__")))
Nick Coghlane8c45d62013-07-28 20:00:01 +10002027
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002028 try:
2029 sig = obj.__signature__
2030 except AttributeError:
2031 pass
2032 else:
2033 if sig is not None:
Yury Selivanov42407ab2014-06-23 10:23:50 -07002034 if not isinstance(sig, Signature):
2035 raise TypeError(
2036 'unexpected object {!r} in __signature__ '
2037 'attribute'.format(sig))
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002038 return sig
2039
Yury Selivanovda5fe4f2014-01-27 17:28:37 -05002040 try:
2041 partialmethod = obj._partialmethod
2042 except AttributeError:
2043 pass
2044 else:
Yury Selivanov0486f812014-01-29 12:18:59 -05002045 if isinstance(partialmethod, functools.partialmethod):
2046 # Unbound partialmethod (see functools.partialmethod)
2047 # This means, that we need to calculate the signature
2048 # as if it's a regular partial object, but taking into
2049 # account that the first positional argument
2050 # (usually `self`, or `cls`) will not be passed
2051 # automatically (as for boundmethods)
Yury Selivanovda5fe4f2014-01-27 17:28:37 -05002052
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002053 wrapped_sig = _signature_from_callable(
Yury Selivanovda396452014-03-27 12:09:24 -04002054 partialmethod.func,
2055 follow_wrapper_chains=follow_wrapper_chains,
2056 skip_bound_arg=skip_bound_arg,
2057 sigcls=sigcls)
2058
Yury Selivanov0486f812014-01-29 12:18:59 -05002059 sig = _signature_get_partial(wrapped_sig, partialmethod, (None,))
Yury Selivanovda5fe4f2014-01-27 17:28:37 -05002060
Yury Selivanov0486f812014-01-29 12:18:59 -05002061 first_wrapped_param = tuple(wrapped_sig.parameters.values())[0]
2062 new_params = (first_wrapped_param,) + tuple(sig.parameters.values())
Yury Selivanovda5fe4f2014-01-27 17:28:37 -05002063
Yury Selivanov0486f812014-01-29 12:18:59 -05002064 return sig.replace(parameters=new_params)
Yury Selivanovda5fe4f2014-01-27 17:28:37 -05002065
Yury Selivanov63da7c72014-01-31 14:48:37 -05002066 if isfunction(obj) or _signature_is_functionlike(obj):
2067 # If it's a pure Python function, or an object that is duck type
2068 # of a Python function (Cython functions, for instance), then:
Yury Selivanovda396452014-03-27 12:09:24 -04002069 return sigcls.from_function(obj)
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002070
Yury Selivanova773de02014-02-21 18:30:53 -05002071 if _signature_is_builtin(obj):
Yury Selivanovda396452014-03-27 12:09:24 -04002072 return _signature_from_builtin(sigcls, obj,
Yury Selivanova773de02014-02-21 18:30:53 -05002073 skip_bound_arg=skip_bound_arg)
2074
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002075 if isinstance(obj, functools.partial):
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002076 wrapped_sig = _signature_from_callable(
Yury Selivanovda396452014-03-27 12:09:24 -04002077 obj.func,
2078 follow_wrapper_chains=follow_wrapper_chains,
2079 skip_bound_arg=skip_bound_arg,
2080 sigcls=sigcls)
Yury Selivanov62560fb2014-01-28 12:26:24 -05002081 return _signature_get_partial(wrapped_sig, obj)
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002082
2083 sig = None
2084 if isinstance(obj, type):
2085 # obj is a class or a metaclass
2086
2087 # First, let's see if it has an overloaded __call__ defined
2088 # in its metaclass
Yury Selivanov421f0c72014-01-29 12:05:40 -05002089 call = _signature_get_user_defined_method(type(obj), '__call__')
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002090 if call is not None:
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002091 sig = _signature_from_callable(
Yury Selivanovda396452014-03-27 12:09:24 -04002092 call,
2093 follow_wrapper_chains=follow_wrapper_chains,
2094 skip_bound_arg=skip_bound_arg,
2095 sigcls=sigcls)
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002096 else:
2097 # Now we check if the 'obj' class has a '__new__' method
Yury Selivanov421f0c72014-01-29 12:05:40 -05002098 new = _signature_get_user_defined_method(obj, '__new__')
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002099 if new is not None:
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002100 sig = _signature_from_callable(
Yury Selivanovda396452014-03-27 12:09:24 -04002101 new,
2102 follow_wrapper_chains=follow_wrapper_chains,
2103 skip_bound_arg=skip_bound_arg,
2104 sigcls=sigcls)
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002105 else:
2106 # Finally, we should have at least __init__ implemented
Yury Selivanov421f0c72014-01-29 12:05:40 -05002107 init = _signature_get_user_defined_method(obj, '__init__')
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002108 if init is not None:
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002109 sig = _signature_from_callable(
Yury Selivanovda396452014-03-27 12:09:24 -04002110 init,
2111 follow_wrapper_chains=follow_wrapper_chains,
2112 skip_bound_arg=skip_bound_arg,
2113 sigcls=sigcls)
Yury Selivanove7dcc5e2014-01-27 19:29:45 -05002114
2115 if sig is None:
Yury Selivanov7d2bfed2014-02-03 02:46:07 -05002116 # At this point we know, that `obj` is a class, with no user-
2117 # defined '__init__', '__new__', or class-level '__call__'
2118
Larry Hastings2623c8c2014-02-08 22:15:29 -08002119 for base in obj.__mro__[:-1]:
Yury Selivanov7d2bfed2014-02-03 02:46:07 -05002120 # Since '__text_signature__' is implemented as a
2121 # descriptor that extracts text signature from the
2122 # class docstring, if 'obj' is derived from a builtin
2123 # class, its own '__text_signature__' may be 'None'.
Larry Hastings2623c8c2014-02-08 22:15:29 -08002124 # Therefore, we go through the MRO (except the last
2125 # class in there, which is 'object') to find the first
Yury Selivanov7d2bfed2014-02-03 02:46:07 -05002126 # class with non-empty text signature.
2127 try:
2128 text_sig = base.__text_signature__
2129 except AttributeError:
2130 pass
2131 else:
2132 if text_sig:
2133 # If 'obj' class has a __text_signature__ attribute:
2134 # return a signature based on it
Yury Selivanovda396452014-03-27 12:09:24 -04002135 return _signature_fromstr(sigcls, obj, text_sig)
Yury Selivanov7d2bfed2014-02-03 02:46:07 -05002136
2137 # No '__text_signature__' was found for the 'obj' class.
2138 # Last option is to check if its '__init__' is
2139 # object.__init__ or type.__init__.
Larry Hastings2623c8c2014-02-08 22:15:29 -08002140 if type not in obj.__mro__:
Yury Selivanove7dcc5e2014-01-27 19:29:45 -05002141 # We have a class (not metaclass), but no user-defined
2142 # __init__ or __new__ for it
Yury Selivanov7d2bfed2014-02-03 02:46:07 -05002143 if obj.__init__ is object.__init__:
2144 # Return a signature of 'object' builtin.
2145 return signature(object)
Yury Selivanove7dcc5e2014-01-27 19:29:45 -05002146
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002147 elif not isinstance(obj, _NonUserDefinedCallables):
2148 # An object with __call__
2149 # We also check that the 'obj' is not an instance of
2150 # _WrapperDescriptor or _MethodWrapper to avoid
2151 # infinite recursion (and even potential segfault)
Yury Selivanov421f0c72014-01-29 12:05:40 -05002152 call = _signature_get_user_defined_method(type(obj), '__call__')
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002153 if call is not None:
Larry Hastings2623c8c2014-02-08 22:15:29 -08002154 try:
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002155 sig = _signature_from_callable(
Yury Selivanovda396452014-03-27 12:09:24 -04002156 call,
2157 follow_wrapper_chains=follow_wrapper_chains,
2158 skip_bound_arg=skip_bound_arg,
2159 sigcls=sigcls)
Larry Hastings2623c8c2014-02-08 22:15:29 -08002160 except ValueError as ex:
2161 msg = 'no signature found for {!r}'.format(obj)
2162 raise ValueError(msg) from ex
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002163
2164 if sig is not None:
2165 # For classes and objects we skip the first parameter of their
2166 # __call__, __new__, or __init__ methods
Yury Selivanov57d240e2014-02-19 16:27:23 -05002167 if skip_bound_arg:
2168 return _signature_bound_method(sig)
2169 else:
2170 return sig
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002171
2172 if isinstance(obj, types.BuiltinFunctionType):
2173 # Raise a nicer error message for builtins
2174 msg = 'no signature found for builtin function {!r}'.format(obj)
2175 raise ValueError(msg)
2176
2177 raise ValueError('callable {!r} is not supported by signature'.format(obj))
2178
2179
2180class _void:
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002181 """A private marker - used in Parameter & Signature."""
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002182
2183
2184class _empty:
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002185 """Marker object for Signature.empty and Parameter.empty."""
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002186
2187
Yury Selivanov21e83a52014-03-27 11:23:13 -04002188class _ParameterKind(enum.IntEnum):
2189 POSITIONAL_ONLY = 0
2190 POSITIONAL_OR_KEYWORD = 1
2191 VAR_POSITIONAL = 2
2192 KEYWORD_ONLY = 3
2193 VAR_KEYWORD = 4
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002194
2195 def __str__(self):
Yury Selivanov21e83a52014-03-27 11:23:13 -04002196 return self._name_
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002197
2198
Yury Selivanov21e83a52014-03-27 11:23:13 -04002199_POSITIONAL_ONLY = _ParameterKind.POSITIONAL_ONLY
2200_POSITIONAL_OR_KEYWORD = _ParameterKind.POSITIONAL_OR_KEYWORD
2201_VAR_POSITIONAL = _ParameterKind.VAR_POSITIONAL
2202_KEYWORD_ONLY = _ParameterKind.KEYWORD_ONLY
2203_VAR_KEYWORD = _ParameterKind.VAR_KEYWORD
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002204
2205
2206class Parameter:
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002207 """Represents a parameter in a function signature.
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002208
2209 Has the following public attributes:
2210
2211 * name : str
2212 The name of the parameter as a string.
2213 * default : object
2214 The default value for the parameter if specified. If the
Yury Selivanov8757ead2014-01-28 16:39:25 -05002215 parameter has no default value, this attribute is set to
2216 `Parameter.empty`.
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002217 * annotation
2218 The annotation for the parameter if specified. If the
Yury Selivanov8757ead2014-01-28 16:39:25 -05002219 parameter has no annotation, this attribute is set to
2220 `Parameter.empty`.
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002221 * kind : str
2222 Describes how argument values are bound to the parameter.
2223 Possible values: `Parameter.POSITIONAL_ONLY`,
2224 `Parameter.POSITIONAL_OR_KEYWORD`, `Parameter.VAR_POSITIONAL`,
2225 `Parameter.KEYWORD_ONLY`, `Parameter.VAR_KEYWORD`.
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002226 """
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002227
Yury Selivanov3f73ca22014-04-08 11:30:45 -04002228 __slots__ = ('_name', '_kind', '_default', '_annotation')
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002229
2230 POSITIONAL_ONLY = _POSITIONAL_ONLY
2231 POSITIONAL_OR_KEYWORD = _POSITIONAL_OR_KEYWORD
2232 VAR_POSITIONAL = _VAR_POSITIONAL
2233 KEYWORD_ONLY = _KEYWORD_ONLY
2234 VAR_KEYWORD = _VAR_KEYWORD
2235
2236 empty = _empty
2237
Yury Selivanov3f73ca22014-04-08 11:30:45 -04002238 def __init__(self, name, kind, *, default=_empty, annotation=_empty):
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002239
2240 if kind not in (_POSITIONAL_ONLY, _POSITIONAL_OR_KEYWORD,
2241 _VAR_POSITIONAL, _KEYWORD_ONLY, _VAR_KEYWORD):
2242 raise ValueError("invalid value for 'Parameter.kind' attribute")
2243 self._kind = kind
2244
2245 if default is not _empty:
2246 if kind in (_VAR_POSITIONAL, _VAR_KEYWORD):
2247 msg = '{} parameters cannot have default values'.format(kind)
2248 raise ValueError(msg)
2249 self._default = default
2250 self._annotation = annotation
2251
Yury Selivanov2393dca2014-01-27 15:07:58 -05002252 if name is _empty:
2253 raise ValueError('name is a required attribute for Parameter')
2254
2255 if not isinstance(name, str):
2256 raise TypeError("name must be a str, not a {!r}".format(name))
2257
2258 if not name.isidentifier():
2259 raise ValueError('{!r} is not a valid parameter name'.format(name))
2260
2261 self._name = name
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002262
Yury Selivanova5d63dd2014-03-27 11:31:43 -04002263 def __reduce__(self):
2264 return (type(self),
2265 (self._name, self._kind),
Yury Selivanov3f73ca22014-04-08 11:30:45 -04002266 {'_default': self._default,
Yury Selivanova5d63dd2014-03-27 11:31:43 -04002267 '_annotation': self._annotation})
2268
2269 def __setstate__(self, state):
Yury Selivanova5d63dd2014-03-27 11:31:43 -04002270 self._default = state['_default']
2271 self._annotation = state['_annotation']
2272
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002273 @property
2274 def name(self):
2275 return self._name
2276
2277 @property
2278 def default(self):
2279 return self._default
2280
2281 @property
2282 def annotation(self):
2283 return self._annotation
2284
2285 @property
2286 def kind(self):
2287 return self._kind
2288
Yury Selivanov3f73ca22014-04-08 11:30:45 -04002289 def replace(self, *, name=_void, kind=_void,
2290 annotation=_void, default=_void):
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002291 """Creates a customized copy of the Parameter."""
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002292
2293 if name is _void:
2294 name = self._name
2295
2296 if kind is _void:
2297 kind = self._kind
2298
2299 if annotation is _void:
2300 annotation = self._annotation
2301
2302 if default is _void:
2303 default = self._default
2304
Yury Selivanov3f73ca22014-04-08 11:30:45 -04002305 return type(self)(name, kind, default=default, annotation=annotation)
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002306
2307 def __str__(self):
2308 kind = self.kind
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002309 formatted = self._name
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002310
2311 # Add annotation and default value
2312 if self._annotation is not _empty:
2313 formatted = '{}:{}'.format(formatted,
2314 formatannotation(self._annotation))
2315
2316 if self._default is not _empty:
2317 formatted = '{}={}'.format(formatted, repr(self._default))
2318
2319 if kind == _VAR_POSITIONAL:
2320 formatted = '*' + formatted
2321 elif kind == _VAR_KEYWORD:
2322 formatted = '**' + formatted
2323
2324 return formatted
2325
2326 def __repr__(self):
Yury Selivanov374375d2014-03-27 12:41:53 -04002327 return '<{} at {:#x} "{}">'.format(self.__class__.__name__,
2328 id(self), self)
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002329
Yury Selivanov67ae50e2014-04-08 11:46:50 -04002330 def __hash__(self):
Yury Selivanov08d4a4f2014-09-12 15:48:02 -04002331 return hash((self.name, self.kind, self.annotation, self.default))
Yury Selivanov67ae50e2014-04-08 11:46:50 -04002332
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002333 def __eq__(self, other):
2334 return (issubclass(other.__class__, Parameter) and
2335 self._name == other._name and
2336 self._kind == other._kind and
2337 self._default == other._default and
2338 self._annotation == other._annotation)
2339
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002340
2341class BoundArguments:
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002342 """Result of `Signature.bind` call. Holds the mapping of arguments
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002343 to the function's parameters.
2344
2345 Has the following public attributes:
2346
2347 * arguments : OrderedDict
2348 An ordered mutable mapping of parameters' names to arguments' values.
2349 Does not contain arguments' default values.
2350 * signature : Signature
2351 The Signature object that created this instance.
2352 * args : tuple
2353 Tuple of positional arguments values.
2354 * kwargs : dict
2355 Dict of keyword arguments values.
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002356 """
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002357
2358 def __init__(self, signature, arguments):
2359 self.arguments = arguments
2360 self._signature = signature
2361
2362 @property
2363 def signature(self):
2364 return self._signature
2365
2366 @property
2367 def args(self):
2368 args = []
2369 for param_name, param in self._signature.parameters.items():
Yury Selivanov3f73ca22014-04-08 11:30:45 -04002370 if param.kind in (_VAR_KEYWORD, _KEYWORD_ONLY):
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002371 break
2372
2373 try:
2374 arg = self.arguments[param_name]
2375 except KeyError:
2376 # We're done here. Other arguments
2377 # will be mapped in 'BoundArguments.kwargs'
2378 break
2379 else:
2380 if param.kind == _VAR_POSITIONAL:
2381 # *args
2382 args.extend(arg)
2383 else:
2384 # plain argument
2385 args.append(arg)
2386
2387 return tuple(args)
2388
2389 @property
2390 def kwargs(self):
2391 kwargs = {}
2392 kwargs_started = False
2393 for param_name, param in self._signature.parameters.items():
2394 if not kwargs_started:
Yury Selivanov3f73ca22014-04-08 11:30:45 -04002395 if param.kind in (_VAR_KEYWORD, _KEYWORD_ONLY):
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002396 kwargs_started = True
2397 else:
2398 if param_name not in self.arguments:
2399 kwargs_started = True
2400 continue
2401
2402 if not kwargs_started:
2403 continue
2404
2405 try:
2406 arg = self.arguments[param_name]
2407 except KeyError:
2408 pass
2409 else:
2410 if param.kind == _VAR_KEYWORD:
2411 # **kwargs
2412 kwargs.update(arg)
2413 else:
2414 # plain keyword argument
2415 kwargs[param_name] = arg
2416
2417 return kwargs
2418
2419 def __eq__(self, other):
2420 return (issubclass(other.__class__, BoundArguments) and
2421 self.signature == other.signature and
2422 self.arguments == other.arguments)
2423
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002424
2425class Signature:
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002426 """A Signature object represents the overall signature of a function.
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002427 It stores a Parameter object for each parameter accepted by the
2428 function, as well as information specific to the function itself.
2429
2430 A Signature object has the following public attributes and methods:
2431
2432 * parameters : OrderedDict
2433 An ordered mapping of parameters' names to the corresponding
2434 Parameter objects (keyword-only arguments are in the same order
2435 as listed in `code.co_varnames`).
2436 * return_annotation : object
2437 The annotation for the return type of the function if specified.
2438 If the function has no annotation for its return type, this
Yury Selivanov8757ead2014-01-28 16:39:25 -05002439 attribute is set to `Signature.empty`.
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002440 * bind(*args, **kwargs) -> BoundArguments
2441 Creates a mapping from positional and keyword arguments to
2442 parameters.
2443 * bind_partial(*args, **kwargs) -> BoundArguments
2444 Creates a partial mapping from positional and keyword arguments
2445 to parameters (simulating 'functools.partial' behavior.)
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002446 """
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002447
2448 __slots__ = ('_return_annotation', '_parameters')
2449
2450 _parameter_cls = Parameter
2451 _bound_arguments_cls = BoundArguments
2452
2453 empty = _empty
2454
2455 def __init__(self, parameters=None, *, return_annotation=_empty,
2456 __validate_parameters__=True):
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002457 """Constructs Signature from the given list of Parameter
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002458 objects and 'return_annotation'. All arguments are optional.
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002459 """
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002460
2461 if parameters is None:
2462 params = OrderedDict()
2463 else:
2464 if __validate_parameters__:
2465 params = OrderedDict()
2466 top_kind = _POSITIONAL_ONLY
Yury Selivanov07a9e452014-01-29 10:58:16 -05002467 kind_defaults = False
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002468
2469 for idx, param in enumerate(parameters):
2470 kind = param.kind
Yury Selivanov2393dca2014-01-27 15:07:58 -05002471 name = param.name
2472
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002473 if kind < top_kind:
Yury Selivanov3f73ca22014-04-08 11:30:45 -04002474 msg = 'wrong parameter order: {!r} before {!r}'
Yury Selivanov2393dca2014-01-27 15:07:58 -05002475 msg = msg.format(top_kind, kind)
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002476 raise ValueError(msg)
Yury Selivanov07a9e452014-01-29 10:58:16 -05002477 elif kind > top_kind:
2478 kind_defaults = False
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002479 top_kind = kind
2480
Yury Selivanov3f73ca22014-04-08 11:30:45 -04002481 if kind in (_POSITIONAL_ONLY, _POSITIONAL_OR_KEYWORD):
Yury Selivanov07a9e452014-01-29 10:58:16 -05002482 if param.default is _empty:
2483 if kind_defaults:
2484 # No default for this parameter, but the
2485 # previous parameter of the same kind had
2486 # a default
2487 msg = 'non-default argument follows default ' \
2488 'argument'
2489 raise ValueError(msg)
2490 else:
2491 # There is a default for this parameter.
2492 kind_defaults = True
2493
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002494 if name in params:
2495 msg = 'duplicate parameter name: {!r}'.format(name)
2496 raise ValueError(msg)
Yury Selivanov2393dca2014-01-27 15:07:58 -05002497
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002498 params[name] = param
2499 else:
2500 params = OrderedDict(((param.name, param)
2501 for param in parameters))
2502
2503 self._parameters = types.MappingProxyType(params)
2504 self._return_annotation = return_annotation
2505
2506 @classmethod
2507 def from_function(cls, func):
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002508 """Constructs Signature for the given python function."""
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002509
Yury Selivanov5334bcd2014-01-31 15:21:51 -05002510 is_duck_function = False
2511 if not isfunction(func):
2512 if _signature_is_functionlike(func):
2513 is_duck_function = True
2514 else:
2515 # If it's not a pure Python function, and not a duck type
2516 # of pure function:
2517 raise TypeError('{!r} is not a Python function'.format(func))
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002518
2519 Parameter = cls._parameter_cls
2520
2521 # Parameter information.
2522 func_code = func.__code__
2523 pos_count = func_code.co_argcount
2524 arg_names = func_code.co_varnames
2525 positional = tuple(arg_names[:pos_count])
2526 keyword_only_count = func_code.co_kwonlyargcount
2527 keyword_only = arg_names[pos_count:(pos_count + keyword_only_count)]
2528 annotations = func.__annotations__
2529 defaults = func.__defaults__
2530 kwdefaults = func.__kwdefaults__
2531
2532 if defaults:
2533 pos_default_count = len(defaults)
2534 else:
2535 pos_default_count = 0
2536
2537 parameters = []
2538
2539 # Non-keyword-only parameters w/o defaults.
2540 non_default_count = pos_count - pos_default_count
2541 for name in positional[:non_default_count]:
2542 annotation = annotations.get(name, _empty)
2543 parameters.append(Parameter(name, annotation=annotation,
2544 kind=_POSITIONAL_OR_KEYWORD))
2545
2546 # ... w/ defaults.
2547 for offset, name in enumerate(positional[non_default_count:]):
2548 annotation = annotations.get(name, _empty)
2549 parameters.append(Parameter(name, annotation=annotation,
2550 kind=_POSITIONAL_OR_KEYWORD,
2551 default=defaults[offset]))
2552
2553 # *args
Yury Selivanov89ca85c2014-01-29 16:50:40 -05002554 if func_code.co_flags & CO_VARARGS:
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002555 name = arg_names[pos_count + keyword_only_count]
2556 annotation = annotations.get(name, _empty)
2557 parameters.append(Parameter(name, annotation=annotation,
2558 kind=_VAR_POSITIONAL))
2559
2560 # Keyword-only parameters.
2561 for name in keyword_only:
2562 default = _empty
2563 if kwdefaults is not None:
2564 default = kwdefaults.get(name, _empty)
2565
2566 annotation = annotations.get(name, _empty)
2567 parameters.append(Parameter(name, annotation=annotation,
2568 kind=_KEYWORD_ONLY,
2569 default=default))
2570 # **kwargs
Yury Selivanov89ca85c2014-01-29 16:50:40 -05002571 if func_code.co_flags & CO_VARKEYWORDS:
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002572 index = pos_count + keyword_only_count
Yury Selivanov89ca85c2014-01-29 16:50:40 -05002573 if func_code.co_flags & CO_VARARGS:
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002574 index += 1
2575
2576 name = arg_names[index]
2577 annotation = annotations.get(name, _empty)
2578 parameters.append(Parameter(name, annotation=annotation,
2579 kind=_VAR_KEYWORD))
2580
Yury Selivanov5334bcd2014-01-31 15:21:51 -05002581 # Is 'func' is a pure Python function - don't validate the
2582 # parameters list (for correct order and defaults), it should be OK.
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002583 return cls(parameters,
2584 return_annotation=annotations.get('return', _empty),
Yury Selivanov5334bcd2014-01-31 15:21:51 -05002585 __validate_parameters__=is_duck_function)
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002586
Larry Hastings44e2eaa2013-11-23 15:37:55 -08002587 @classmethod
2588 def from_builtin(cls, func):
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002589 """Constructs Signature for the given builtin function."""
Yury Selivanov57d240e2014-02-19 16:27:23 -05002590 return _signature_from_builtin(cls, func)
Larry Hastings44e2eaa2013-11-23 15:37:55 -08002591
Yury Selivanovda396452014-03-27 12:09:24 -04002592 @classmethod
2593 def from_callable(cls, obj):
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002594 """Constructs Signature for the given callable object."""
2595 return _signature_from_callable(obj, sigcls=cls)
Yury Selivanovda396452014-03-27 12:09:24 -04002596
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002597 @property
2598 def parameters(self):
2599 return self._parameters
2600
2601 @property
2602 def return_annotation(self):
2603 return self._return_annotation
2604
2605 def replace(self, *, parameters=_void, return_annotation=_void):
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002606 """Creates a customized copy of the Signature.
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002607 Pass 'parameters' and/or 'return_annotation' arguments
2608 to override them in the new copy.
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002609 """
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002610
2611 if parameters is _void:
2612 parameters = self.parameters.values()
2613
2614 if return_annotation is _void:
2615 return_annotation = self._return_annotation
2616
2617 return type(self)(parameters,
2618 return_annotation=return_annotation)
2619
Yury Selivanov08d4a4f2014-09-12 15:48:02 -04002620 def _hash_basis(self):
2621 params = tuple(param for param in self.parameters.values()
2622 if param.kind != _KEYWORD_ONLY)
2623
2624 kwo_params = {param.name: param for param in self.parameters.values()
2625 if param.kind == _KEYWORD_ONLY}
2626
2627 return params, kwo_params, self.return_annotation
2628
Yury Selivanov67ae50e2014-04-08 11:46:50 -04002629 def __hash__(self):
Yury Selivanov08d4a4f2014-09-12 15:48:02 -04002630 params, kwo_params, return_annotation = self._hash_basis()
2631 kwo_params = frozenset(kwo_params.values())
2632 return hash((params, kwo_params, return_annotation))
Yury Selivanov67ae50e2014-04-08 11:46:50 -04002633
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002634 def __eq__(self, other):
Yury Selivanov08d4a4f2014-09-12 15:48:02 -04002635 return (isinstance(other, Signature) and
2636 self._hash_basis() == other._hash_basis())
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002637
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002638 def _bind(self, args, kwargs, *, partial=False):
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002639 """Private method. Don't use directly."""
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002640
2641 arguments = OrderedDict()
2642
2643 parameters = iter(self.parameters.values())
2644 parameters_ex = ()
2645 arg_vals = iter(args)
2646
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002647 while True:
2648 # Let's iterate through the positional arguments and corresponding
2649 # parameters
2650 try:
2651 arg_val = next(arg_vals)
2652 except StopIteration:
2653 # No more positional arguments
2654 try:
2655 param = next(parameters)
2656 except StopIteration:
2657 # No more parameters. That's it. Just need to check that
2658 # we have no `kwargs` after this while loop
2659 break
2660 else:
2661 if param.kind == _VAR_POSITIONAL:
2662 # That's OK, just empty *args. Let's start parsing
2663 # kwargs
2664 break
2665 elif param.name in kwargs:
2666 if param.kind == _POSITIONAL_ONLY:
2667 msg = '{arg!r} parameter is positional only, ' \
2668 'but was passed as a keyword'
2669 msg = msg.format(arg=param.name)
2670 raise TypeError(msg) from None
2671 parameters_ex = (param,)
2672 break
2673 elif (param.kind == _VAR_KEYWORD or
2674 param.default is not _empty):
2675 # That's fine too - we have a default value for this
2676 # parameter. So, lets start parsing `kwargs`, starting
2677 # with the current parameter
2678 parameters_ex = (param,)
2679 break
2680 else:
Yury Selivanov38b0d5a2014-01-28 17:27:39 -05002681 # No default, not VAR_KEYWORD, not VAR_POSITIONAL,
2682 # not in `kwargs`
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002683 if partial:
2684 parameters_ex = (param,)
2685 break
2686 else:
2687 msg = '{arg!r} parameter lacking default value'
2688 msg = msg.format(arg=param.name)
2689 raise TypeError(msg) from None
2690 else:
2691 # We have a positional argument to process
2692 try:
2693 param = next(parameters)
2694 except StopIteration:
2695 raise TypeError('too many positional arguments') from None
2696 else:
2697 if param.kind in (_VAR_KEYWORD, _KEYWORD_ONLY):
2698 # Looks like we have no parameter for this positional
2699 # argument
2700 raise TypeError('too many positional arguments')
2701
2702 if param.kind == _VAR_POSITIONAL:
2703 # We have an '*args'-like argument, let's fill it with
2704 # all positional arguments we have left and move on to
2705 # the next phase
2706 values = [arg_val]
2707 values.extend(arg_vals)
2708 arguments[param.name] = tuple(values)
2709 break
2710
2711 if param.name in kwargs:
2712 raise TypeError('multiple values for argument '
2713 '{arg!r}'.format(arg=param.name))
2714
2715 arguments[param.name] = arg_val
2716
2717 # Now, we iterate through the remaining parameters to process
2718 # keyword arguments
2719 kwargs_param = None
2720 for param in itertools.chain(parameters_ex, parameters):
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002721 if param.kind == _VAR_KEYWORD:
2722 # Memorize that we have a '**kwargs'-like parameter
2723 kwargs_param = param
2724 continue
2725
Yury Selivanov38b0d5a2014-01-28 17:27:39 -05002726 if param.kind == _VAR_POSITIONAL:
2727 # Named arguments don't refer to '*args'-like parameters.
2728 # We only arrive here if the positional arguments ended
2729 # before reaching the last parameter before *args.
2730 continue
2731
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002732 param_name = param.name
2733 try:
2734 arg_val = kwargs.pop(param_name)
2735 except KeyError:
2736 # We have no value for this parameter. It's fine though,
2737 # if it has a default value, or it is an '*args'-like
2738 # parameter, left alone by the processing of positional
2739 # arguments.
2740 if (not partial and param.kind != _VAR_POSITIONAL and
2741 param.default is _empty):
2742 raise TypeError('{arg!r} parameter lacking default value'. \
2743 format(arg=param_name)) from None
2744
2745 else:
Yury Selivanov9b9ac952014-01-28 20:54:28 -05002746 if param.kind == _POSITIONAL_ONLY:
2747 # This should never happen in case of a properly built
2748 # Signature object (but let's have this check here
2749 # to ensure correct behaviour just in case)
2750 raise TypeError('{arg!r} parameter is positional only, '
2751 'but was passed as a keyword'. \
2752 format(arg=param.name))
2753
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002754 arguments[param_name] = arg_val
2755
2756 if kwargs:
2757 if kwargs_param is not None:
2758 # Process our '**kwargs'-like parameter
2759 arguments[kwargs_param.name] = kwargs
2760 else:
2761 raise TypeError('too many keyword arguments')
2762
2763 return self._bound_arguments_cls(self, arguments)
2764
Yury Selivanovc45873e2014-01-29 12:10:27 -05002765 def bind(*args, **kwargs):
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002766 """Get a BoundArguments object, that maps the passed `args`
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002767 and `kwargs` to the function's signature. Raises `TypeError`
2768 if the passed arguments can not be bound.
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002769 """
Yury Selivanovc45873e2014-01-29 12:10:27 -05002770 return args[0]._bind(args[1:], kwargs)
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002771
Yury Selivanovc45873e2014-01-29 12:10:27 -05002772 def bind_partial(*args, **kwargs):
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002773 """Get a BoundArguments object, that partially maps the
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002774 passed `args` and `kwargs` to the function's signature.
2775 Raises `TypeError` if the passed arguments can not be bound.
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002776 """
Yury Selivanovc45873e2014-01-29 12:10:27 -05002777 return args[0]._bind(args[1:], kwargs, partial=True)
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002778
Yury Selivanova5d63dd2014-03-27 11:31:43 -04002779 def __reduce__(self):
2780 return (type(self),
2781 (tuple(self._parameters.values()),),
2782 {'_return_annotation': self._return_annotation})
2783
2784 def __setstate__(self, state):
2785 self._return_annotation = state['_return_annotation']
2786
Yury Selivanov374375d2014-03-27 12:41:53 -04002787 def __repr__(self):
2788 return '<{} at {:#x} "{}">'.format(self.__class__.__name__,
2789 id(self), self)
2790
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002791 def __str__(self):
2792 result = []
Yury Selivanov2393dca2014-01-27 15:07:58 -05002793 render_pos_only_separator = False
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002794 render_kw_only_separator = True
Yury Selivanov2393dca2014-01-27 15:07:58 -05002795 for param in self.parameters.values():
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002796 formatted = str(param)
2797
2798 kind = param.kind
Yury Selivanov2393dca2014-01-27 15:07:58 -05002799
2800 if kind == _POSITIONAL_ONLY:
2801 render_pos_only_separator = True
2802 elif render_pos_only_separator:
2803 # It's not a positional-only parameter, and the flag
2804 # is set to 'True' (there were pos-only params before.)
2805 result.append('/')
2806 render_pos_only_separator = False
2807
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002808 if kind == _VAR_POSITIONAL:
2809 # OK, we have an '*args'-like parameter, so we won't need
2810 # a '*' to separate keyword-only arguments
2811 render_kw_only_separator = False
2812 elif kind == _KEYWORD_ONLY and render_kw_only_separator:
2813 # We have a keyword-only parameter to render and we haven't
2814 # rendered an '*args'-like parameter before, so add a '*'
2815 # separator to the parameters list ("foo(arg1, *, arg2)" case)
2816 result.append('*')
2817 # This condition should be only triggered once, so
2818 # reset the flag
2819 render_kw_only_separator = False
2820
2821 result.append(formatted)
2822
Yury Selivanov2393dca2014-01-27 15:07:58 -05002823 if render_pos_only_separator:
2824 # There were only positional-only parameters, hence the
2825 # flag was not reset to 'False'
2826 result.append('/')
2827
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002828 rendered = '({})'.format(', '.join(result))
2829
2830 if self.return_annotation is not _empty:
2831 anno = formatannotation(self.return_annotation)
2832 rendered += ' -> {}'.format(anno)
2833
2834 return rendered
Nick Coghlanf94a16b2013-09-22 22:46:49 +10002835
Yury Selivanovda396452014-03-27 12:09:24 -04002836
2837def signature(obj):
Yury Selivanov5a23bd02014-03-29 13:47:11 -04002838 """Get a signature object for the passed callable."""
Yury Selivanovda396452014-03-27 12:09:24 -04002839 return Signature.from_callable(obj)
2840
2841
Nick Coghlanf94a16b2013-09-22 22:46:49 +10002842def _main():
2843 """ Logic for inspecting an object given at command line """
2844 import argparse
2845 import importlib
2846
2847 parser = argparse.ArgumentParser()
2848 parser.add_argument(
2849 'object',
2850 help="The object to be analysed. "
2851 "It supports the 'module:qualname' syntax")
2852 parser.add_argument(
2853 '-d', '--details', action='store_true',
2854 help='Display info about the module rather than its source code')
2855
2856 args = parser.parse_args()
2857
2858 target = args.object
2859 mod_name, has_attrs, attrs = target.partition(":")
2860 try:
2861 obj = module = importlib.import_module(mod_name)
2862 except Exception as exc:
2863 msg = "Failed to import {} ({}: {})".format(mod_name,
2864 type(exc).__name__,
2865 exc)
2866 print(msg, file=sys.stderr)
2867 exit(2)
2868
2869 if has_attrs:
2870 parts = attrs.split(".")
2871 obj = module
2872 for part in parts:
2873 obj = getattr(obj, part)
2874
2875 if module.__name__ in sys.builtin_module_names:
2876 print("Can't get info for builtin modules.", file=sys.stderr)
2877 exit(1)
2878
2879 if args.details:
2880 print('Target: {}'.format(target))
2881 print('Origin: {}'.format(getsourcefile(module)))
2882 print('Cached: {}'.format(module.__cached__))
2883 if obj is module:
2884 print('Loader: {}'.format(repr(module.__loader__)))
2885 if hasattr(module, '__path__'):
2886 print('Submodule search path: {}'.format(module.__path__))
2887 else:
2888 try:
2889 __, lineno = findsource(obj)
2890 except Exception:
2891 pass
2892 else:
2893 print('Line: {}'.format(lineno))
2894
2895 print('\n')
2896 else:
2897 print(getsource(obj))
2898
2899
2900if __name__ == "__main__":
2901 _main()