blob: 51b771760f74231e8cfc2ac482faeed8048b211c [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
Guido van Rossum2e65f892007-02-28 22:03:49 +000020 getfullargspec() - same, with support for Python-3000 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
Brett Cannoncb66eb02012-05-11 12:58:42 -040034import importlib.machinery
35import itertools
Christian Heimes7131fd92008-02-19 14:21:46 +000036import linecache
Brett Cannoncb66eb02012-05-11 12:58:42 -040037import os
38import re
39import sys
40import tokenize
41import types
Brett Cannon2b88fcf2012-06-02 22:28:42 -040042import warnings
Larry Hastings7c7cbfc2012-06-22 15:19:35 -070043import functools
Nick Coghlan2f92e542012-06-23 19:39:55 +100044import builtins
Raymond Hettingera1a992c2005-03-11 06:46:45 +000045from operator import attrgetter
Larry Hastings7c7cbfc2012-06-22 15:19:35 -070046from collections import namedtuple, OrderedDict
Nick Coghlan09c81232010-08-17 10:18:16 +000047
48# Create constants for the compiler flags in Include/code.h
49# We try to get them from dis to avoid duplication, but fall
Ezio Melotti30b9d5d2013-08-17 15:50:46 +030050# back to hardcoding so the dependency is optional
Nick Coghlan09c81232010-08-17 10:18:16 +000051try:
52 from dis import COMPILER_FLAG_NAMES as _flag_names
Brett Cannoncd171c82013-07-04 17:43:24 -040053except ImportError:
Nick Coghlan09c81232010-08-17 10:18:16 +000054 CO_OPTIMIZED, CO_NEWLOCALS = 0x1, 0x2
55 CO_VARARGS, CO_VARKEYWORDS = 0x4, 0x8
56 CO_NESTED, CO_GENERATOR, CO_NOFREE = 0x10, 0x20, 0x40
57else:
58 mod_dict = globals()
59 for k, v in _flag_names.items():
60 mod_dict["CO_" + v] = k
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +000061
Christian Heimesbe5b30b2008-03-03 19:18:51 +000062# See Include/object.h
63TPFLAGS_IS_ABSTRACT = 1 << 20
64
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +000065# ----------------------------------------------------------- type-checking
66def ismodule(object):
67 """Return true if the object is a module.
68
69 Module objects provide these attributes:
Barry Warsaw28a691b2010-04-17 00:19:56 +000070 __cached__ pathname to byte compiled file
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +000071 __doc__ documentation string
72 __file__ filename (missing for built-in modules)"""
Tim Peters28bc59f2001-09-16 08:40:16 +000073 return isinstance(object, types.ModuleType)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +000074
75def isclass(object):
76 """Return true if the object is a class.
77
78 Class objects provide these attributes:
79 __doc__ documentation string
80 __module__ name of module in which this class was defined"""
Benjamin Petersonc4656002009-01-17 22:41:18 +000081 return isinstance(object, type)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +000082
83def ismethod(object):
84 """Return true if the object is an instance method.
85
86 Instance method objects provide these attributes:
87 __doc__ documentation string
88 __name__ name with which this method was defined
Christian Heimesff737952007-11-27 10:40:20 +000089 __func__ function object containing implementation of method
90 __self__ instance to which this method is bound"""
Tim Peters28bc59f2001-09-16 08:40:16 +000091 return isinstance(object, types.MethodType)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +000092
Tim Peters536d2262001-09-20 05:13:38 +000093def ismethoddescriptor(object):
Tim Petersf1d90b92001-09-20 05:47:55 +000094 """Return true if the object is a method descriptor.
95
96 But not if ismethod() or isclass() or isfunction() are true.
Tim Peters536d2262001-09-20 05:13:38 +000097
98 This is new in Python 2.2, and, for example, is true of int.__add__.
99 An object passing this test has a __get__ attribute but not a __set__
100 attribute, but beyond that the set of attributes varies. __name__ is
101 usually sensible, and __doc__ often is.
102
Tim Petersf1d90b92001-09-20 05:47:55 +0000103 Methods implemented via descriptors that also pass one of the other
104 tests return false from the ismethoddescriptor() test, simply because
105 the other tests promise more -- you can, e.g., count on having the
Christian Heimesff737952007-11-27 10:40:20 +0000106 __func__ attribute (etc) when an object passes ismethod()."""
Antoine Pitrou86a8a9a2011-12-21 09:57:40 +0100107 if isclass(object) or ismethod(object) or isfunction(object):
108 # mutual exclusion
109 return False
110 tp = type(object)
111 return hasattr(tp, "__get__") and not hasattr(tp, "__set__")
Tim Peters536d2262001-09-20 05:13:38 +0000112
Martin v. Löwise59e2ba2003-05-03 09:09:02 +0000113def isdatadescriptor(object):
114 """Return true if the object is a data descriptor.
115
116 Data descriptors have both a __get__ and a __set__ attribute. Examples are
117 properties (defined in Python) and getsets and members (defined in C).
118 Typically, data descriptors will also have __name__ and __doc__ attributes
119 (properties, getsets, and members have both of these attributes), but this
120 is not guaranteed."""
Antoine Pitrou86a8a9a2011-12-21 09:57:40 +0100121 if isclass(object) or ismethod(object) or isfunction(object):
122 # mutual exclusion
123 return False
124 tp = type(object)
125 return hasattr(tp, "__set__") and hasattr(tp, "__get__")
Martin v. Löwise59e2ba2003-05-03 09:09:02 +0000126
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000127if hasattr(types, 'MemberDescriptorType'):
128 # CPython and equivalent
129 def ismemberdescriptor(object):
130 """Return true if the object is a member descriptor.
131
132 Member descriptors are specialized descriptors defined in extension
133 modules."""
134 return isinstance(object, types.MemberDescriptorType)
135else:
136 # Other implementations
137 def ismemberdescriptor(object):
138 """Return true if the object is a member descriptor.
139
140 Member descriptors are specialized descriptors defined in extension
141 modules."""
142 return False
143
144if hasattr(types, 'GetSetDescriptorType'):
145 # CPython and equivalent
146 def isgetsetdescriptor(object):
147 """Return true if the object is a getset descriptor.
148
149 getset descriptors are specialized descriptors defined in extension
150 modules."""
151 return isinstance(object, types.GetSetDescriptorType)
152else:
153 # Other implementations
154 def isgetsetdescriptor(object):
155 """Return true if the object is a getset descriptor.
156
157 getset descriptors are specialized descriptors defined in extension
158 modules."""
159 return False
160
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000161def isfunction(object):
162 """Return true if the object is a user-defined function.
163
164 Function objects provide these attributes:
165 __doc__ documentation string
166 __name__ name with which this function was defined
Neal Norwitz221085d2007-02-25 20:55:47 +0000167 __code__ code object containing compiled function bytecode
168 __defaults__ tuple of any default values for arguments
169 __globals__ global namespace in which this function was defined
170 __annotations__ dict of parameter annotations
171 __kwdefaults__ dict of keyword only parameters with defaults"""
Tim Peters28bc59f2001-09-16 08:40:16 +0000172 return isinstance(object, types.FunctionType)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000173
Christian Heimes7131fd92008-02-19 14:21:46 +0000174def isgeneratorfunction(object):
175 """Return true if the object is a user-defined generator function.
176
177 Generator function objects provides same attributes as functions.
178
Alexander Belopolsky977a6842010-08-16 20:17:07 +0000179 See help(isfunction) for attributes listing."""
Georg Brandlb1441c72009-01-03 22:33:39 +0000180 return bool((isfunction(object) or ismethod(object)) and
181 object.__code__.co_flags & CO_GENERATOR)
Christian Heimes7131fd92008-02-19 14:21:46 +0000182
183def isgenerator(object):
184 """Return true if the object is a generator.
185
186 Generator objects provide these attributes:
Ezio Melotti30b9d5d2013-08-17 15:50:46 +0300187 __iter__ defined to support iteration over container
Christian Heimes7131fd92008-02-19 14:21:46 +0000188 close raises a new GeneratorExit exception inside the
189 generator to terminate the iteration
190 gi_code code object
191 gi_frame frame object or possibly None once the generator has
192 been exhausted
193 gi_running set to 1 when generator is executing, 0 otherwise
194 next return the next item from the container
195 send resumes the generator and "sends" a value that becomes
196 the result of the current yield-expression
197 throw used to raise an exception inside the generator"""
198 return isinstance(object, types.GeneratorType)
199
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000200def istraceback(object):
201 """Return true if the object is a traceback.
202
203 Traceback objects provide these attributes:
204 tb_frame frame object at this level
205 tb_lasti index of last attempted instruction in bytecode
206 tb_lineno current line number in Python source code
207 tb_next next inner traceback object (called by this level)"""
Tim Peters28bc59f2001-09-16 08:40:16 +0000208 return isinstance(object, types.TracebackType)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000209
210def isframe(object):
211 """Return true if the object is a frame object.
212
213 Frame objects provide these attributes:
214 f_back next outer frame object (this frame's caller)
215 f_builtins built-in namespace seen by this frame
216 f_code code object being executed in this frame
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000217 f_globals global namespace seen by this frame
218 f_lasti index of last attempted instruction in bytecode
219 f_lineno current line number in Python source code
220 f_locals local namespace seen by this frame
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000221 f_trace tracing function for this frame, or None"""
Tim Peters28bc59f2001-09-16 08:40:16 +0000222 return isinstance(object, types.FrameType)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000223
224def iscode(object):
225 """Return true if the object is a code object.
226
227 Code objects provide these attributes:
228 co_argcount number of arguments (not including * or ** args)
229 co_code string of raw compiled bytecode
230 co_consts tuple of constants used in the bytecode
231 co_filename name of file in which this code object was created
232 co_firstlineno number of first line in Python source code
233 co_flags bitmap: 1=optimized | 2=newlocals | 4=*arg | 8=**arg
234 co_lnotab encoded mapping of line numbers to bytecode indices
235 co_name name with which this code object was defined
236 co_names tuple of names of local variables
237 co_nlocals number of local variables
238 co_stacksize virtual machine stack space required
239 co_varnames tuple of names of arguments and local variables"""
Tim Peters28bc59f2001-09-16 08:40:16 +0000240 return isinstance(object, types.CodeType)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000241
242def isbuiltin(object):
243 """Return true if the object is a built-in function or method.
244
245 Built-in functions and methods provide these attributes:
246 __doc__ documentation string
247 __name__ original name of this function or method
248 __self__ instance to which a method is bound, or None"""
Tim Peters28bc59f2001-09-16 08:40:16 +0000249 return isinstance(object, types.BuiltinFunctionType)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000250
251def isroutine(object):
252 """Return true if the object is any kind of function or method."""
Tim Peters536d2262001-09-20 05:13:38 +0000253 return (isbuiltin(object)
254 or isfunction(object)
255 or ismethod(object)
256 or ismethoddescriptor(object))
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000257
Christian Heimesbe5b30b2008-03-03 19:18:51 +0000258def isabstract(object):
259 """Return true if the object is an abstract base class (ABC)."""
Benjamin Petersona0dfa822009-11-13 02:25:08 +0000260 return bool(isinstance(object, type) and object.__flags__ & TPFLAGS_IS_ABSTRACT)
Christian Heimesbe5b30b2008-03-03 19:18:51 +0000261
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000262def getmembers(object, predicate=None):
263 """Return all members of an object as (name, value) pairs sorted by name.
264 Optionally, only return members that satisfy a given predicate."""
Antoine Pitrou86a8a9a2011-12-21 09:57:40 +0100265 if isclass(object):
266 mro = (object,) + getmro(object)
267 else:
268 mro = ()
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000269 results = []
270 for key in dir(object):
Antoine Pitrou86a8a9a2011-12-21 09:57:40 +0100271 # First try to get the value via __dict__. Some descriptors don't
272 # like calling their __get__ (see bug #1785).
273 for base in mro:
274 if key in base.__dict__:
275 value = base.__dict__[key]
276 break
277 else:
278 try:
279 value = getattr(object, key)
280 except AttributeError:
281 continue
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000282 if not predicate or predicate(value):
283 results.append((key, value))
284 results.sort()
285 return results
286
Christian Heimes25bb7832008-01-11 16:17:00 +0000287Attribute = namedtuple('Attribute', 'name kind defining_class object')
288
Tim Peters13b49d32001-09-23 02:00:29 +0000289def classify_class_attrs(cls):
290 """Return list of attribute-descriptor tuples.
291
292 For each name in dir(cls), the return list contains a 4-tuple
293 with these elements:
294
295 0. The name (a string).
296
297 1. The kind of attribute this is, one of these strings:
298 'class method' created via classmethod()
299 'static method' created via staticmethod()
300 'property' created via property()
301 'method' any other flavor of method
302 'data' not a method
303
304 2. The class which defined this attribute (a class).
305
306 3. The object as obtained directly from the defining class's
307 __dict__, not via getattr. This is especially important for
308 data attributes: C.data is just a data object, but
309 C.__dict__['data'] may be a data descriptor with additional
310 info, like a __doc__ string.
311 """
312
313 mro = getmro(cls)
314 names = dir(cls)
315 result = []
316 for name in names:
Antoine Pitrou86a8a9a2011-12-21 09:57:40 +0100317 # Get the object associated with the name, and where it was defined.
Tim Peters13b49d32001-09-23 02:00:29 +0000318 # Getting an obj from the __dict__ sometimes reveals more than
319 # using getattr. Static and class methods are dramatic examples.
Antoine Pitrou86a8a9a2011-12-21 09:57:40 +0100320 # Furthermore, some objects may raise an Exception when fetched with
321 # getattr(). This is the case with some descriptors (bug #1785).
322 # Thus, we only use getattr() as a last resort.
323 homecls = None
324 for base in (cls,) + mro:
325 if name in base.__dict__:
326 obj = base.__dict__[name]
327 homecls = base
328 break
Tim Peters13b49d32001-09-23 02:00:29 +0000329 else:
330 obj = getattr(cls, name)
Antoine Pitrou86a8a9a2011-12-21 09:57:40 +0100331 homecls = getattr(obj, "__objclass__", homecls)
Tim Peters13b49d32001-09-23 02:00:29 +0000332
333 # Classify the object.
334 if isinstance(obj, staticmethod):
335 kind = "static method"
336 elif isinstance(obj, classmethod):
337 kind = "class method"
338 elif isinstance(obj, property):
339 kind = "property"
Antoine Pitrou86a8a9a2011-12-21 09:57:40 +0100340 elif ismethoddescriptor(obj):
Tim Peters13b49d32001-09-23 02:00:29 +0000341 kind = "method"
Antoine Pitrou86a8a9a2011-12-21 09:57:40 +0100342 elif isdatadescriptor(obj):
Tim Peters13b49d32001-09-23 02:00:29 +0000343 kind = "data"
Antoine Pitrou86a8a9a2011-12-21 09:57:40 +0100344 else:
345 obj_via_getattr = getattr(cls, name)
346 if (isfunction(obj_via_getattr) or
347 ismethoddescriptor(obj_via_getattr)):
348 kind = "method"
349 else:
350 kind = "data"
351 obj = obj_via_getattr
Tim Peters13b49d32001-09-23 02:00:29 +0000352
Christian Heimes25bb7832008-01-11 16:17:00 +0000353 result.append(Attribute(name, kind, homecls, obj))
Tim Peters13b49d32001-09-23 02:00:29 +0000354
355 return result
356
Tim Peterse0b2d7a2001-09-22 06:10:55 +0000357# ----------------------------------------------------------- class helpers
Tim Peterse0b2d7a2001-09-22 06:10:55 +0000358
359def getmro(cls):
360 "Return tuple of base classes (including cls) in method resolution order."
Benjamin Petersonb82c8e52010-11-04 00:38:49 +0000361 return cls.__mro__
Tim Peterse0b2d7a2001-09-22 06:10:55 +0000362
Nick Coghlane8c45d62013-07-28 20:00:01 +1000363# -------------------------------------------------------- function helpers
364
365def unwrap(func, *, stop=None):
366 """Get the object wrapped by *func*.
367
368 Follows the chain of :attr:`__wrapped__` attributes returning the last
369 object in the chain.
370
371 *stop* is an optional callback accepting an object in the wrapper chain
372 as its sole argument that allows the unwrapping to be terminated early if
373 the callback returns a true value. If the callback never returns a true
374 value, the last object in the chain is returned as usual. For example,
375 :func:`signature` uses this to stop unwrapping if any object in the
376 chain has a ``__signature__`` attribute defined.
377
378 :exc:`ValueError` is raised if a cycle is encountered.
379
380 """
381 if stop is None:
382 def _is_wrapper(f):
383 return hasattr(f, '__wrapped__')
384 else:
385 def _is_wrapper(f):
386 return hasattr(f, '__wrapped__') and not stop(f)
387 f = func # remember the original func for error reporting
388 memo = {id(f)} # Memoise by id to tolerate non-hashable objects
389 while _is_wrapper(func):
390 func = func.__wrapped__
391 id_func = id(func)
392 if id_func in memo:
393 raise ValueError('wrapper loop when unwrapping {!r}'.format(f))
394 memo.add(id_func)
395 return func
396
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000397# -------------------------------------------------- source code extraction
398def indentsize(line):
399 """Return the indent size, in spaces, at the start of a line of text."""
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000400 expline = line.expandtabs()
401 return len(expline) - len(expline.lstrip())
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000402
403def getdoc(object):
404 """Get the documentation string for an object.
405
406 All tabs are expanded to spaces. To clean up docstrings that are
407 indented to line up with blocks of code, any whitespace than can be
408 uniformly removed from the second line onwards is removed."""
Tim Peters24008312002-03-17 18:56:20 +0000409 try:
410 doc = object.__doc__
411 except AttributeError:
412 return None
Guido van Rossum3172c5d2007-10-16 18:12:55 +0000413 if not isinstance(doc, str):
Tim Peters24008312002-03-17 18:56:20 +0000414 return None
Georg Brandl0c77a822008-06-10 16:37:50 +0000415 return cleandoc(doc)
416
417def cleandoc(doc):
418 """Clean up indentation from docstrings.
419
420 Any whitespace that can be uniformly removed from the second line
421 onwards is removed."""
Tim Peters24008312002-03-17 18:56:20 +0000422 try:
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000423 lines = doc.expandtabs().split('\n')
Tim Peters24008312002-03-17 18:56:20 +0000424 except UnicodeError:
425 return None
426 else:
Ka-Ping Yeea59ef7b2002-11-30 03:53:15 +0000427 # Find minimum indentation of any non-blank lines after first line.
Christian Heimesa37d4c62007-12-04 23:02:19 +0000428 margin = sys.maxsize
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000429 for line in lines[1:]:
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000430 content = len(line.lstrip())
Ka-Ping Yeea59ef7b2002-11-30 03:53:15 +0000431 if content:
432 indent = len(line) - content
433 margin = min(margin, indent)
434 # Remove indentation.
435 if lines:
436 lines[0] = lines[0].lstrip()
Christian Heimesa37d4c62007-12-04 23:02:19 +0000437 if margin < sys.maxsize:
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000438 for i in range(1, len(lines)): lines[i] = lines[i][margin:]
Ka-Ping Yeea59ef7b2002-11-30 03:53:15 +0000439 # Remove any trailing or leading blank lines.
440 while lines and not lines[-1]:
441 lines.pop()
442 while lines and not lines[0]:
443 lines.pop(0)
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000444 return '\n'.join(lines)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000445
446def getfile(object):
Ka-Ping Yeec113c242001-03-02 02:08:53 +0000447 """Work out which source or compiled file an object was defined in."""
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000448 if ismodule(object):
449 if hasattr(object, '__file__'):
450 return object.__file__
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +0000451 raise TypeError('{!r} is a built-in module'.format(object))
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000452 if isclass(object):
Ka-Ping Yeec99e0f12001-04-13 12:10:40 +0000453 object = sys.modules.get(object.__module__)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000454 if hasattr(object, '__file__'):
455 return object.__file__
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +0000456 raise TypeError('{!r} is a built-in class'.format(object))
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000457 if ismethod(object):
Christian Heimesff737952007-11-27 10:40:20 +0000458 object = object.__func__
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000459 if isfunction(object):
Neal Norwitz221085d2007-02-25 20:55:47 +0000460 object = object.__code__
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000461 if istraceback(object):
462 object = object.tb_frame
463 if isframe(object):
464 object = object.f_code
465 if iscode(object):
466 return object.co_filename
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +0000467 raise TypeError('{!r} is not a module, class, method, '
468 'function, traceback, frame, or code object'.format(object))
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000469
Christian Heimes25bb7832008-01-11 16:17:00 +0000470ModuleInfo = namedtuple('ModuleInfo', 'name suffix mode module_type')
471
Ka-Ping Yee4d6fc7f2001-04-10 11:43:00 +0000472def getmoduleinfo(path):
473 """Get the module name, suffix, mode, and module type for a given file."""
Brett Cannoncb66eb02012-05-11 12:58:42 -0400474 warnings.warn('inspect.getmoduleinfo() is deprecated', DeprecationWarning,
475 2)
Brett Cannone4f41de2013-06-16 13:13:40 -0400476 with warnings.catch_warnings():
477 warnings.simplefilter('ignore', PendingDeprecationWarning)
478 import imp
Ka-Ping Yee4d6fc7f2001-04-10 11:43:00 +0000479 filename = os.path.basename(path)
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000480 suffixes = [(-len(suffix), suffix, mode, mtype)
481 for suffix, mode, mtype in imp.get_suffixes()]
Ka-Ping Yee4d6fc7f2001-04-10 11:43:00 +0000482 suffixes.sort() # try longest suffixes first, in case they overlap
483 for neglen, suffix, mode, mtype in suffixes:
484 if filename[neglen:] == suffix:
Christian Heimes25bb7832008-01-11 16:17:00 +0000485 return ModuleInfo(filename[:neglen], suffix, mode, mtype)
Ka-Ping Yee4d6fc7f2001-04-10 11:43:00 +0000486
487def getmodulename(path):
488 """Return the module name for a given file, or None."""
Nick Coghlan76e07702012-07-18 23:14:57 +1000489 fname = os.path.basename(path)
490 # Check for paths that look like an actual module file
491 suffixes = [(-len(suffix), suffix)
492 for suffix in importlib.machinery.all_suffixes()]
493 suffixes.sort() # try longest suffixes first, in case they overlap
494 for neglen, suffix in suffixes:
495 if fname.endswith(suffix):
496 return fname[:neglen]
497 return None
Ka-Ping Yee4d6fc7f2001-04-10 11:43:00 +0000498
Ka-Ping Yeec113c242001-03-02 02:08:53 +0000499def getsourcefile(object):
R. David Murraya1b37402010-06-17 02:04:29 +0000500 """Return the filename that can be used to locate an object's source.
501 Return None if no way can be identified to get the source.
502 """
Ka-Ping Yeec113c242001-03-02 02:08:53 +0000503 filename = getfile(object)
Brett Cannoncb66eb02012-05-11 12:58:42 -0400504 all_bytecode_suffixes = importlib.machinery.DEBUG_BYTECODE_SUFFIXES[:]
505 all_bytecode_suffixes += importlib.machinery.OPTIMIZED_BYTECODE_SUFFIXES[:]
506 if any(filename.endswith(s) for s in all_bytecode_suffixes):
507 filename = (os.path.splitext(filename)[0] +
508 importlib.machinery.SOURCE_SUFFIXES[0])
509 elif any(filename.endswith(s) for s in
510 importlib.machinery.EXTENSION_SUFFIXES):
511 return None
Thomas Wouters477c8d52006-05-27 19:21:47 +0000512 if os.path.exists(filename):
513 return filename
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000514 # only return a non-existent filename if the module has a PEP 302 loader
Brett Cannon4c14b5d2013-05-04 13:56:58 -0400515 if getattr(getmodule(object, filename), '__loader__', None) is not None:
Ka-Ping Yeec113c242001-03-02 02:08:53 +0000516 return filename
R. David Murraya1b37402010-06-17 02:04:29 +0000517 # or it is in the linecache
518 if filename in linecache.cache:
519 return filename
Ka-Ping Yeec113c242001-03-02 02:08:53 +0000520
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000521def getabsfile(object, _filename=None):
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000522 """Return an absolute path to the source or compiled file for an object.
Ka-Ping Yeec113c242001-03-02 02:08:53 +0000523
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000524 The idea is for each object to have a unique origin, so this routine
525 normalizes the result as much as possible."""
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000526 if _filename is None:
527 _filename = getsourcefile(object) or getfile(object)
528 return os.path.normcase(os.path.abspath(_filename))
Ka-Ping Yeec113c242001-03-02 02:08:53 +0000529
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000530modulesbyfile = {}
Thomas Wouters89f507f2006-12-13 04:49:30 +0000531_filesbymodname = {}
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000532
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000533def getmodule(object, _filename=None):
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000534 """Return the module an object was defined in, or None if not found."""
Ka-Ping Yee202c99b2001-04-13 09:15:08 +0000535 if ismodule(object):
536 return object
Johannes Gijsbers93245262004-09-11 15:53:22 +0000537 if hasattr(object, '__module__'):
Ka-Ping Yee8b58b842001-03-01 13:56:16 +0000538 return sys.modules.get(object.__module__)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000539 # Try the filename to modulename cache
540 if _filename is not None and _filename in modulesbyfile:
541 return sys.modules.get(modulesbyfile[_filename])
542 # Try the cache again with the absolute file name
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000543 try:
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000544 file = getabsfile(object, _filename)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000545 except TypeError:
546 return None
Raymond Hettinger54f02222002-06-01 14:18:47 +0000547 if file in modulesbyfile:
Ka-Ping Yeeb38bbbd2003-03-28 16:29:50 +0000548 return sys.modules.get(modulesbyfile[file])
Thomas Wouters89f507f2006-12-13 04:49:30 +0000549 # Update the filename to module name cache and check yet again
550 # Copy sys.modules in order to cope with changes while iterating
Éric Araujoa74f8ef2011-11-29 16:58:53 +0100551 for modname, module in list(sys.modules.items()):
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000552 if ismodule(module) and hasattr(module, '__file__'):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000553 f = module.__file__
554 if f == _filesbymodname.get(modname, None):
555 # Have already mapped this module, so skip it
556 continue
557 _filesbymodname[modname] = f
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000558 f = getabsfile(module)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000559 # Always map to the name the module knows itself by
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000560 modulesbyfile[f] = modulesbyfile[
561 os.path.realpath(f)] = module.__name__
Raymond Hettinger54f02222002-06-01 14:18:47 +0000562 if file in modulesbyfile:
Ka-Ping Yeeb38bbbd2003-03-28 16:29:50 +0000563 return sys.modules.get(modulesbyfile[file])
Thomas Wouters89f507f2006-12-13 04:49:30 +0000564 # Check the main module
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000565 main = sys.modules['__main__']
Brett Cannon4a671fe2003-06-15 22:33:28 +0000566 if not hasattr(object, '__name__'):
567 return None
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000568 if hasattr(main, object.__name__):
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000569 mainobject = getattr(main, object.__name__)
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000570 if mainobject is object:
571 return main
Thomas Wouters89f507f2006-12-13 04:49:30 +0000572 # Check builtins
Georg Brandl1a3284e2007-12-02 09:40:06 +0000573 builtin = sys.modules['builtins']
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000574 if hasattr(builtin, object.__name__):
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000575 builtinobject = getattr(builtin, object.__name__)
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000576 if builtinobject is object:
577 return builtin
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000578
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000579def findsource(object):
580 """Return the entire source file and starting line number for an object.
581
582 The argument may be a module, class, method, function, traceback, frame,
583 or code object. The source code is returned as a list of all the lines
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200584 in the file and the line number indexes a line in that list. An OSError
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000585 is raised if the source code cannot be retrieved."""
Benjamin Peterson9620cc02011-06-11 15:53:11 -0500586
587 file = getfile(object)
588 sourcefile = getsourcefile(object)
Ezio Melotti1b145922013-03-30 05:17:24 +0200589 if not sourcefile and file[:1] + file[-1:] != '<>':
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200590 raise OSError('source code not available')
Benjamin Peterson9620cc02011-06-11 15:53:11 -0500591 file = sourcefile if sourcefile else file
592
Thomas Wouters89f507f2006-12-13 04:49:30 +0000593 module = getmodule(object, file)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000594 if module:
595 lines = linecache.getlines(file, module.__dict__)
596 else:
597 lines = linecache.getlines(file)
Neil Schemenauerf06f8532002-03-23 23:51:04 +0000598 if not lines:
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200599 raise OSError('could not get source code')
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000600
601 if ismodule(object):
602 return lines, 0
603
604 if isclass(object):
605 name = object.__name__
Thomas Wouters89f507f2006-12-13 04:49:30 +0000606 pat = re.compile(r'^(\s*)class\s*' + name + r'\b')
607 # make some effort to find the best matching class definition:
608 # use the one with the least indentation, which is the one
609 # that's most probably not inside a function definition.
610 candidates = []
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000611 for i in range(len(lines)):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000612 match = pat.match(lines[i])
613 if match:
614 # if it's at toplevel, it's already the best one
615 if lines[i][0] == 'c':
616 return lines, i
617 # else add whitespace to candidate list
618 candidates.append((match.group(1), i))
619 if candidates:
620 # this will sort by whitespace, and by line number,
621 # less whitespace first
622 candidates.sort()
623 return lines, candidates[0][1]
Jeremy Hyltonab919022003-06-27 18:41:20 +0000624 else:
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200625 raise OSError('could not find class definition')
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000626
627 if ismethod(object):
Christian Heimesff737952007-11-27 10:40:20 +0000628 object = object.__func__
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000629 if isfunction(object):
Neal Norwitz221085d2007-02-25 20:55:47 +0000630 object = object.__code__
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000631 if istraceback(object):
632 object = object.tb_frame
633 if isframe(object):
634 object = object.f_code
635 if iscode(object):
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000636 if not hasattr(object, 'co_firstlineno'):
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200637 raise OSError('could not find function definition')
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000638 lnum = object.co_firstlineno - 1
Johannes Gijsbers1542f342004-12-12 16:46:28 +0000639 pat = re.compile(r'^(\s*def\s)|(.*(?<!\w)lambda(:|\s))|^(\s*@)')
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000640 while lnum > 0:
Ka-Ping Yeea6e59712001-03-10 09:31:55 +0000641 if pat.match(lines[lnum]): break
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000642 lnum = lnum - 1
643 return lines, lnum
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200644 raise OSError('could not find code object')
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000645
646def getcomments(object):
Jeremy Hyltonb4c17c82002-03-28 23:01:56 +0000647 """Get lines of comments immediately preceding an object's source code.
648
649 Returns None when source can't be found.
650 """
651 try:
652 lines, lnum = findsource(object)
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200653 except (OSError, TypeError):
Jeremy Hyltonb4c17c82002-03-28 23:01:56 +0000654 return None
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000655
656 if ismodule(object):
657 # Look for a comment block at the top of the file.
658 start = 0
Ka-Ping Yeeb910efe2001-04-12 13:17:17 +0000659 if lines and lines[0][:2] == '#!': start = 1
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000660 while start < len(lines) and lines[start].strip() in ('', '#'):
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000661 start = start + 1
Ka-Ping Yeeb910efe2001-04-12 13:17:17 +0000662 if start < len(lines) and lines[start][:1] == '#':
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000663 comments = []
664 end = start
665 while end < len(lines) and lines[end][:1] == '#':
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000666 comments.append(lines[end].expandtabs())
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000667 end = end + 1
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000668 return ''.join(comments)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000669
670 # Look for a preceding block of comments at the same indentation.
671 elif lnum > 0:
672 indent = indentsize(lines[lnum])
673 end = lnum - 1
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000674 if end >= 0 and lines[end].lstrip()[:1] == '#' and \
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000675 indentsize(lines[end]) == indent:
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000676 comments = [lines[end].expandtabs().lstrip()]
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000677 if end > 0:
678 end = end - 1
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000679 comment = lines[end].expandtabs().lstrip()
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000680 while comment[:1] == '#' and indentsize(lines[end]) == indent:
681 comments[:0] = [comment]
682 end = end - 1
683 if end < 0: break
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000684 comment = lines[end].expandtabs().lstrip()
685 while comments and comments[0].strip() == '#':
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000686 comments[:1] = []
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000687 while comments and comments[-1].strip() == '#':
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000688 comments[-1:] = []
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000689 return ''.join(comments)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000690
Tim Peters4efb6e92001-06-29 23:51:08 +0000691class EndOfBlock(Exception): pass
692
693class BlockFinder:
694 """Provide a tokeneater() method to detect the end of a code block."""
695 def __init__(self):
696 self.indent = 0
Johannes Gijsbersa5855d52005-03-12 16:37:11 +0000697 self.islambda = False
Johannes Gijsbers1542f342004-12-12 16:46:28 +0000698 self.started = False
699 self.passline = False
Armin Rigodd5c0232005-09-25 11:45:45 +0000700 self.last = 1
Tim Peters4efb6e92001-06-29 23:51:08 +0000701
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000702 def tokeneater(self, type, token, srowcol, erowcol, line):
Tim Peters4efb6e92001-06-29 23:51:08 +0000703 if not self.started:
Armin Rigodd5c0232005-09-25 11:45:45 +0000704 # look for the first "def", "class" or "lambda"
Johannes Gijsbers1542f342004-12-12 16:46:28 +0000705 if token in ("def", "class", "lambda"):
Johannes Gijsbersa5855d52005-03-12 16:37:11 +0000706 if token == "lambda":
707 self.islambda = True
Johannes Gijsbers1542f342004-12-12 16:46:28 +0000708 self.started = True
Armin Rigodd5c0232005-09-25 11:45:45 +0000709 self.passline = True # skip to the end of the line
Tim Peters4efb6e92001-06-29 23:51:08 +0000710 elif type == tokenize.NEWLINE:
Armin Rigodd5c0232005-09-25 11:45:45 +0000711 self.passline = False # stop skipping when a NEWLINE is seen
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000712 self.last = srowcol[0]
Armin Rigodd5c0232005-09-25 11:45:45 +0000713 if self.islambda: # lambdas always end at the first NEWLINE
714 raise EndOfBlock
Johannes Gijsbers1542f342004-12-12 16:46:28 +0000715 elif self.passline:
716 pass
Tim Peters4efb6e92001-06-29 23:51:08 +0000717 elif type == tokenize.INDENT:
718 self.indent = self.indent + 1
Johannes Gijsbers1542f342004-12-12 16:46:28 +0000719 self.passline = True
Tim Peters4efb6e92001-06-29 23:51:08 +0000720 elif type == tokenize.DEDENT:
721 self.indent = self.indent - 1
Armin Rigodd5c0232005-09-25 11:45:45 +0000722 # the end of matching indent/dedent pairs end a block
723 # (note that this only works for "def"/"class" blocks,
724 # not e.g. for "if: else:" or "try: finally:" blocks)
725 if self.indent <= 0:
726 raise EndOfBlock
727 elif self.indent == 0 and type not in (tokenize.COMMENT, tokenize.NL):
728 # any other token on the same indentation level end the previous
729 # block as well, except the pseudo-tokens COMMENT and NL.
730 raise EndOfBlock
Tim Peters4efb6e92001-06-29 23:51:08 +0000731
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000732def getblock(lines):
733 """Extract the block of code at the top of the given list of lines."""
Armin Rigodd5c0232005-09-25 11:45:45 +0000734 blockfinder = BlockFinder()
Tim Peters4efb6e92001-06-29 23:51:08 +0000735 try:
Trent Nelson428de652008-03-18 22:41:35 +0000736 tokens = tokenize.generate_tokens(iter(lines).__next__)
737 for _token in tokens:
738 blockfinder.tokeneater(*_token)
Armin Rigodd5c0232005-09-25 11:45:45 +0000739 except (EndOfBlock, IndentationError):
740 pass
741 return lines[:blockfinder.last]
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000742
743def getsourcelines(object):
744 """Return a list of source lines and starting line number for an object.
745
746 The argument may be a module, class, method, function, traceback, frame,
747 or code object. The source code is returned as a list of the lines
748 corresponding to the object and the line number indicates where in the
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200749 original source file the first line of code was found. An OSError is
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000750 raised if the source code cannot be retrieved."""
751 lines, lnum = findsource(object)
752
753 if ismodule(object): return lines, 0
754 else: return getblock(lines[lnum:]), lnum + 1
755
756def getsource(object):
757 """Return the text of the source code for an object.
758
759 The argument may be a module, class, method, function, traceback, frame,
760 or code object. The source code is returned as a single string. An
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200761 OSError is raised if the source code cannot be retrieved."""
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000762 lines, lnum = getsourcelines(object)
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000763 return ''.join(lines)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000764
765# --------------------------------------------------- class tree extraction
766def walktree(classes, children, parent):
767 """Recursive helper function for getclasstree()."""
768 results = []
Raymond Hettingera1a992c2005-03-11 06:46:45 +0000769 classes.sort(key=attrgetter('__module__', '__name__'))
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000770 for c in classes:
771 results.append((c, c.__bases__))
Raymond Hettinger54f02222002-06-01 14:18:47 +0000772 if c in children:
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000773 results.append(walktree(children[c], children, c))
774 return results
775
Georg Brandl5ce83a02009-06-01 17:23:51 +0000776def getclasstree(classes, unique=False):
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000777 """Arrange the given list of classes into a hierarchy of nested lists.
778
779 Where a nested list appears, it contains classes derived from the class
780 whose entry immediately precedes the list. Each entry is a 2-tuple
781 containing a class and a tuple of its base classes. If the 'unique'
782 argument is true, exactly one entry appears in the returned structure
783 for each class in the given list. Otherwise, classes using multiple
784 inheritance and their descendants will appear multiple times."""
785 children = {}
786 roots = []
787 for c in classes:
788 if c.__bases__:
789 for parent in c.__bases__:
Raymond Hettinger54f02222002-06-01 14:18:47 +0000790 if not parent in children:
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000791 children[parent] = []
Serhiy Storchaka362c1b52013-09-05 17:14:32 +0300792 if c not in children[parent]:
793 children[parent].append(c)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000794 if unique and parent in classes: break
795 elif c not in roots:
796 roots.append(c)
Raymond Hettingere0d49722002-06-02 18:55:56 +0000797 for parent in children:
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000798 if parent not in classes:
799 roots.append(parent)
800 return walktree(roots, children, None)
801
802# ------------------------------------------------ argument list extraction
Christian Heimes25bb7832008-01-11 16:17:00 +0000803Arguments = namedtuple('Arguments', 'args, varargs, varkw')
804
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000805def getargs(co):
806 """Get information about the arguments accepted by a code object.
807
Guido van Rossum2e65f892007-02-28 22:03:49 +0000808 Three things are returned: (args, varargs, varkw), where
Georg Brandlc1c4bf82010-10-15 16:07:41 +0000809 'args' is the list of argument names. Keyword-only arguments are
810 appended. 'varargs' and 'varkw' are the names of the * and **
811 arguments or None."""
Guido van Rossum2e65f892007-02-28 22:03:49 +0000812 args, varargs, kwonlyargs, varkw = _getfullargs(co)
Christian Heimes25bb7832008-01-11 16:17:00 +0000813 return Arguments(args + kwonlyargs, varargs, varkw)
Guido van Rossum2e65f892007-02-28 22:03:49 +0000814
815def _getfullargs(co):
816 """Get information about the arguments accepted by a code object.
817
818 Four things are returned: (args, varargs, kwonlyargs, varkw), where
Georg Brandlc1c4bf82010-10-15 16:07:41 +0000819 'args' and 'kwonlyargs' are lists of argument names, and 'varargs'
820 and 'varkw' are the names of the * and ** arguments or None."""
Jeremy Hylton64967882003-06-27 18:14:39 +0000821
822 if not iscode(co):
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +0000823 raise TypeError('{!r} is not a code object'.format(co))
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000824
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000825 nargs = co.co_argcount
826 names = co.co_varnames
Guido van Rossum2e65f892007-02-28 22:03:49 +0000827 nkwargs = co.co_kwonlyargcount
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000828 args = list(names[:nargs])
Guido van Rossum2e65f892007-02-28 22:03:49 +0000829 kwonlyargs = list(names[nargs:nargs+nkwargs])
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000830 step = 0
831
Guido van Rossum2e65f892007-02-28 22:03:49 +0000832 nargs += nkwargs
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000833 varargs = None
834 if co.co_flags & CO_VARARGS:
835 varargs = co.co_varnames[nargs]
836 nargs = nargs + 1
837 varkw = None
838 if co.co_flags & CO_VARKEYWORDS:
839 varkw = co.co_varnames[nargs]
Guido van Rossum2e65f892007-02-28 22:03:49 +0000840 return args, varargs, kwonlyargs, varkw
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000841
Christian Heimes25bb7832008-01-11 16:17:00 +0000842
843ArgSpec = namedtuple('ArgSpec', 'args varargs keywords defaults')
844
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000845def getargspec(func):
846 """Get the names and default values of a function's arguments.
847
848 A tuple of four things is returned: (args, varargs, varkw, defaults).
Georg Brandlc1c4bf82010-10-15 16:07:41 +0000849 'args' is a list of the argument names.
Guido van Rossum2e65f892007-02-28 22:03:49 +0000850 'args' will include keyword-only argument names.
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000851 'varargs' and 'varkw' are the names of the * and ** arguments or None.
Jeremy Hylton64967882003-06-27 18:14:39 +0000852 'defaults' is an n-tuple of the default values of the last n arguments.
Guido van Rossuma8add0e2007-05-14 22:03:55 +0000853
Guido van Rossum2e65f892007-02-28 22:03:49 +0000854 Use the getfullargspec() API for Python-3000 code, as annotations
855 and keyword arguments are supported. getargspec() will raise ValueError
856 if the func has either annotations or keyword arguments.
857 """
858
859 args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults, ann = \
860 getfullargspec(func)
861 if kwonlyargs or ann:
Collin Winterce36ad82007-08-30 01:19:48 +0000862 raise ValueError("Function has keyword-only arguments or annotations"
863 ", use getfullargspec() API which can support them")
Christian Heimes25bb7832008-01-11 16:17:00 +0000864 return ArgSpec(args, varargs, varkw, defaults)
865
866FullArgSpec = namedtuple('FullArgSpec',
Benjamin Peterson3d4ca742008-11-12 21:39:01 +0000867 'args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults, annotations')
Guido van Rossum2e65f892007-02-28 22:03:49 +0000868
869def getfullargspec(func):
870 """Get the names and default values of a function's arguments.
871
Brett Cannon504d8852007-09-07 02:12:14 +0000872 A tuple of seven things is returned:
873 (args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults annotations).
Georg Brandlc1c4bf82010-10-15 16:07:41 +0000874 'args' is a list of the argument names.
Guido van Rossum2e65f892007-02-28 22:03:49 +0000875 'varargs' and 'varkw' are the names of the * and ** arguments or None.
876 'defaults' is an n-tuple of the default values of the last n arguments.
877 'kwonlyargs' is a list of keyword-only argument names.
878 'kwonlydefaults' is a dictionary mapping names from kwonlyargs to defaults.
879 'annotations' is a dictionary mapping argument names to annotations.
Guido van Rossuma8add0e2007-05-14 22:03:55 +0000880
Guido van Rossum2e65f892007-02-28 22:03:49 +0000881 The first four items in the tuple correspond to getargspec().
Jeremy Hylton64967882003-06-27 18:14:39 +0000882 """
883
884 if ismethod(func):
Christian Heimesff737952007-11-27 10:40:20 +0000885 func = func.__func__
Jeremy Hylton64967882003-06-27 18:14:39 +0000886 if not isfunction(func):
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +0000887 raise TypeError('{!r} is not a Python function'.format(func))
Guido van Rossum2e65f892007-02-28 22:03:49 +0000888 args, varargs, kwonlyargs, varkw = _getfullargs(func.__code__)
Christian Heimes25bb7832008-01-11 16:17:00 +0000889 return FullArgSpec(args, varargs, varkw, func.__defaults__,
Guido van Rossum2e65f892007-02-28 22:03:49 +0000890 kwonlyargs, func.__kwdefaults__, func.__annotations__)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000891
Christian Heimes25bb7832008-01-11 16:17:00 +0000892ArgInfo = namedtuple('ArgInfo', 'args varargs keywords locals')
893
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000894def getargvalues(frame):
895 """Get information about arguments passed into a particular frame.
896
897 A tuple of four things is returned: (args, varargs, varkw, locals).
Georg Brandlc1c4bf82010-10-15 16:07:41 +0000898 'args' is a list of the argument names.
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000899 'varargs' and 'varkw' are the names of the * and ** arguments or None.
900 'locals' is the locals dictionary of the given frame."""
901 args, varargs, varkw = getargs(frame.f_code)
Benjamin Peterson1a6e0d02008-10-25 15:49:17 +0000902 return ArgInfo(args, varargs, varkw, frame.f_locals)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000903
Guido van Rossum2e65f892007-02-28 22:03:49 +0000904def formatannotation(annotation, base_module=None):
905 if isinstance(annotation, type):
Georg Brandl1a3284e2007-12-02 09:40:06 +0000906 if annotation.__module__ in ('builtins', base_module):
Guido van Rossum2e65f892007-02-28 22:03:49 +0000907 return annotation.__name__
908 return annotation.__module__+'.'+annotation.__name__
909 return repr(annotation)
Guido van Rossuma8add0e2007-05-14 22:03:55 +0000910
Guido van Rossum2e65f892007-02-28 22:03:49 +0000911def formatannotationrelativeto(object):
Guido van Rossuma8add0e2007-05-14 22:03:55 +0000912 module = getattr(object, '__module__', None)
913 def _formatannotation(annotation):
914 return formatannotation(annotation, module)
915 return _formatannotation
Guido van Rossum2e65f892007-02-28 22:03:49 +0000916
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000917def formatargspec(args, varargs=None, varkw=None, defaults=None,
Guido van Rossum2e65f892007-02-28 22:03:49 +0000918 kwonlyargs=(), kwonlydefaults={}, annotations={},
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000919 formatarg=str,
920 formatvarargs=lambda name: '*' + name,
921 formatvarkw=lambda name: '**' + name,
922 formatvalue=lambda value: '=' + repr(value),
Guido van Rossum2e65f892007-02-28 22:03:49 +0000923 formatreturns=lambda text: ' -> ' + text,
Georg Brandlc1c4bf82010-10-15 16:07:41 +0000924 formatannotation=formatannotation):
Guido van Rossuma8add0e2007-05-14 22:03:55 +0000925 """Format an argument spec from the values returned by getargspec
Guido van Rossum2e65f892007-02-28 22:03:49 +0000926 or getfullargspec.
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000927
Guido van Rossum2e65f892007-02-28 22:03:49 +0000928 The first seven arguments are (args, varargs, varkw, defaults,
929 kwonlyargs, kwonlydefaults, annotations). The other five arguments
930 are the corresponding optional formatting functions that are called to
931 turn names and values into strings. The last argument is an optional
932 function to format the sequence of arguments."""
933 def formatargandannotation(arg):
934 result = formatarg(arg)
935 if arg in annotations:
936 result += ': ' + formatannotation(annotations[arg])
937 return result
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000938 specs = []
939 if defaults:
940 firstdefault = len(args) - len(defaults)
Benjamin Petersonb58dda72009-01-18 22:27:04 +0000941 for i, arg in enumerate(args):
Georg Brandlc1c4bf82010-10-15 16:07:41 +0000942 spec = formatargandannotation(arg)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000943 if defaults and i >= firstdefault:
944 spec = spec + formatvalue(defaults[i - firstdefault])
945 specs.append(spec)
Raymond Hettinger936654b2002-06-01 03:06:31 +0000946 if varargs is not None:
Guido van Rossum2e65f892007-02-28 22:03:49 +0000947 specs.append(formatvarargs(formatargandannotation(varargs)))
948 else:
949 if kwonlyargs:
950 specs.append('*')
951 if kwonlyargs:
952 for kwonlyarg in kwonlyargs:
953 spec = formatargandannotation(kwonlyarg)
Benjamin Peterson9953a8d2009-01-17 04:15:01 +0000954 if kwonlydefaults and kwonlyarg in kwonlydefaults:
Guido van Rossum2e65f892007-02-28 22:03:49 +0000955 spec += formatvalue(kwonlydefaults[kwonlyarg])
956 specs.append(spec)
Raymond Hettinger936654b2002-06-01 03:06:31 +0000957 if varkw is not None:
Guido van Rossum2e65f892007-02-28 22:03:49 +0000958 specs.append(formatvarkw(formatargandannotation(varkw)))
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000959 result = '(' + ', '.join(specs) + ')'
Guido van Rossum2e65f892007-02-28 22:03:49 +0000960 if 'return' in annotations:
961 result += formatreturns(formatannotation(annotations['return']))
962 return result
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000963
964def formatargvalues(args, varargs, varkw, locals,
965 formatarg=str,
966 formatvarargs=lambda name: '*' + name,
967 formatvarkw=lambda name: '**' + name,
Georg Brandlc1c4bf82010-10-15 16:07:41 +0000968 formatvalue=lambda value: '=' + repr(value)):
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000969 """Format an argument spec from the 4 values returned by getargvalues.
970
971 The first four arguments are (args, varargs, varkw, locals). The
972 next four arguments are the corresponding optional formatting functions
973 that are called to turn names and values into strings. The ninth
974 argument is an optional function to format the sequence of arguments."""
975 def convert(name, locals=locals,
976 formatarg=formatarg, formatvalue=formatvalue):
977 return formatarg(name) + formatvalue(locals[name])
978 specs = []
979 for i in range(len(args)):
Georg Brandlc1c4bf82010-10-15 16:07:41 +0000980 specs.append(convert(args[i]))
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000981 if varargs:
982 specs.append(formatvarargs(varargs) + formatvalue(locals[varargs]))
983 if varkw:
984 specs.append(formatvarkw(varkw) + formatvalue(locals[varkw]))
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000985 return '(' + ', '.join(specs) + ')'
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000986
Benjamin Petersone109c702011-06-24 09:37:26 -0500987def _missing_arguments(f_name, argnames, pos, values):
988 names = [repr(name) for name in argnames if name not in values]
989 missing = len(names)
990 if missing == 1:
991 s = names[0]
992 elif missing == 2:
993 s = "{} and {}".format(*names)
994 else:
995 tail = ", {} and {}".format(names[-2:])
996 del names[-2:]
997 s = ", ".join(names) + tail
998 raise TypeError("%s() missing %i required %s argument%s: %s" %
999 (f_name, missing,
1000 "positional" if pos else "keyword-only",
1001 "" if missing == 1 else "s", s))
1002
1003def _too_many(f_name, args, kwonly, varargs, defcount, given, values):
Benjamin Petersonb204a422011-06-05 22:04:07 -05001004 atleast = len(args) - defcount
Benjamin Petersonb204a422011-06-05 22:04:07 -05001005 kwonly_given = len([arg for arg in kwonly if arg in values])
1006 if varargs:
1007 plural = atleast != 1
1008 sig = "at least %d" % (atleast,)
1009 elif defcount:
1010 plural = True
1011 sig = "from %d to %d" % (atleast, len(args))
1012 else:
1013 plural = len(args) != 1
1014 sig = str(len(args))
1015 kwonly_sig = ""
1016 if kwonly_given:
1017 msg = " positional argument%s (and %d keyword-only argument%s)"
1018 kwonly_sig = (msg % ("s" if given != 1 else "", kwonly_given,
1019 "s" if kwonly_given != 1 else ""))
1020 raise TypeError("%s() takes %s positional argument%s but %d%s %s given" %
1021 (f_name, sig, "s" if plural else "", given, kwonly_sig,
1022 "was" if given == 1 and not kwonly_given else "were"))
1023
Benjamin Peterson25cd7eb2010-03-30 18:42:32 +00001024def getcallargs(func, *positional, **named):
1025 """Get the mapping of arguments to values.
1026
1027 A dict is returned, with keys the function argument names (including the
1028 names of the * and ** arguments, if any), and values the respective bound
1029 values from 'positional' and 'named'."""
1030 spec = getfullargspec(func)
1031 args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults, ann = spec
1032 f_name = func.__name__
1033 arg2value = {}
1034
Benjamin Petersonb204a422011-06-05 22:04:07 -05001035
Benjamin Peterson25cd7eb2010-03-30 18:42:32 +00001036 if ismethod(func) and func.__self__ is not None:
1037 # implicit 'self' (or 'cls' for classmethods) argument
1038 positional = (func.__self__,) + positional
1039 num_pos = len(positional)
Benjamin Peterson25cd7eb2010-03-30 18:42:32 +00001040 num_args = len(args)
1041 num_defaults = len(defaults) if defaults else 0
Benjamin Peterson25cd7eb2010-03-30 18:42:32 +00001042
Benjamin Petersonb204a422011-06-05 22:04:07 -05001043 n = min(num_pos, num_args)
1044 for i in range(n):
1045 arg2value[args[i]] = positional[i]
1046 if varargs:
1047 arg2value[varargs] = tuple(positional[n:])
1048 possible_kwargs = set(args + kwonlyargs)
Benjamin Peterson25cd7eb2010-03-30 18:42:32 +00001049 if varkw:
Benjamin Petersonb204a422011-06-05 22:04:07 -05001050 arg2value[varkw] = {}
1051 for kw, value in named.items():
1052 if kw not in possible_kwargs:
1053 if not varkw:
1054 raise TypeError("%s() got an unexpected keyword argument %r" %
1055 (f_name, kw))
1056 arg2value[varkw][kw] = value
1057 continue
1058 if kw in arg2value:
1059 raise TypeError("%s() got multiple values for argument %r" %
1060 (f_name, kw))
1061 arg2value[kw] = value
1062 if num_pos > num_args and not varargs:
Benjamin Petersone109c702011-06-24 09:37:26 -05001063 _too_many(f_name, args, kwonlyargs, varargs, num_defaults,
1064 num_pos, arg2value)
Benjamin Petersonb204a422011-06-05 22:04:07 -05001065 if num_pos < num_args:
Benjamin Petersone109c702011-06-24 09:37:26 -05001066 req = args[:num_args - num_defaults]
1067 for arg in req:
Benjamin Petersonb204a422011-06-05 22:04:07 -05001068 if arg not in arg2value:
Benjamin Petersone109c702011-06-24 09:37:26 -05001069 _missing_arguments(f_name, req, True, arg2value)
Benjamin Petersonb204a422011-06-05 22:04:07 -05001070 for i, arg in enumerate(args[num_args - num_defaults:]):
1071 if arg not in arg2value:
1072 arg2value[arg] = defaults[i]
Benjamin Petersone109c702011-06-24 09:37:26 -05001073 missing = 0
Benjamin Petersonb204a422011-06-05 22:04:07 -05001074 for kwarg in kwonlyargs:
1075 if kwarg not in arg2value:
Benjamin Petersone109c702011-06-24 09:37:26 -05001076 if kwarg in kwonlydefaults:
1077 arg2value[kwarg] = kwonlydefaults[kwarg]
1078 else:
1079 missing += 1
1080 if missing:
1081 _missing_arguments(f_name, kwonlyargs, False, arg2value)
Benjamin Peterson25cd7eb2010-03-30 18:42:32 +00001082 return arg2value
1083
Nick Coghlan2f92e542012-06-23 19:39:55 +10001084ClosureVars = namedtuple('ClosureVars', 'nonlocals globals builtins unbound')
1085
1086def getclosurevars(func):
1087 """
1088 Get the mapping of free variables to their current values.
1089
Meador Inge8fda3592012-07-19 21:33:21 -05001090 Returns a named tuple of dicts mapping the current nonlocal, global
Nick Coghlan2f92e542012-06-23 19:39:55 +10001091 and builtin references as seen by the body of the function. A final
1092 set of unbound names that could not be resolved is also provided.
1093 """
1094
1095 if ismethod(func):
1096 func = func.__func__
1097
1098 if not isfunction(func):
1099 raise TypeError("'{!r}' is not a Python function".format(func))
1100
1101 code = func.__code__
1102 # Nonlocal references are named in co_freevars and resolved
1103 # by looking them up in __closure__ by positional index
1104 if func.__closure__ is None:
1105 nonlocal_vars = {}
1106 else:
1107 nonlocal_vars = {
1108 var : cell.cell_contents
1109 for var, cell in zip(code.co_freevars, func.__closure__)
1110 }
1111
1112 # Global and builtin references are named in co_names and resolved
1113 # by looking them up in __globals__ or __builtins__
1114 global_ns = func.__globals__
1115 builtin_ns = global_ns.get("__builtins__", builtins.__dict__)
1116 if ismodule(builtin_ns):
1117 builtin_ns = builtin_ns.__dict__
1118 global_vars = {}
1119 builtin_vars = {}
1120 unbound_names = set()
1121 for name in code.co_names:
1122 if name in ("None", "True", "False"):
1123 # Because these used to be builtins instead of keywords, they
1124 # may still show up as name references. We ignore them.
1125 continue
1126 try:
1127 global_vars[name] = global_ns[name]
1128 except KeyError:
1129 try:
1130 builtin_vars[name] = builtin_ns[name]
1131 except KeyError:
1132 unbound_names.add(name)
1133
1134 return ClosureVars(nonlocal_vars, global_vars,
1135 builtin_vars, unbound_names)
1136
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001137# -------------------------------------------------- stack frame extraction
Christian Heimes25bb7832008-01-11 16:17:00 +00001138
1139Traceback = namedtuple('Traceback', 'filename lineno function code_context index')
1140
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001141def getframeinfo(frame, context=1):
1142 """Get information about a frame or traceback object.
1143
1144 A tuple of five things is returned: the filename, the line number of
1145 the current line, the function name, a list of lines of context from
1146 the source code, and the index of the current line within that list.
1147 The optional second argument specifies the number of lines of context
1148 to return, which are centered around the current line."""
1149 if istraceback(frame):
Andrew M. Kuchlingba8b6bc2004-06-05 14:11:59 +00001150 lineno = frame.tb_lineno
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001151 frame = frame.tb_frame
Andrew M. Kuchlingba8b6bc2004-06-05 14:11:59 +00001152 else:
1153 lineno = frame.f_lineno
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001154 if not isframe(frame):
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00001155 raise TypeError('{!r} is not a frame or traceback object'.format(frame))
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001156
Neil Schemenauerf06f8532002-03-23 23:51:04 +00001157 filename = getsourcefile(frame) or getfile(frame)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001158 if context > 0:
Guido van Rossum54e54c62001-09-04 19:14:14 +00001159 start = lineno - 1 - context//2
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001160 try:
1161 lines, lnum = findsource(frame)
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02001162 except OSError:
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +00001163 lines = index = None
1164 else:
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001165 start = max(start, 1)
Raymond Hettingera0501712004-06-15 11:22:53 +00001166 start = max(0, min(start, len(lines) - context))
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001167 lines = lines[start:start+context]
Ka-Ping Yee59ade082001-03-01 03:55:35 +00001168 index = lineno - 1 - start
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001169 else:
1170 lines = index = None
1171
Christian Heimes25bb7832008-01-11 16:17:00 +00001172 return Traceback(filename, lineno, frame.f_code.co_name, lines, index)
Ka-Ping Yee59ade082001-03-01 03:55:35 +00001173
1174def getlineno(frame):
1175 """Get the line number from a frame object, allowing for optimization."""
Michael W. Hudsondd32a912002-08-15 14:59:02 +00001176 # FrameType.f_lineno is now a descriptor that grovels co_lnotab
1177 return frame.f_lineno
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001178
1179def getouterframes(frame, context=1):
1180 """Get a list of records for a frame and all higher (calling) frames.
1181
1182 Each record contains a frame object, filename, line number, function
1183 name, a list of lines of context, and index within the context."""
1184 framelist = []
1185 while frame:
1186 framelist.append((frame,) + getframeinfo(frame, context))
1187 frame = frame.f_back
1188 return framelist
1189
1190def getinnerframes(tb, context=1):
1191 """Get a list of records for a traceback's frame and all lower frames.
1192
1193 Each record contains a frame object, filename, line number, function
1194 name, a list of lines of context, and index within the context."""
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001195 framelist = []
1196 while tb:
1197 framelist.append((tb.tb_frame,) + getframeinfo(tb, context))
1198 tb = tb.tb_next
1199 return framelist
1200
Benjamin Peterson42ac4752010-08-09 13:05:35 +00001201def currentframe():
Benjamin Petersona3a3fc62010-08-09 15:49:56 +00001202 """Return the frame of the caller or None if this is not possible."""
Benjamin Peterson42ac4752010-08-09 13:05:35 +00001203 return sys._getframe(1) if hasattr(sys, "_getframe") else None
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001204
1205def stack(context=1):
1206 """Return a list of records for the stack above the caller's frame."""
Jeremy Hyltonab919022003-06-27 18:41:20 +00001207 return getouterframes(sys._getframe(1), context)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001208
1209def trace(context=1):
Tim Peters85ba6732001-02-28 08:26:44 +00001210 """Return a list of records for the stack below the current exception."""
Fred Draked451ec12002-04-26 02:29:55 +00001211 return getinnerframes(sys.exc_info()[2], context)
Michael Foord95fc51d2010-11-20 15:07:30 +00001212
1213
1214# ------------------------------------------------ static version of getattr
1215
1216_sentinel = object()
1217
Michael Foorde5162652010-11-20 16:40:44 +00001218def _static_getmro(klass):
1219 return type.__dict__['__mro__'].__get__(klass)
1220
Michael Foord95fc51d2010-11-20 15:07:30 +00001221def _check_instance(obj, attr):
1222 instance_dict = {}
1223 try:
1224 instance_dict = object.__getattribute__(obj, "__dict__")
1225 except AttributeError:
1226 pass
Michael Foorddcebe0f2011-03-15 19:20:44 -04001227 return dict.get(instance_dict, attr, _sentinel)
Michael Foord95fc51d2010-11-20 15:07:30 +00001228
1229
1230def _check_class(klass, attr):
Michael Foorde5162652010-11-20 16:40:44 +00001231 for entry in _static_getmro(klass):
Michael Foorda51623b2011-12-18 22:01:40 +00001232 if _shadowed_dict(type(entry)) is _sentinel:
Michael Foorddcebe0f2011-03-15 19:20:44 -04001233 try:
1234 return entry.__dict__[attr]
1235 except KeyError:
1236 pass
Michael Foord95fc51d2010-11-20 15:07:30 +00001237 return _sentinel
1238
Michael Foord35184ed2010-11-20 16:58:30 +00001239def _is_type(obj):
1240 try:
1241 _static_getmro(obj)
1242 except TypeError:
1243 return False
1244 return True
1245
Michael Foorddcebe0f2011-03-15 19:20:44 -04001246def _shadowed_dict(klass):
1247 dict_attr = type.__dict__["__dict__"]
1248 for entry in _static_getmro(klass):
1249 try:
1250 class_dict = dict_attr.__get__(entry)["__dict__"]
1251 except KeyError:
1252 pass
1253 else:
1254 if not (type(class_dict) is types.GetSetDescriptorType and
1255 class_dict.__name__ == "__dict__" and
1256 class_dict.__objclass__ is entry):
Michael Foorda51623b2011-12-18 22:01:40 +00001257 return class_dict
1258 return _sentinel
Michael Foord95fc51d2010-11-20 15:07:30 +00001259
1260def getattr_static(obj, attr, default=_sentinel):
1261 """Retrieve attributes without triggering dynamic lookup via the
1262 descriptor protocol, __getattr__ or __getattribute__.
1263
1264 Note: this function may not be able to retrieve all attributes
1265 that getattr can fetch (like dynamically created attributes)
1266 and may find attributes that getattr can't (like descriptors
1267 that raise AttributeError). It can also return descriptor objects
1268 instead of instance members in some cases. See the
1269 documentation for details.
1270 """
1271 instance_result = _sentinel
Michael Foord35184ed2010-11-20 16:58:30 +00001272 if not _is_type(obj):
Michael Foordcc7ebb82010-11-20 16:20:16 +00001273 klass = type(obj)
Michael Foorda51623b2011-12-18 22:01:40 +00001274 dict_attr = _shadowed_dict(klass)
1275 if (dict_attr is _sentinel or
1276 type(dict_attr) is types.MemberDescriptorType):
Michael Foorddcebe0f2011-03-15 19:20:44 -04001277 instance_result = _check_instance(obj, attr)
Michael Foord95fc51d2010-11-20 15:07:30 +00001278 else:
1279 klass = obj
1280
1281 klass_result = _check_class(klass, attr)
1282
1283 if instance_result is not _sentinel and klass_result is not _sentinel:
1284 if (_check_class(type(klass_result), '__get__') is not _sentinel and
1285 _check_class(type(klass_result), '__set__') is not _sentinel):
1286 return klass_result
1287
1288 if instance_result is not _sentinel:
1289 return instance_result
1290 if klass_result is not _sentinel:
1291 return klass_result
1292
1293 if obj is klass:
1294 # for types we check the metaclass too
Michael Foorde5162652010-11-20 16:40:44 +00001295 for entry in _static_getmro(type(klass)):
Michael Foord3ba95f82011-12-22 01:13:37 +00001296 if _shadowed_dict(type(entry)) is _sentinel:
1297 try:
1298 return entry.__dict__[attr]
1299 except KeyError:
1300 pass
Michael Foord95fc51d2010-11-20 15:07:30 +00001301 if default is not _sentinel:
1302 return default
1303 raise AttributeError(attr)
Nick Coghlane0f04652010-11-21 03:44:04 +00001304
1305
Nick Coghlan04e2e3f2012-06-23 19:52:05 +10001306# ------------------------------------------------ generator introspection
1307
Nick Coghlan7921b9f2010-11-30 06:36:04 +00001308GEN_CREATED = 'GEN_CREATED'
1309GEN_RUNNING = 'GEN_RUNNING'
1310GEN_SUSPENDED = 'GEN_SUSPENDED'
1311GEN_CLOSED = 'GEN_CLOSED'
Nick Coghlane0f04652010-11-21 03:44:04 +00001312
1313def getgeneratorstate(generator):
1314 """Get current state of a generator-iterator.
1315
1316 Possible states are:
1317 GEN_CREATED: Waiting to start execution.
1318 GEN_RUNNING: Currently being executed by the interpreter.
1319 GEN_SUSPENDED: Currently suspended at a yield expression.
1320 GEN_CLOSED: Execution has completed.
1321 """
1322 if generator.gi_running:
1323 return GEN_RUNNING
1324 if generator.gi_frame is None:
1325 return GEN_CLOSED
1326 if generator.gi_frame.f_lasti == -1:
1327 return GEN_CREATED
1328 return GEN_SUSPENDED
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07001329
1330
Nick Coghlan04e2e3f2012-06-23 19:52:05 +10001331def getgeneratorlocals(generator):
1332 """
1333 Get the mapping of generator local variables to their current values.
1334
1335 A dict is returned, with the keys the local variable names and values the
1336 bound values."""
1337
1338 if not isgenerator(generator):
1339 raise TypeError("'{!r}' is not a Python generator".format(generator))
1340
1341 frame = getattr(generator, "gi_frame", None)
1342 if frame is not None:
1343 return generator.gi_frame.f_locals
1344 else:
1345 return {}
1346
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07001347###############################################################################
1348### Function Signature Object (PEP 362)
1349###############################################################################
1350
1351
1352_WrapperDescriptor = type(type.__call__)
1353_MethodWrapper = type(all.__call__)
1354
1355_NonUserDefinedCallables = (_WrapperDescriptor,
1356 _MethodWrapper,
1357 types.BuiltinFunctionType)
1358
1359
1360def _get_user_defined_method(cls, method_name):
1361 try:
1362 meth = getattr(cls, method_name)
1363 except AttributeError:
1364 return
1365 else:
1366 if not isinstance(meth, _NonUserDefinedCallables):
1367 # Once '__signature__' will be added to 'C'-level
1368 # callables, this check won't be necessary
1369 return meth
1370
1371
1372def signature(obj):
1373 '''Get a signature object for the passed callable.'''
1374
1375 if not callable(obj):
1376 raise TypeError('{!r} is not a callable object'.format(obj))
1377
1378 if isinstance(obj, types.MethodType):
1379 # In this case we skip the first parameter of the underlying
1380 # function (usually `self` or `cls`).
1381 sig = signature(obj.__func__)
1382 return sig.replace(parameters=tuple(sig.parameters.values())[1:])
1383
Nick Coghlane8c45d62013-07-28 20:00:01 +10001384 # Was this function wrapped by a decorator?
1385 obj = unwrap(obj, stop=(lambda f: hasattr(f, "__signature__")))
1386
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07001387 try:
1388 sig = obj.__signature__
1389 except AttributeError:
1390 pass
1391 else:
1392 if sig is not None:
1393 return sig
1394
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07001395
1396 if isinstance(obj, types.FunctionType):
1397 return Signature.from_function(obj)
1398
1399 if isinstance(obj, functools.partial):
1400 sig = signature(obj.func)
1401
1402 new_params = OrderedDict(sig.parameters.items())
1403
1404 partial_args = obj.args or ()
1405 partial_keywords = obj.keywords or {}
1406 try:
1407 ba = sig.bind_partial(*partial_args, **partial_keywords)
1408 except TypeError as ex:
1409 msg = 'partial object {!r} has incorrect arguments'.format(obj)
1410 raise ValueError(msg) from ex
1411
1412 for arg_name, arg_value in ba.arguments.items():
1413 param = new_params[arg_name]
1414 if arg_name in partial_keywords:
1415 # We set a new default value, because the following code
1416 # is correct:
1417 #
1418 # >>> def foo(a): print(a)
1419 # >>> print(partial(partial(foo, a=10), a=20)())
1420 # 20
1421 # >>> print(partial(partial(foo, a=10), a=20)(a=30))
1422 # 30
1423 #
1424 # So, with 'partial' objects, passing a keyword argument is
1425 # like setting a new default value for the corresponding
1426 # parameter
1427 #
1428 # We also mark this parameter with '_partial_kwarg'
1429 # flag. Later, in '_bind', the 'default' value of this
1430 # parameter will be added to 'kwargs', to simulate
1431 # the 'functools.partial' real call.
1432 new_params[arg_name] = param.replace(default=arg_value,
1433 _partial_kwarg=True)
1434
1435 elif (param.kind not in (_VAR_KEYWORD, _VAR_POSITIONAL) and
1436 not param._partial_kwarg):
1437 new_params.pop(arg_name)
1438
1439 return sig.replace(parameters=new_params.values())
1440
1441 sig = None
1442 if isinstance(obj, type):
1443 # obj is a class or a metaclass
1444
1445 # First, let's see if it has an overloaded __call__ defined
1446 # in its metaclass
1447 call = _get_user_defined_method(type(obj), '__call__')
1448 if call is not None:
1449 sig = signature(call)
1450 else:
1451 # Now we check if the 'obj' class has a '__new__' method
1452 new = _get_user_defined_method(obj, '__new__')
1453 if new is not None:
1454 sig = signature(new)
1455 else:
1456 # Finally, we should have at least __init__ implemented
1457 init = _get_user_defined_method(obj, '__init__')
1458 if init is not None:
1459 sig = signature(init)
1460 elif not isinstance(obj, _NonUserDefinedCallables):
1461 # An object with __call__
1462 # We also check that the 'obj' is not an instance of
1463 # _WrapperDescriptor or _MethodWrapper to avoid
1464 # infinite recursion (and even potential segfault)
1465 call = _get_user_defined_method(type(obj), '__call__')
1466 if call is not None:
1467 sig = signature(call)
1468
1469 if sig is not None:
1470 # For classes and objects we skip the first parameter of their
1471 # __call__, __new__, or __init__ methods
1472 return sig.replace(parameters=tuple(sig.parameters.values())[1:])
1473
1474 if isinstance(obj, types.BuiltinFunctionType):
1475 # Raise a nicer error message for builtins
1476 msg = 'no signature found for builtin function {!r}'.format(obj)
1477 raise ValueError(msg)
1478
1479 raise ValueError('callable {!r} is not supported by signature'.format(obj))
1480
1481
1482class _void:
1483 '''A private marker - used in Parameter & Signature'''
1484
1485
1486class _empty:
1487 pass
1488
1489
1490class _ParameterKind(int):
1491 def __new__(self, *args, name):
1492 obj = int.__new__(self, *args)
1493 obj._name = name
1494 return obj
1495
1496 def __str__(self):
1497 return self._name
1498
1499 def __repr__(self):
1500 return '<_ParameterKind: {!r}>'.format(self._name)
1501
1502
1503_POSITIONAL_ONLY = _ParameterKind(0, name='POSITIONAL_ONLY')
1504_POSITIONAL_OR_KEYWORD = _ParameterKind(1, name='POSITIONAL_OR_KEYWORD')
1505_VAR_POSITIONAL = _ParameterKind(2, name='VAR_POSITIONAL')
1506_KEYWORD_ONLY = _ParameterKind(3, name='KEYWORD_ONLY')
1507_VAR_KEYWORD = _ParameterKind(4, name='VAR_KEYWORD')
1508
1509
1510class Parameter:
1511 '''Represents a parameter in a function signature.
1512
1513 Has the following public attributes:
1514
1515 * name : str
1516 The name of the parameter as a string.
1517 * default : object
1518 The default value for the parameter if specified. If the
1519 parameter has no default value, this attribute is not set.
1520 * annotation
1521 The annotation for the parameter if specified. If the
1522 parameter has no annotation, this attribute is not set.
1523 * kind : str
1524 Describes how argument values are bound to the parameter.
1525 Possible values: `Parameter.POSITIONAL_ONLY`,
1526 `Parameter.POSITIONAL_OR_KEYWORD`, `Parameter.VAR_POSITIONAL`,
1527 `Parameter.KEYWORD_ONLY`, `Parameter.VAR_KEYWORD`.
1528 '''
1529
1530 __slots__ = ('_name', '_kind', '_default', '_annotation', '_partial_kwarg')
1531
1532 POSITIONAL_ONLY = _POSITIONAL_ONLY
1533 POSITIONAL_OR_KEYWORD = _POSITIONAL_OR_KEYWORD
1534 VAR_POSITIONAL = _VAR_POSITIONAL
1535 KEYWORD_ONLY = _KEYWORD_ONLY
1536 VAR_KEYWORD = _VAR_KEYWORD
1537
1538 empty = _empty
1539
1540 def __init__(self, name, kind, *, default=_empty, annotation=_empty,
1541 _partial_kwarg=False):
1542
1543 if kind not in (_POSITIONAL_ONLY, _POSITIONAL_OR_KEYWORD,
1544 _VAR_POSITIONAL, _KEYWORD_ONLY, _VAR_KEYWORD):
1545 raise ValueError("invalid value for 'Parameter.kind' attribute")
1546 self._kind = kind
1547
1548 if default is not _empty:
1549 if kind in (_VAR_POSITIONAL, _VAR_KEYWORD):
1550 msg = '{} parameters cannot have default values'.format(kind)
1551 raise ValueError(msg)
1552 self._default = default
1553 self._annotation = annotation
1554
1555 if name is None:
1556 if kind != _POSITIONAL_ONLY:
1557 raise ValueError("None is not a valid name for a "
1558 "non-positional-only parameter")
1559 self._name = name
1560 else:
1561 name = str(name)
1562 if kind != _POSITIONAL_ONLY and not name.isidentifier():
1563 msg = '{!r} is not a valid parameter name'.format(name)
1564 raise ValueError(msg)
1565 self._name = name
1566
1567 self._partial_kwarg = _partial_kwarg
1568
1569 @property
1570 def name(self):
1571 return self._name
1572
1573 @property
1574 def default(self):
1575 return self._default
1576
1577 @property
1578 def annotation(self):
1579 return self._annotation
1580
1581 @property
1582 def kind(self):
1583 return self._kind
1584
1585 def replace(self, *, name=_void, kind=_void, annotation=_void,
1586 default=_void, _partial_kwarg=_void):
1587 '''Creates a customized copy of the Parameter.'''
1588
1589 if name is _void:
1590 name = self._name
1591
1592 if kind is _void:
1593 kind = self._kind
1594
1595 if annotation is _void:
1596 annotation = self._annotation
1597
1598 if default is _void:
1599 default = self._default
1600
1601 if _partial_kwarg is _void:
1602 _partial_kwarg = self._partial_kwarg
1603
1604 return type(self)(name, kind, default=default, annotation=annotation,
1605 _partial_kwarg=_partial_kwarg)
1606
1607 def __str__(self):
1608 kind = self.kind
1609
1610 formatted = self._name
1611 if kind == _POSITIONAL_ONLY:
1612 if formatted is None:
1613 formatted = ''
1614 formatted = '<{}>'.format(formatted)
1615
1616 # Add annotation and default value
1617 if self._annotation is not _empty:
1618 formatted = '{}:{}'.format(formatted,
1619 formatannotation(self._annotation))
1620
1621 if self._default is not _empty:
1622 formatted = '{}={}'.format(formatted, repr(self._default))
1623
1624 if kind == _VAR_POSITIONAL:
1625 formatted = '*' + formatted
1626 elif kind == _VAR_KEYWORD:
1627 formatted = '**' + formatted
1628
1629 return formatted
1630
1631 def __repr__(self):
1632 return '<{} at {:#x} {!r}>'.format(self.__class__.__name__,
1633 id(self), self.name)
1634
1635 def __eq__(self, other):
1636 return (issubclass(other.__class__, Parameter) and
1637 self._name == other._name and
1638 self._kind == other._kind and
1639 self._default == other._default and
1640 self._annotation == other._annotation)
1641
1642 def __ne__(self, other):
1643 return not self.__eq__(other)
1644
1645
1646class BoundArguments:
1647 '''Result of `Signature.bind` call. Holds the mapping of arguments
1648 to the function's parameters.
1649
1650 Has the following public attributes:
1651
1652 * arguments : OrderedDict
1653 An ordered mutable mapping of parameters' names to arguments' values.
1654 Does not contain arguments' default values.
1655 * signature : Signature
1656 The Signature object that created this instance.
1657 * args : tuple
1658 Tuple of positional arguments values.
1659 * kwargs : dict
1660 Dict of keyword arguments values.
1661 '''
1662
1663 def __init__(self, signature, arguments):
1664 self.arguments = arguments
1665 self._signature = signature
1666
1667 @property
1668 def signature(self):
1669 return self._signature
1670
1671 @property
1672 def args(self):
1673 args = []
1674 for param_name, param in self._signature.parameters.items():
1675 if (param.kind in (_VAR_KEYWORD, _KEYWORD_ONLY) or
1676 param._partial_kwarg):
1677 # Keyword arguments mapped by 'functools.partial'
1678 # (Parameter._partial_kwarg is True) are mapped
1679 # in 'BoundArguments.kwargs', along with VAR_KEYWORD &
1680 # KEYWORD_ONLY
1681 break
1682
1683 try:
1684 arg = self.arguments[param_name]
1685 except KeyError:
1686 # We're done here. Other arguments
1687 # will be mapped in 'BoundArguments.kwargs'
1688 break
1689 else:
1690 if param.kind == _VAR_POSITIONAL:
1691 # *args
1692 args.extend(arg)
1693 else:
1694 # plain argument
1695 args.append(arg)
1696
1697 return tuple(args)
1698
1699 @property
1700 def kwargs(self):
1701 kwargs = {}
1702 kwargs_started = False
1703 for param_name, param in self._signature.parameters.items():
1704 if not kwargs_started:
1705 if (param.kind in (_VAR_KEYWORD, _KEYWORD_ONLY) or
1706 param._partial_kwarg):
1707 kwargs_started = True
1708 else:
1709 if param_name not in self.arguments:
1710 kwargs_started = True
1711 continue
1712
1713 if not kwargs_started:
1714 continue
1715
1716 try:
1717 arg = self.arguments[param_name]
1718 except KeyError:
1719 pass
1720 else:
1721 if param.kind == _VAR_KEYWORD:
1722 # **kwargs
1723 kwargs.update(arg)
1724 else:
1725 # plain keyword argument
1726 kwargs[param_name] = arg
1727
1728 return kwargs
1729
1730 def __eq__(self, other):
1731 return (issubclass(other.__class__, BoundArguments) and
1732 self.signature == other.signature and
1733 self.arguments == other.arguments)
1734
1735 def __ne__(self, other):
1736 return not self.__eq__(other)
1737
1738
1739class Signature:
1740 '''A Signature object represents the overall signature of a function.
1741 It stores a Parameter object for each parameter accepted by the
1742 function, as well as information specific to the function itself.
1743
1744 A Signature object has the following public attributes and methods:
1745
1746 * parameters : OrderedDict
1747 An ordered mapping of parameters' names to the corresponding
1748 Parameter objects (keyword-only arguments are in the same order
1749 as listed in `code.co_varnames`).
1750 * return_annotation : object
1751 The annotation for the return type of the function if specified.
1752 If the function has no annotation for its return type, this
1753 attribute is not set.
1754 * bind(*args, **kwargs) -> BoundArguments
1755 Creates a mapping from positional and keyword arguments to
1756 parameters.
1757 * bind_partial(*args, **kwargs) -> BoundArguments
1758 Creates a partial mapping from positional and keyword arguments
1759 to parameters (simulating 'functools.partial' behavior.)
1760 '''
1761
1762 __slots__ = ('_return_annotation', '_parameters')
1763
1764 _parameter_cls = Parameter
1765 _bound_arguments_cls = BoundArguments
1766
1767 empty = _empty
1768
1769 def __init__(self, parameters=None, *, return_annotation=_empty,
1770 __validate_parameters__=True):
1771 '''Constructs Signature from the given list of Parameter
1772 objects and 'return_annotation'. All arguments are optional.
1773 '''
1774
1775 if parameters is None:
1776 params = OrderedDict()
1777 else:
1778 if __validate_parameters__:
1779 params = OrderedDict()
1780 top_kind = _POSITIONAL_ONLY
1781
1782 for idx, param in enumerate(parameters):
1783 kind = param.kind
1784 if kind < top_kind:
1785 msg = 'wrong parameter order: {} before {}'
1786 msg = msg.format(top_kind, param.kind)
1787 raise ValueError(msg)
1788 else:
1789 top_kind = kind
1790
1791 name = param.name
1792 if name is None:
1793 name = str(idx)
1794 param = param.replace(name=name)
1795
1796 if name in params:
1797 msg = 'duplicate parameter name: {!r}'.format(name)
1798 raise ValueError(msg)
1799 params[name] = param
1800 else:
1801 params = OrderedDict(((param.name, param)
1802 for param in parameters))
1803
1804 self._parameters = types.MappingProxyType(params)
1805 self._return_annotation = return_annotation
1806
1807 @classmethod
1808 def from_function(cls, func):
1809 '''Constructs Signature for the given python function'''
1810
1811 if not isinstance(func, types.FunctionType):
1812 raise TypeError('{!r} is not a Python function'.format(func))
1813
1814 Parameter = cls._parameter_cls
1815
1816 # Parameter information.
1817 func_code = func.__code__
1818 pos_count = func_code.co_argcount
1819 arg_names = func_code.co_varnames
1820 positional = tuple(arg_names[:pos_count])
1821 keyword_only_count = func_code.co_kwonlyargcount
1822 keyword_only = arg_names[pos_count:(pos_count + keyword_only_count)]
1823 annotations = func.__annotations__
1824 defaults = func.__defaults__
1825 kwdefaults = func.__kwdefaults__
1826
1827 if defaults:
1828 pos_default_count = len(defaults)
1829 else:
1830 pos_default_count = 0
1831
1832 parameters = []
1833
1834 # Non-keyword-only parameters w/o defaults.
1835 non_default_count = pos_count - pos_default_count
1836 for name in positional[:non_default_count]:
1837 annotation = annotations.get(name, _empty)
1838 parameters.append(Parameter(name, annotation=annotation,
1839 kind=_POSITIONAL_OR_KEYWORD))
1840
1841 # ... w/ defaults.
1842 for offset, name in enumerate(positional[non_default_count:]):
1843 annotation = annotations.get(name, _empty)
1844 parameters.append(Parameter(name, annotation=annotation,
1845 kind=_POSITIONAL_OR_KEYWORD,
1846 default=defaults[offset]))
1847
1848 # *args
1849 if func_code.co_flags & 0x04:
1850 name = arg_names[pos_count + keyword_only_count]
1851 annotation = annotations.get(name, _empty)
1852 parameters.append(Parameter(name, annotation=annotation,
1853 kind=_VAR_POSITIONAL))
1854
1855 # Keyword-only parameters.
1856 for name in keyword_only:
1857 default = _empty
1858 if kwdefaults is not None:
1859 default = kwdefaults.get(name, _empty)
1860
1861 annotation = annotations.get(name, _empty)
1862 parameters.append(Parameter(name, annotation=annotation,
1863 kind=_KEYWORD_ONLY,
1864 default=default))
1865 # **kwargs
1866 if func_code.co_flags & 0x08:
1867 index = pos_count + keyword_only_count
1868 if func_code.co_flags & 0x04:
1869 index += 1
1870
1871 name = arg_names[index]
1872 annotation = annotations.get(name, _empty)
1873 parameters.append(Parameter(name, annotation=annotation,
1874 kind=_VAR_KEYWORD))
1875
1876 return cls(parameters,
1877 return_annotation=annotations.get('return', _empty),
1878 __validate_parameters__=False)
1879
1880 @property
1881 def parameters(self):
1882 return self._parameters
1883
1884 @property
1885 def return_annotation(self):
1886 return self._return_annotation
1887
1888 def replace(self, *, parameters=_void, return_annotation=_void):
1889 '''Creates a customized copy of the Signature.
1890 Pass 'parameters' and/or 'return_annotation' arguments
1891 to override them in the new copy.
1892 '''
1893
1894 if parameters is _void:
1895 parameters = self.parameters.values()
1896
1897 if return_annotation is _void:
1898 return_annotation = self._return_annotation
1899
1900 return type(self)(parameters,
1901 return_annotation=return_annotation)
1902
1903 def __eq__(self, other):
1904 if (not issubclass(type(other), Signature) or
1905 self.return_annotation != other.return_annotation or
1906 len(self.parameters) != len(other.parameters)):
1907 return False
1908
1909 other_positions = {param: idx
1910 for idx, param in enumerate(other.parameters.keys())}
1911
1912 for idx, (param_name, param) in enumerate(self.parameters.items()):
1913 if param.kind == _KEYWORD_ONLY:
1914 try:
1915 other_param = other.parameters[param_name]
1916 except KeyError:
1917 return False
1918 else:
1919 if param != other_param:
1920 return False
1921 else:
1922 try:
1923 other_idx = other_positions[param_name]
1924 except KeyError:
1925 return False
1926 else:
1927 if (idx != other_idx or
1928 param != other.parameters[param_name]):
1929 return False
1930
1931 return True
1932
1933 def __ne__(self, other):
1934 return not self.__eq__(other)
1935
1936 def _bind(self, args, kwargs, *, partial=False):
1937 '''Private method. Don't use directly.'''
1938
1939 arguments = OrderedDict()
1940
1941 parameters = iter(self.parameters.values())
1942 parameters_ex = ()
1943 arg_vals = iter(args)
1944
1945 if partial:
1946 # Support for binding arguments to 'functools.partial' objects.
1947 # See 'functools.partial' case in 'signature()' implementation
1948 # for details.
1949 for param_name, param in self.parameters.items():
1950 if (param._partial_kwarg and param_name not in kwargs):
1951 # Simulating 'functools.partial' behavior
1952 kwargs[param_name] = param.default
1953
1954 while True:
1955 # Let's iterate through the positional arguments and corresponding
1956 # parameters
1957 try:
1958 arg_val = next(arg_vals)
1959 except StopIteration:
1960 # No more positional arguments
1961 try:
1962 param = next(parameters)
1963 except StopIteration:
1964 # No more parameters. That's it. Just need to check that
1965 # we have no `kwargs` after this while loop
1966 break
1967 else:
1968 if param.kind == _VAR_POSITIONAL:
1969 # That's OK, just empty *args. Let's start parsing
1970 # kwargs
1971 break
1972 elif param.name in kwargs:
1973 if param.kind == _POSITIONAL_ONLY:
1974 msg = '{arg!r} parameter is positional only, ' \
1975 'but was passed as a keyword'
1976 msg = msg.format(arg=param.name)
1977 raise TypeError(msg) from None
1978 parameters_ex = (param,)
1979 break
1980 elif (param.kind == _VAR_KEYWORD or
1981 param.default is not _empty):
1982 # That's fine too - we have a default value for this
1983 # parameter. So, lets start parsing `kwargs`, starting
1984 # with the current parameter
1985 parameters_ex = (param,)
1986 break
1987 else:
1988 if partial:
1989 parameters_ex = (param,)
1990 break
1991 else:
1992 msg = '{arg!r} parameter lacking default value'
1993 msg = msg.format(arg=param.name)
1994 raise TypeError(msg) from None
1995 else:
1996 # We have a positional argument to process
1997 try:
1998 param = next(parameters)
1999 except StopIteration:
2000 raise TypeError('too many positional arguments') from None
2001 else:
2002 if param.kind in (_VAR_KEYWORD, _KEYWORD_ONLY):
2003 # Looks like we have no parameter for this positional
2004 # argument
2005 raise TypeError('too many positional arguments')
2006
2007 if param.kind == _VAR_POSITIONAL:
2008 # We have an '*args'-like argument, let's fill it with
2009 # all positional arguments we have left and move on to
2010 # the next phase
2011 values = [arg_val]
2012 values.extend(arg_vals)
2013 arguments[param.name] = tuple(values)
2014 break
2015
2016 if param.name in kwargs:
2017 raise TypeError('multiple values for argument '
2018 '{arg!r}'.format(arg=param.name))
2019
2020 arguments[param.name] = arg_val
2021
2022 # Now, we iterate through the remaining parameters to process
2023 # keyword arguments
2024 kwargs_param = None
2025 for param in itertools.chain(parameters_ex, parameters):
2026 if param.kind == _POSITIONAL_ONLY:
2027 # This should never happen in case of a properly built
2028 # Signature object (but let's have this check here
2029 # to ensure correct behaviour just in case)
2030 raise TypeError('{arg!r} parameter is positional only, '
2031 'but was passed as a keyword'. \
2032 format(arg=param.name))
2033
2034 if param.kind == _VAR_KEYWORD:
2035 # Memorize that we have a '**kwargs'-like parameter
2036 kwargs_param = param
2037 continue
2038
2039 param_name = param.name
2040 try:
2041 arg_val = kwargs.pop(param_name)
2042 except KeyError:
2043 # We have no value for this parameter. It's fine though,
2044 # if it has a default value, or it is an '*args'-like
2045 # parameter, left alone by the processing of positional
2046 # arguments.
2047 if (not partial and param.kind != _VAR_POSITIONAL and
2048 param.default is _empty):
2049 raise TypeError('{arg!r} parameter lacking default value'. \
2050 format(arg=param_name)) from None
2051
2052 else:
2053 arguments[param_name] = arg_val
2054
2055 if kwargs:
2056 if kwargs_param is not None:
2057 # Process our '**kwargs'-like parameter
2058 arguments[kwargs_param.name] = kwargs
2059 else:
2060 raise TypeError('too many keyword arguments')
2061
2062 return self._bound_arguments_cls(self, arguments)
2063
Antoine Pitroubd41d1b2013-01-29 21:20:57 +01002064 def bind(__bind_self, *args, **kwargs):
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002065 '''Get a BoundArguments object, that maps the passed `args`
2066 and `kwargs` to the function's signature. Raises `TypeError`
2067 if the passed arguments can not be bound.
2068 '''
Antoine Pitroubd41d1b2013-01-29 21:20:57 +01002069 return __bind_self._bind(args, kwargs)
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002070
Antoine Pitroubd41d1b2013-01-29 21:20:57 +01002071 def bind_partial(__bind_self, *args, **kwargs):
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002072 '''Get a BoundArguments object, that partially maps the
2073 passed `args` and `kwargs` to the function's signature.
2074 Raises `TypeError` if the passed arguments can not be bound.
2075 '''
Antoine Pitroubd41d1b2013-01-29 21:20:57 +01002076 return __bind_self._bind(args, kwargs, partial=True)
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002077
2078 def __str__(self):
2079 result = []
2080 render_kw_only_separator = True
2081 for idx, param in enumerate(self.parameters.values()):
2082 formatted = str(param)
2083
2084 kind = param.kind
2085 if kind == _VAR_POSITIONAL:
2086 # OK, we have an '*args'-like parameter, so we won't need
2087 # a '*' to separate keyword-only arguments
2088 render_kw_only_separator = False
2089 elif kind == _KEYWORD_ONLY and render_kw_only_separator:
2090 # We have a keyword-only parameter to render and we haven't
2091 # rendered an '*args'-like parameter before, so add a '*'
2092 # separator to the parameters list ("foo(arg1, *, arg2)" case)
2093 result.append('*')
2094 # This condition should be only triggered once, so
2095 # reset the flag
2096 render_kw_only_separator = False
2097
2098 result.append(formatted)
2099
2100 rendered = '({})'.format(', '.join(result))
2101
2102 if self.return_annotation is not _empty:
2103 anno = formatannotation(self.return_annotation)
2104 rendered += ' -> {}'.format(anno)
2105
2106 return rendered