blob: 195c9fdd67285915dc5ff3e33d7b1342c64fca72 [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
50# back to hardcording so the dependency is optional
51try:
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:
187 __iter__ defined to support interation over container
188 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] = []
792 children[parent].append(c)
793 if unique and parent in classes: break
794 elif c not in roots:
795 roots.append(c)
Raymond Hettingere0d49722002-06-02 18:55:56 +0000796 for parent in children:
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000797 if parent not in classes:
798 roots.append(parent)
799 return walktree(roots, children, None)
800
801# ------------------------------------------------ argument list extraction
Christian Heimes25bb7832008-01-11 16:17:00 +0000802Arguments = namedtuple('Arguments', 'args, varargs, varkw')
803
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000804def getargs(co):
805 """Get information about the arguments accepted by a code object.
806
Guido van Rossum2e65f892007-02-28 22:03:49 +0000807 Three things are returned: (args, varargs, varkw), where
Georg Brandlc1c4bf82010-10-15 16:07:41 +0000808 'args' is the list of argument names. Keyword-only arguments are
809 appended. 'varargs' and 'varkw' are the names of the * and **
810 arguments or None."""
Guido van Rossum2e65f892007-02-28 22:03:49 +0000811 args, varargs, kwonlyargs, varkw = _getfullargs(co)
Christian Heimes25bb7832008-01-11 16:17:00 +0000812 return Arguments(args + kwonlyargs, varargs, varkw)
Guido van Rossum2e65f892007-02-28 22:03:49 +0000813
814def _getfullargs(co):
815 """Get information about the arguments accepted by a code object.
816
817 Four things are returned: (args, varargs, kwonlyargs, varkw), where
Georg Brandlc1c4bf82010-10-15 16:07:41 +0000818 'args' and 'kwonlyargs' are lists of argument names, and 'varargs'
819 and 'varkw' are the names of the * and ** arguments or None."""
Jeremy Hylton64967882003-06-27 18:14:39 +0000820
821 if not iscode(co):
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +0000822 raise TypeError('{!r} is not a code object'.format(co))
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000823
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000824 nargs = co.co_argcount
825 names = co.co_varnames
Guido van Rossum2e65f892007-02-28 22:03:49 +0000826 nkwargs = co.co_kwonlyargcount
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000827 args = list(names[:nargs])
Guido van Rossum2e65f892007-02-28 22:03:49 +0000828 kwonlyargs = list(names[nargs:nargs+nkwargs])
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000829 step = 0
830
Guido van Rossum2e65f892007-02-28 22:03:49 +0000831 nargs += nkwargs
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000832 varargs = None
833 if co.co_flags & CO_VARARGS:
834 varargs = co.co_varnames[nargs]
835 nargs = nargs + 1
836 varkw = None
837 if co.co_flags & CO_VARKEYWORDS:
838 varkw = co.co_varnames[nargs]
Guido van Rossum2e65f892007-02-28 22:03:49 +0000839 return args, varargs, kwonlyargs, varkw
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000840
Christian Heimes25bb7832008-01-11 16:17:00 +0000841
842ArgSpec = namedtuple('ArgSpec', 'args varargs keywords defaults')
843
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000844def getargspec(func):
845 """Get the names and default values of a function's arguments.
846
847 A tuple of four things is returned: (args, varargs, varkw, defaults).
Georg Brandlc1c4bf82010-10-15 16:07:41 +0000848 'args' is a list of the argument names.
Guido van Rossum2e65f892007-02-28 22:03:49 +0000849 'args' will include keyword-only argument names.
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000850 'varargs' and 'varkw' are the names of the * and ** arguments or None.
Jeremy Hylton64967882003-06-27 18:14:39 +0000851 'defaults' is an n-tuple of the default values of the last n arguments.
Guido van Rossuma8add0e2007-05-14 22:03:55 +0000852
Guido van Rossum2e65f892007-02-28 22:03:49 +0000853 Use the getfullargspec() API for Python-3000 code, as annotations
854 and keyword arguments are supported. getargspec() will raise ValueError
855 if the func has either annotations or keyword arguments.
856 """
857
858 args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults, ann = \
859 getfullargspec(func)
860 if kwonlyargs or ann:
Collin Winterce36ad82007-08-30 01:19:48 +0000861 raise ValueError("Function has keyword-only arguments or annotations"
862 ", use getfullargspec() API which can support them")
Christian Heimes25bb7832008-01-11 16:17:00 +0000863 return ArgSpec(args, varargs, varkw, defaults)
864
865FullArgSpec = namedtuple('FullArgSpec',
Benjamin Peterson3d4ca742008-11-12 21:39:01 +0000866 'args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults, annotations')
Guido van Rossum2e65f892007-02-28 22:03:49 +0000867
868def getfullargspec(func):
869 """Get the names and default values of a function's arguments.
870
Brett Cannon504d8852007-09-07 02:12:14 +0000871 A tuple of seven things is returned:
872 (args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults annotations).
Georg Brandlc1c4bf82010-10-15 16:07:41 +0000873 'args' is a list of the argument names.
Guido van Rossum2e65f892007-02-28 22:03:49 +0000874 'varargs' and 'varkw' are the names of the * and ** arguments or None.
875 'defaults' is an n-tuple of the default values of the last n arguments.
876 'kwonlyargs' is a list of keyword-only argument names.
877 'kwonlydefaults' is a dictionary mapping names from kwonlyargs to defaults.
878 'annotations' is a dictionary mapping argument names to annotations.
Guido van Rossuma8add0e2007-05-14 22:03:55 +0000879
Guido van Rossum2e65f892007-02-28 22:03:49 +0000880 The first four items in the tuple correspond to getargspec().
Jeremy Hylton64967882003-06-27 18:14:39 +0000881 """
882
883 if ismethod(func):
Christian Heimesff737952007-11-27 10:40:20 +0000884 func = func.__func__
Jeremy Hylton64967882003-06-27 18:14:39 +0000885 if not isfunction(func):
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +0000886 raise TypeError('{!r} is not a Python function'.format(func))
Guido van Rossum2e65f892007-02-28 22:03:49 +0000887 args, varargs, kwonlyargs, varkw = _getfullargs(func.__code__)
Christian Heimes25bb7832008-01-11 16:17:00 +0000888 return FullArgSpec(args, varargs, varkw, func.__defaults__,
Guido van Rossum2e65f892007-02-28 22:03:49 +0000889 kwonlyargs, func.__kwdefaults__, func.__annotations__)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000890
Christian Heimes25bb7832008-01-11 16:17:00 +0000891ArgInfo = namedtuple('ArgInfo', 'args varargs keywords locals')
892
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000893def getargvalues(frame):
894 """Get information about arguments passed into a particular frame.
895
896 A tuple of four things is returned: (args, varargs, varkw, locals).
Georg Brandlc1c4bf82010-10-15 16:07:41 +0000897 'args' is a list of the argument names.
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000898 'varargs' and 'varkw' are the names of the * and ** arguments or None.
899 'locals' is the locals dictionary of the given frame."""
900 args, varargs, varkw = getargs(frame.f_code)
Benjamin Peterson1a6e0d02008-10-25 15:49:17 +0000901 return ArgInfo(args, varargs, varkw, frame.f_locals)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000902
Guido van Rossum2e65f892007-02-28 22:03:49 +0000903def formatannotation(annotation, base_module=None):
904 if isinstance(annotation, type):
Georg Brandl1a3284e2007-12-02 09:40:06 +0000905 if annotation.__module__ in ('builtins', base_module):
Guido van Rossum2e65f892007-02-28 22:03:49 +0000906 return annotation.__name__
907 return annotation.__module__+'.'+annotation.__name__
908 return repr(annotation)
Guido van Rossuma8add0e2007-05-14 22:03:55 +0000909
Guido van Rossum2e65f892007-02-28 22:03:49 +0000910def formatannotationrelativeto(object):
Guido van Rossuma8add0e2007-05-14 22:03:55 +0000911 module = getattr(object, '__module__', None)
912 def _formatannotation(annotation):
913 return formatannotation(annotation, module)
914 return _formatannotation
Guido van Rossum2e65f892007-02-28 22:03:49 +0000915
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000916def formatargspec(args, varargs=None, varkw=None, defaults=None,
Guido van Rossum2e65f892007-02-28 22:03:49 +0000917 kwonlyargs=(), kwonlydefaults={}, annotations={},
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000918 formatarg=str,
919 formatvarargs=lambda name: '*' + name,
920 formatvarkw=lambda name: '**' + name,
921 formatvalue=lambda value: '=' + repr(value),
Guido van Rossum2e65f892007-02-28 22:03:49 +0000922 formatreturns=lambda text: ' -> ' + text,
Georg Brandlc1c4bf82010-10-15 16:07:41 +0000923 formatannotation=formatannotation):
Guido van Rossuma8add0e2007-05-14 22:03:55 +0000924 """Format an argument spec from the values returned by getargspec
Guido van Rossum2e65f892007-02-28 22:03:49 +0000925 or getfullargspec.
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000926
Guido van Rossum2e65f892007-02-28 22:03:49 +0000927 The first seven arguments are (args, varargs, varkw, defaults,
928 kwonlyargs, kwonlydefaults, annotations). The other five arguments
929 are the corresponding optional formatting functions that are called to
930 turn names and values into strings. The last argument is an optional
931 function to format the sequence of arguments."""
932 def formatargandannotation(arg):
933 result = formatarg(arg)
934 if arg in annotations:
935 result += ': ' + formatannotation(annotations[arg])
936 return result
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000937 specs = []
938 if defaults:
939 firstdefault = len(args) - len(defaults)
Benjamin Petersonb58dda72009-01-18 22:27:04 +0000940 for i, arg in enumerate(args):
Georg Brandlc1c4bf82010-10-15 16:07:41 +0000941 spec = formatargandannotation(arg)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000942 if defaults and i >= firstdefault:
943 spec = spec + formatvalue(defaults[i - firstdefault])
944 specs.append(spec)
Raymond Hettinger936654b2002-06-01 03:06:31 +0000945 if varargs is not None:
Guido van Rossum2e65f892007-02-28 22:03:49 +0000946 specs.append(formatvarargs(formatargandannotation(varargs)))
947 else:
948 if kwonlyargs:
949 specs.append('*')
950 if kwonlyargs:
951 for kwonlyarg in kwonlyargs:
952 spec = formatargandannotation(kwonlyarg)
Benjamin Peterson9953a8d2009-01-17 04:15:01 +0000953 if kwonlydefaults and kwonlyarg in kwonlydefaults:
Guido van Rossum2e65f892007-02-28 22:03:49 +0000954 spec += formatvalue(kwonlydefaults[kwonlyarg])
955 specs.append(spec)
Raymond Hettinger936654b2002-06-01 03:06:31 +0000956 if varkw is not None:
Guido van Rossum2e65f892007-02-28 22:03:49 +0000957 specs.append(formatvarkw(formatargandannotation(varkw)))
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000958 result = '(' + ', '.join(specs) + ')'
Guido van Rossum2e65f892007-02-28 22:03:49 +0000959 if 'return' in annotations:
960 result += formatreturns(formatannotation(annotations['return']))
961 return result
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000962
963def formatargvalues(args, varargs, varkw, locals,
964 formatarg=str,
965 formatvarargs=lambda name: '*' + name,
966 formatvarkw=lambda name: '**' + name,
Georg Brandlc1c4bf82010-10-15 16:07:41 +0000967 formatvalue=lambda value: '=' + repr(value)):
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000968 """Format an argument spec from the 4 values returned by getargvalues.
969
970 The first four arguments are (args, varargs, varkw, locals). The
971 next four arguments are the corresponding optional formatting functions
972 that are called to turn names and values into strings. The ninth
973 argument is an optional function to format the sequence of arguments."""
974 def convert(name, locals=locals,
975 formatarg=formatarg, formatvalue=formatvalue):
976 return formatarg(name) + formatvalue(locals[name])
977 specs = []
978 for i in range(len(args)):
Georg Brandlc1c4bf82010-10-15 16:07:41 +0000979 specs.append(convert(args[i]))
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000980 if varargs:
981 specs.append(formatvarargs(varargs) + formatvalue(locals[varargs]))
982 if varkw:
983 specs.append(formatvarkw(varkw) + formatvalue(locals[varkw]))
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000984 return '(' + ', '.join(specs) + ')'
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000985
Benjamin Petersone109c702011-06-24 09:37:26 -0500986def _missing_arguments(f_name, argnames, pos, values):
987 names = [repr(name) for name in argnames if name not in values]
988 missing = len(names)
989 if missing == 1:
990 s = names[0]
991 elif missing == 2:
992 s = "{} and {}".format(*names)
993 else:
994 tail = ", {} and {}".format(names[-2:])
995 del names[-2:]
996 s = ", ".join(names) + tail
997 raise TypeError("%s() missing %i required %s argument%s: %s" %
998 (f_name, missing,
999 "positional" if pos else "keyword-only",
1000 "" if missing == 1 else "s", s))
1001
1002def _too_many(f_name, args, kwonly, varargs, defcount, given, values):
Benjamin Petersonb204a422011-06-05 22:04:07 -05001003 atleast = len(args) - defcount
Benjamin Petersonb204a422011-06-05 22:04:07 -05001004 kwonly_given = len([arg for arg in kwonly if arg in values])
1005 if varargs:
1006 plural = atleast != 1
1007 sig = "at least %d" % (atleast,)
1008 elif defcount:
1009 plural = True
1010 sig = "from %d to %d" % (atleast, len(args))
1011 else:
1012 plural = len(args) != 1
1013 sig = str(len(args))
1014 kwonly_sig = ""
1015 if kwonly_given:
1016 msg = " positional argument%s (and %d keyword-only argument%s)"
1017 kwonly_sig = (msg % ("s" if given != 1 else "", kwonly_given,
1018 "s" if kwonly_given != 1 else ""))
1019 raise TypeError("%s() takes %s positional argument%s but %d%s %s given" %
1020 (f_name, sig, "s" if plural else "", given, kwonly_sig,
1021 "was" if given == 1 and not kwonly_given else "were"))
1022
Benjamin Peterson25cd7eb2010-03-30 18:42:32 +00001023def getcallargs(func, *positional, **named):
1024 """Get the mapping of arguments to values.
1025
1026 A dict is returned, with keys the function argument names (including the
1027 names of the * and ** arguments, if any), and values the respective bound
1028 values from 'positional' and 'named'."""
1029 spec = getfullargspec(func)
1030 args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults, ann = spec
1031 f_name = func.__name__
1032 arg2value = {}
1033
Benjamin Petersonb204a422011-06-05 22:04:07 -05001034
Benjamin Peterson25cd7eb2010-03-30 18:42:32 +00001035 if ismethod(func) and func.__self__ is not None:
1036 # implicit 'self' (or 'cls' for classmethods) argument
1037 positional = (func.__self__,) + positional
1038 num_pos = len(positional)
Benjamin Peterson25cd7eb2010-03-30 18:42:32 +00001039 num_args = len(args)
1040 num_defaults = len(defaults) if defaults else 0
Benjamin Peterson25cd7eb2010-03-30 18:42:32 +00001041
Benjamin Petersonb204a422011-06-05 22:04:07 -05001042 n = min(num_pos, num_args)
1043 for i in range(n):
1044 arg2value[args[i]] = positional[i]
1045 if varargs:
1046 arg2value[varargs] = tuple(positional[n:])
1047 possible_kwargs = set(args + kwonlyargs)
Benjamin Peterson25cd7eb2010-03-30 18:42:32 +00001048 if varkw:
Benjamin Petersonb204a422011-06-05 22:04:07 -05001049 arg2value[varkw] = {}
1050 for kw, value in named.items():
1051 if kw not in possible_kwargs:
1052 if not varkw:
1053 raise TypeError("%s() got an unexpected keyword argument %r" %
1054 (f_name, kw))
1055 arg2value[varkw][kw] = value
1056 continue
1057 if kw in arg2value:
1058 raise TypeError("%s() got multiple values for argument %r" %
1059 (f_name, kw))
1060 arg2value[kw] = value
1061 if num_pos > num_args and not varargs:
Benjamin Petersone109c702011-06-24 09:37:26 -05001062 _too_many(f_name, args, kwonlyargs, varargs, num_defaults,
1063 num_pos, arg2value)
Benjamin Petersonb204a422011-06-05 22:04:07 -05001064 if num_pos < num_args:
Benjamin Petersone109c702011-06-24 09:37:26 -05001065 req = args[:num_args - num_defaults]
1066 for arg in req:
Benjamin Petersonb204a422011-06-05 22:04:07 -05001067 if arg not in arg2value:
Benjamin Petersone109c702011-06-24 09:37:26 -05001068 _missing_arguments(f_name, req, True, arg2value)
Benjamin Petersonb204a422011-06-05 22:04:07 -05001069 for i, arg in enumerate(args[num_args - num_defaults:]):
1070 if arg not in arg2value:
1071 arg2value[arg] = defaults[i]
Benjamin Petersone109c702011-06-24 09:37:26 -05001072 missing = 0
Benjamin Petersonb204a422011-06-05 22:04:07 -05001073 for kwarg in kwonlyargs:
1074 if kwarg not in arg2value:
Benjamin Petersone109c702011-06-24 09:37:26 -05001075 if kwarg in kwonlydefaults:
1076 arg2value[kwarg] = kwonlydefaults[kwarg]
1077 else:
1078 missing += 1
1079 if missing:
1080 _missing_arguments(f_name, kwonlyargs, False, arg2value)
Benjamin Peterson25cd7eb2010-03-30 18:42:32 +00001081 return arg2value
1082
Nick Coghlan2f92e542012-06-23 19:39:55 +10001083ClosureVars = namedtuple('ClosureVars', 'nonlocals globals builtins unbound')
1084
1085def getclosurevars(func):
1086 """
1087 Get the mapping of free variables to their current values.
1088
Meador Inge8fda3592012-07-19 21:33:21 -05001089 Returns a named tuple of dicts mapping the current nonlocal, global
Nick Coghlan2f92e542012-06-23 19:39:55 +10001090 and builtin references as seen by the body of the function. A final
1091 set of unbound names that could not be resolved is also provided.
1092 """
1093
1094 if ismethod(func):
1095 func = func.__func__
1096
1097 if not isfunction(func):
1098 raise TypeError("'{!r}' is not a Python function".format(func))
1099
1100 code = func.__code__
1101 # Nonlocal references are named in co_freevars and resolved
1102 # by looking them up in __closure__ by positional index
1103 if func.__closure__ is None:
1104 nonlocal_vars = {}
1105 else:
1106 nonlocal_vars = {
1107 var : cell.cell_contents
1108 for var, cell in zip(code.co_freevars, func.__closure__)
1109 }
1110
1111 # Global and builtin references are named in co_names and resolved
1112 # by looking them up in __globals__ or __builtins__
1113 global_ns = func.__globals__
1114 builtin_ns = global_ns.get("__builtins__", builtins.__dict__)
1115 if ismodule(builtin_ns):
1116 builtin_ns = builtin_ns.__dict__
1117 global_vars = {}
1118 builtin_vars = {}
1119 unbound_names = set()
1120 for name in code.co_names:
1121 if name in ("None", "True", "False"):
1122 # Because these used to be builtins instead of keywords, they
1123 # may still show up as name references. We ignore them.
1124 continue
1125 try:
1126 global_vars[name] = global_ns[name]
1127 except KeyError:
1128 try:
1129 builtin_vars[name] = builtin_ns[name]
1130 except KeyError:
1131 unbound_names.add(name)
1132
1133 return ClosureVars(nonlocal_vars, global_vars,
1134 builtin_vars, unbound_names)
1135
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001136# -------------------------------------------------- stack frame extraction
Christian Heimes25bb7832008-01-11 16:17:00 +00001137
1138Traceback = namedtuple('Traceback', 'filename lineno function code_context index')
1139
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001140def getframeinfo(frame, context=1):
1141 """Get information about a frame or traceback object.
1142
1143 A tuple of five things is returned: the filename, the line number of
1144 the current line, the function name, a list of lines of context from
1145 the source code, and the index of the current line within that list.
1146 The optional second argument specifies the number of lines of context
1147 to return, which are centered around the current line."""
1148 if istraceback(frame):
Andrew M. Kuchlingba8b6bc2004-06-05 14:11:59 +00001149 lineno = frame.tb_lineno
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001150 frame = frame.tb_frame
Andrew M. Kuchlingba8b6bc2004-06-05 14:11:59 +00001151 else:
1152 lineno = frame.f_lineno
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001153 if not isframe(frame):
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00001154 raise TypeError('{!r} is not a frame or traceback object'.format(frame))
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001155
Neil Schemenauerf06f8532002-03-23 23:51:04 +00001156 filename = getsourcefile(frame) or getfile(frame)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001157 if context > 0:
Guido van Rossum54e54c62001-09-04 19:14:14 +00001158 start = lineno - 1 - context//2
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001159 try:
1160 lines, lnum = findsource(frame)
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02001161 except OSError:
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +00001162 lines = index = None
1163 else:
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001164 start = max(start, 1)
Raymond Hettingera0501712004-06-15 11:22:53 +00001165 start = max(0, min(start, len(lines) - context))
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001166 lines = lines[start:start+context]
Ka-Ping Yee59ade082001-03-01 03:55:35 +00001167 index = lineno - 1 - start
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001168 else:
1169 lines = index = None
1170
Christian Heimes25bb7832008-01-11 16:17:00 +00001171 return Traceback(filename, lineno, frame.f_code.co_name, lines, index)
Ka-Ping Yee59ade082001-03-01 03:55:35 +00001172
1173def getlineno(frame):
1174 """Get the line number from a frame object, allowing for optimization."""
Michael W. Hudsondd32a912002-08-15 14:59:02 +00001175 # FrameType.f_lineno is now a descriptor that grovels co_lnotab
1176 return frame.f_lineno
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001177
1178def getouterframes(frame, context=1):
1179 """Get a list of records for a frame and all higher (calling) frames.
1180
1181 Each record contains a frame object, filename, line number, function
1182 name, a list of lines of context, and index within the context."""
1183 framelist = []
1184 while frame:
1185 framelist.append((frame,) + getframeinfo(frame, context))
1186 frame = frame.f_back
1187 return framelist
1188
1189def getinnerframes(tb, context=1):
1190 """Get a list of records for a traceback's frame and all lower frames.
1191
1192 Each record contains a frame object, filename, line number, function
1193 name, a list of lines of context, and index within the context."""
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001194 framelist = []
1195 while tb:
1196 framelist.append((tb.tb_frame,) + getframeinfo(tb, context))
1197 tb = tb.tb_next
1198 return framelist
1199
Benjamin Peterson42ac4752010-08-09 13:05:35 +00001200def currentframe():
Benjamin Petersona3a3fc62010-08-09 15:49:56 +00001201 """Return the frame of the caller or None if this is not possible."""
Benjamin Peterson42ac4752010-08-09 13:05:35 +00001202 return sys._getframe(1) if hasattr(sys, "_getframe") else None
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001203
1204def stack(context=1):
1205 """Return a list of records for the stack above the caller's frame."""
Jeremy Hyltonab919022003-06-27 18:41:20 +00001206 return getouterframes(sys._getframe(1), context)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001207
1208def trace(context=1):
Tim Peters85ba6732001-02-28 08:26:44 +00001209 """Return a list of records for the stack below the current exception."""
Fred Draked451ec12002-04-26 02:29:55 +00001210 return getinnerframes(sys.exc_info()[2], context)
Michael Foord95fc51d2010-11-20 15:07:30 +00001211
1212
1213# ------------------------------------------------ static version of getattr
1214
1215_sentinel = object()
1216
Michael Foorde5162652010-11-20 16:40:44 +00001217def _static_getmro(klass):
1218 return type.__dict__['__mro__'].__get__(klass)
1219
Michael Foord95fc51d2010-11-20 15:07:30 +00001220def _check_instance(obj, attr):
1221 instance_dict = {}
1222 try:
1223 instance_dict = object.__getattribute__(obj, "__dict__")
1224 except AttributeError:
1225 pass
Michael Foorddcebe0f2011-03-15 19:20:44 -04001226 return dict.get(instance_dict, attr, _sentinel)
Michael Foord95fc51d2010-11-20 15:07:30 +00001227
1228
1229def _check_class(klass, attr):
Michael Foorde5162652010-11-20 16:40:44 +00001230 for entry in _static_getmro(klass):
Michael Foorda51623b2011-12-18 22:01:40 +00001231 if _shadowed_dict(type(entry)) is _sentinel:
Michael Foorddcebe0f2011-03-15 19:20:44 -04001232 try:
1233 return entry.__dict__[attr]
1234 except KeyError:
1235 pass
Michael Foord95fc51d2010-11-20 15:07:30 +00001236 return _sentinel
1237
Michael Foord35184ed2010-11-20 16:58:30 +00001238def _is_type(obj):
1239 try:
1240 _static_getmro(obj)
1241 except TypeError:
1242 return False
1243 return True
1244
Michael Foorddcebe0f2011-03-15 19:20:44 -04001245def _shadowed_dict(klass):
1246 dict_attr = type.__dict__["__dict__"]
1247 for entry in _static_getmro(klass):
1248 try:
1249 class_dict = dict_attr.__get__(entry)["__dict__"]
1250 except KeyError:
1251 pass
1252 else:
1253 if not (type(class_dict) is types.GetSetDescriptorType and
1254 class_dict.__name__ == "__dict__" and
1255 class_dict.__objclass__ is entry):
Michael Foorda51623b2011-12-18 22:01:40 +00001256 return class_dict
1257 return _sentinel
Michael Foord95fc51d2010-11-20 15:07:30 +00001258
1259def getattr_static(obj, attr, default=_sentinel):
1260 """Retrieve attributes without triggering dynamic lookup via the
1261 descriptor protocol, __getattr__ or __getattribute__.
1262
1263 Note: this function may not be able to retrieve all attributes
1264 that getattr can fetch (like dynamically created attributes)
1265 and may find attributes that getattr can't (like descriptors
1266 that raise AttributeError). It can also return descriptor objects
1267 instead of instance members in some cases. See the
1268 documentation for details.
1269 """
1270 instance_result = _sentinel
Michael Foord35184ed2010-11-20 16:58:30 +00001271 if not _is_type(obj):
Michael Foordcc7ebb82010-11-20 16:20:16 +00001272 klass = type(obj)
Michael Foorda51623b2011-12-18 22:01:40 +00001273 dict_attr = _shadowed_dict(klass)
1274 if (dict_attr is _sentinel or
1275 type(dict_attr) is types.MemberDescriptorType):
Michael Foorddcebe0f2011-03-15 19:20:44 -04001276 instance_result = _check_instance(obj, attr)
Michael Foord95fc51d2010-11-20 15:07:30 +00001277 else:
1278 klass = obj
1279
1280 klass_result = _check_class(klass, attr)
1281
1282 if instance_result is not _sentinel and klass_result is not _sentinel:
1283 if (_check_class(type(klass_result), '__get__') is not _sentinel and
1284 _check_class(type(klass_result), '__set__') is not _sentinel):
1285 return klass_result
1286
1287 if instance_result is not _sentinel:
1288 return instance_result
1289 if klass_result is not _sentinel:
1290 return klass_result
1291
1292 if obj is klass:
1293 # for types we check the metaclass too
Michael Foorde5162652010-11-20 16:40:44 +00001294 for entry in _static_getmro(type(klass)):
Michael Foord3ba95f82011-12-22 01:13:37 +00001295 if _shadowed_dict(type(entry)) is _sentinel:
1296 try:
1297 return entry.__dict__[attr]
1298 except KeyError:
1299 pass
Michael Foord95fc51d2010-11-20 15:07:30 +00001300 if default is not _sentinel:
1301 return default
1302 raise AttributeError(attr)
Nick Coghlane0f04652010-11-21 03:44:04 +00001303
1304
Nick Coghlan04e2e3f2012-06-23 19:52:05 +10001305# ------------------------------------------------ generator introspection
1306
Nick Coghlan7921b9f2010-11-30 06:36:04 +00001307GEN_CREATED = 'GEN_CREATED'
1308GEN_RUNNING = 'GEN_RUNNING'
1309GEN_SUSPENDED = 'GEN_SUSPENDED'
1310GEN_CLOSED = 'GEN_CLOSED'
Nick Coghlane0f04652010-11-21 03:44:04 +00001311
1312def getgeneratorstate(generator):
1313 """Get current state of a generator-iterator.
1314
1315 Possible states are:
1316 GEN_CREATED: Waiting to start execution.
1317 GEN_RUNNING: Currently being executed by the interpreter.
1318 GEN_SUSPENDED: Currently suspended at a yield expression.
1319 GEN_CLOSED: Execution has completed.
1320 """
1321 if generator.gi_running:
1322 return GEN_RUNNING
1323 if generator.gi_frame is None:
1324 return GEN_CLOSED
1325 if generator.gi_frame.f_lasti == -1:
1326 return GEN_CREATED
1327 return GEN_SUSPENDED
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07001328
1329
Nick Coghlan04e2e3f2012-06-23 19:52:05 +10001330def getgeneratorlocals(generator):
1331 """
1332 Get the mapping of generator local variables to their current values.
1333
1334 A dict is returned, with the keys the local variable names and values the
1335 bound values."""
1336
1337 if not isgenerator(generator):
1338 raise TypeError("'{!r}' is not a Python generator".format(generator))
1339
1340 frame = getattr(generator, "gi_frame", None)
1341 if frame is not None:
1342 return generator.gi_frame.f_locals
1343 else:
1344 return {}
1345
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07001346###############################################################################
1347### Function Signature Object (PEP 362)
1348###############################################################################
1349
1350
1351_WrapperDescriptor = type(type.__call__)
1352_MethodWrapper = type(all.__call__)
1353
1354_NonUserDefinedCallables = (_WrapperDescriptor,
1355 _MethodWrapper,
1356 types.BuiltinFunctionType)
1357
1358
1359def _get_user_defined_method(cls, method_name):
1360 try:
1361 meth = getattr(cls, method_name)
1362 except AttributeError:
1363 return
1364 else:
1365 if not isinstance(meth, _NonUserDefinedCallables):
1366 # Once '__signature__' will be added to 'C'-level
1367 # callables, this check won't be necessary
1368 return meth
1369
1370
1371def signature(obj):
1372 '''Get a signature object for the passed callable.'''
1373
1374 if not callable(obj):
1375 raise TypeError('{!r} is not a callable object'.format(obj))
1376
1377 if isinstance(obj, types.MethodType):
1378 # In this case we skip the first parameter of the underlying
1379 # function (usually `self` or `cls`).
1380 sig = signature(obj.__func__)
1381 return sig.replace(parameters=tuple(sig.parameters.values())[1:])
1382
Nick Coghlane8c45d62013-07-28 20:00:01 +10001383 # Was this function wrapped by a decorator?
1384 obj = unwrap(obj, stop=(lambda f: hasattr(f, "__signature__")))
1385
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07001386 try:
1387 sig = obj.__signature__
1388 except AttributeError:
1389 pass
1390 else:
1391 if sig is not None:
1392 return sig
1393
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07001394
1395 if isinstance(obj, types.FunctionType):
1396 return Signature.from_function(obj)
1397
1398 if isinstance(obj, functools.partial):
1399 sig = signature(obj.func)
1400
1401 new_params = OrderedDict(sig.parameters.items())
1402
1403 partial_args = obj.args or ()
1404 partial_keywords = obj.keywords or {}
1405 try:
1406 ba = sig.bind_partial(*partial_args, **partial_keywords)
1407 except TypeError as ex:
1408 msg = 'partial object {!r} has incorrect arguments'.format(obj)
1409 raise ValueError(msg) from ex
1410
1411 for arg_name, arg_value in ba.arguments.items():
1412 param = new_params[arg_name]
1413 if arg_name in partial_keywords:
1414 # We set a new default value, because the following code
1415 # is correct:
1416 #
1417 # >>> def foo(a): print(a)
1418 # >>> print(partial(partial(foo, a=10), a=20)())
1419 # 20
1420 # >>> print(partial(partial(foo, a=10), a=20)(a=30))
1421 # 30
1422 #
1423 # So, with 'partial' objects, passing a keyword argument is
1424 # like setting a new default value for the corresponding
1425 # parameter
1426 #
1427 # We also mark this parameter with '_partial_kwarg'
1428 # flag. Later, in '_bind', the 'default' value of this
1429 # parameter will be added to 'kwargs', to simulate
1430 # the 'functools.partial' real call.
1431 new_params[arg_name] = param.replace(default=arg_value,
1432 _partial_kwarg=True)
1433
1434 elif (param.kind not in (_VAR_KEYWORD, _VAR_POSITIONAL) and
1435 not param._partial_kwarg):
1436 new_params.pop(arg_name)
1437
1438 return sig.replace(parameters=new_params.values())
1439
1440 sig = None
1441 if isinstance(obj, type):
1442 # obj is a class or a metaclass
1443
1444 # First, let's see if it has an overloaded __call__ defined
1445 # in its metaclass
1446 call = _get_user_defined_method(type(obj), '__call__')
1447 if call is not None:
1448 sig = signature(call)
1449 else:
1450 # Now we check if the 'obj' class has a '__new__' method
1451 new = _get_user_defined_method(obj, '__new__')
1452 if new is not None:
1453 sig = signature(new)
1454 else:
1455 # Finally, we should have at least __init__ implemented
1456 init = _get_user_defined_method(obj, '__init__')
1457 if init is not None:
1458 sig = signature(init)
1459 elif not isinstance(obj, _NonUserDefinedCallables):
1460 # An object with __call__
1461 # We also check that the 'obj' is not an instance of
1462 # _WrapperDescriptor or _MethodWrapper to avoid
1463 # infinite recursion (and even potential segfault)
1464 call = _get_user_defined_method(type(obj), '__call__')
1465 if call is not None:
1466 sig = signature(call)
1467
1468 if sig is not None:
1469 # For classes and objects we skip the first parameter of their
1470 # __call__, __new__, or __init__ methods
1471 return sig.replace(parameters=tuple(sig.parameters.values())[1:])
1472
1473 if isinstance(obj, types.BuiltinFunctionType):
1474 # Raise a nicer error message for builtins
1475 msg = 'no signature found for builtin function {!r}'.format(obj)
1476 raise ValueError(msg)
1477
1478 raise ValueError('callable {!r} is not supported by signature'.format(obj))
1479
1480
1481class _void:
1482 '''A private marker - used in Parameter & Signature'''
1483
1484
1485class _empty:
1486 pass
1487
1488
1489class _ParameterKind(int):
1490 def __new__(self, *args, name):
1491 obj = int.__new__(self, *args)
1492 obj._name = name
1493 return obj
1494
1495 def __str__(self):
1496 return self._name
1497
1498 def __repr__(self):
1499 return '<_ParameterKind: {!r}>'.format(self._name)
1500
1501
1502_POSITIONAL_ONLY = _ParameterKind(0, name='POSITIONAL_ONLY')
1503_POSITIONAL_OR_KEYWORD = _ParameterKind(1, name='POSITIONAL_OR_KEYWORD')
1504_VAR_POSITIONAL = _ParameterKind(2, name='VAR_POSITIONAL')
1505_KEYWORD_ONLY = _ParameterKind(3, name='KEYWORD_ONLY')
1506_VAR_KEYWORD = _ParameterKind(4, name='VAR_KEYWORD')
1507
1508
1509class Parameter:
1510 '''Represents a parameter in a function signature.
1511
1512 Has the following public attributes:
1513
1514 * name : str
1515 The name of the parameter as a string.
1516 * default : object
1517 The default value for the parameter if specified. If the
1518 parameter has no default value, this attribute is not set.
1519 * annotation
1520 The annotation for the parameter if specified. If the
1521 parameter has no annotation, this attribute is not set.
1522 * kind : str
1523 Describes how argument values are bound to the parameter.
1524 Possible values: `Parameter.POSITIONAL_ONLY`,
1525 `Parameter.POSITIONAL_OR_KEYWORD`, `Parameter.VAR_POSITIONAL`,
1526 `Parameter.KEYWORD_ONLY`, `Parameter.VAR_KEYWORD`.
1527 '''
1528
1529 __slots__ = ('_name', '_kind', '_default', '_annotation', '_partial_kwarg')
1530
1531 POSITIONAL_ONLY = _POSITIONAL_ONLY
1532 POSITIONAL_OR_KEYWORD = _POSITIONAL_OR_KEYWORD
1533 VAR_POSITIONAL = _VAR_POSITIONAL
1534 KEYWORD_ONLY = _KEYWORD_ONLY
1535 VAR_KEYWORD = _VAR_KEYWORD
1536
1537 empty = _empty
1538
1539 def __init__(self, name, kind, *, default=_empty, annotation=_empty,
1540 _partial_kwarg=False):
1541
1542 if kind not in (_POSITIONAL_ONLY, _POSITIONAL_OR_KEYWORD,
1543 _VAR_POSITIONAL, _KEYWORD_ONLY, _VAR_KEYWORD):
1544 raise ValueError("invalid value for 'Parameter.kind' attribute")
1545 self._kind = kind
1546
1547 if default is not _empty:
1548 if kind in (_VAR_POSITIONAL, _VAR_KEYWORD):
1549 msg = '{} parameters cannot have default values'.format(kind)
1550 raise ValueError(msg)
1551 self._default = default
1552 self._annotation = annotation
1553
1554 if name is None:
1555 if kind != _POSITIONAL_ONLY:
1556 raise ValueError("None is not a valid name for a "
1557 "non-positional-only parameter")
1558 self._name = name
1559 else:
1560 name = str(name)
1561 if kind != _POSITIONAL_ONLY and not name.isidentifier():
1562 msg = '{!r} is not a valid parameter name'.format(name)
1563 raise ValueError(msg)
1564 self._name = name
1565
1566 self._partial_kwarg = _partial_kwarg
1567
1568 @property
1569 def name(self):
1570 return self._name
1571
1572 @property
1573 def default(self):
1574 return self._default
1575
1576 @property
1577 def annotation(self):
1578 return self._annotation
1579
1580 @property
1581 def kind(self):
1582 return self._kind
1583
1584 def replace(self, *, name=_void, kind=_void, annotation=_void,
1585 default=_void, _partial_kwarg=_void):
1586 '''Creates a customized copy of the Parameter.'''
1587
1588 if name is _void:
1589 name = self._name
1590
1591 if kind is _void:
1592 kind = self._kind
1593
1594 if annotation is _void:
1595 annotation = self._annotation
1596
1597 if default is _void:
1598 default = self._default
1599
1600 if _partial_kwarg is _void:
1601 _partial_kwarg = self._partial_kwarg
1602
1603 return type(self)(name, kind, default=default, annotation=annotation,
1604 _partial_kwarg=_partial_kwarg)
1605
1606 def __str__(self):
1607 kind = self.kind
1608
1609 formatted = self._name
1610 if kind == _POSITIONAL_ONLY:
1611 if formatted is None:
1612 formatted = ''
1613 formatted = '<{}>'.format(formatted)
1614
1615 # Add annotation and default value
1616 if self._annotation is not _empty:
1617 formatted = '{}:{}'.format(formatted,
1618 formatannotation(self._annotation))
1619
1620 if self._default is not _empty:
1621 formatted = '{}={}'.format(formatted, repr(self._default))
1622
1623 if kind == _VAR_POSITIONAL:
1624 formatted = '*' + formatted
1625 elif kind == _VAR_KEYWORD:
1626 formatted = '**' + formatted
1627
1628 return formatted
1629
1630 def __repr__(self):
1631 return '<{} at {:#x} {!r}>'.format(self.__class__.__name__,
1632 id(self), self.name)
1633
1634 def __eq__(self, other):
1635 return (issubclass(other.__class__, Parameter) and
1636 self._name == other._name and
1637 self._kind == other._kind and
1638 self._default == other._default and
1639 self._annotation == other._annotation)
1640
1641 def __ne__(self, other):
1642 return not self.__eq__(other)
1643
1644
1645class BoundArguments:
1646 '''Result of `Signature.bind` call. Holds the mapping of arguments
1647 to the function's parameters.
1648
1649 Has the following public attributes:
1650
1651 * arguments : OrderedDict
1652 An ordered mutable mapping of parameters' names to arguments' values.
1653 Does not contain arguments' default values.
1654 * signature : Signature
1655 The Signature object that created this instance.
1656 * args : tuple
1657 Tuple of positional arguments values.
1658 * kwargs : dict
1659 Dict of keyword arguments values.
1660 '''
1661
1662 def __init__(self, signature, arguments):
1663 self.arguments = arguments
1664 self._signature = signature
1665
1666 @property
1667 def signature(self):
1668 return self._signature
1669
1670 @property
1671 def args(self):
1672 args = []
1673 for param_name, param in self._signature.parameters.items():
1674 if (param.kind in (_VAR_KEYWORD, _KEYWORD_ONLY) or
1675 param._partial_kwarg):
1676 # Keyword arguments mapped by 'functools.partial'
1677 # (Parameter._partial_kwarg is True) are mapped
1678 # in 'BoundArguments.kwargs', along with VAR_KEYWORD &
1679 # KEYWORD_ONLY
1680 break
1681
1682 try:
1683 arg = self.arguments[param_name]
1684 except KeyError:
1685 # We're done here. Other arguments
1686 # will be mapped in 'BoundArguments.kwargs'
1687 break
1688 else:
1689 if param.kind == _VAR_POSITIONAL:
1690 # *args
1691 args.extend(arg)
1692 else:
1693 # plain argument
1694 args.append(arg)
1695
1696 return tuple(args)
1697
1698 @property
1699 def kwargs(self):
1700 kwargs = {}
1701 kwargs_started = False
1702 for param_name, param in self._signature.parameters.items():
1703 if not kwargs_started:
1704 if (param.kind in (_VAR_KEYWORD, _KEYWORD_ONLY) or
1705 param._partial_kwarg):
1706 kwargs_started = True
1707 else:
1708 if param_name not in self.arguments:
1709 kwargs_started = True
1710 continue
1711
1712 if not kwargs_started:
1713 continue
1714
1715 try:
1716 arg = self.arguments[param_name]
1717 except KeyError:
1718 pass
1719 else:
1720 if param.kind == _VAR_KEYWORD:
1721 # **kwargs
1722 kwargs.update(arg)
1723 else:
1724 # plain keyword argument
1725 kwargs[param_name] = arg
1726
1727 return kwargs
1728
1729 def __eq__(self, other):
1730 return (issubclass(other.__class__, BoundArguments) and
1731 self.signature == other.signature and
1732 self.arguments == other.arguments)
1733
1734 def __ne__(self, other):
1735 return not self.__eq__(other)
1736
1737
1738class Signature:
1739 '''A Signature object represents the overall signature of a function.
1740 It stores a Parameter object for each parameter accepted by the
1741 function, as well as information specific to the function itself.
1742
1743 A Signature object has the following public attributes and methods:
1744
1745 * parameters : OrderedDict
1746 An ordered mapping of parameters' names to the corresponding
1747 Parameter objects (keyword-only arguments are in the same order
1748 as listed in `code.co_varnames`).
1749 * return_annotation : object
1750 The annotation for the return type of the function if specified.
1751 If the function has no annotation for its return type, this
1752 attribute is not set.
1753 * bind(*args, **kwargs) -> BoundArguments
1754 Creates a mapping from positional and keyword arguments to
1755 parameters.
1756 * bind_partial(*args, **kwargs) -> BoundArguments
1757 Creates a partial mapping from positional and keyword arguments
1758 to parameters (simulating 'functools.partial' behavior.)
1759 '''
1760
1761 __slots__ = ('_return_annotation', '_parameters')
1762
1763 _parameter_cls = Parameter
1764 _bound_arguments_cls = BoundArguments
1765
1766 empty = _empty
1767
1768 def __init__(self, parameters=None, *, return_annotation=_empty,
1769 __validate_parameters__=True):
1770 '''Constructs Signature from the given list of Parameter
1771 objects and 'return_annotation'. All arguments are optional.
1772 '''
1773
1774 if parameters is None:
1775 params = OrderedDict()
1776 else:
1777 if __validate_parameters__:
1778 params = OrderedDict()
1779 top_kind = _POSITIONAL_ONLY
1780
1781 for idx, param in enumerate(parameters):
1782 kind = param.kind
1783 if kind < top_kind:
1784 msg = 'wrong parameter order: {} before {}'
1785 msg = msg.format(top_kind, param.kind)
1786 raise ValueError(msg)
1787 else:
1788 top_kind = kind
1789
1790 name = param.name
1791 if name is None:
1792 name = str(idx)
1793 param = param.replace(name=name)
1794
1795 if name in params:
1796 msg = 'duplicate parameter name: {!r}'.format(name)
1797 raise ValueError(msg)
1798 params[name] = param
1799 else:
1800 params = OrderedDict(((param.name, param)
1801 for param in parameters))
1802
1803 self._parameters = types.MappingProxyType(params)
1804 self._return_annotation = return_annotation
1805
1806 @classmethod
1807 def from_function(cls, func):
1808 '''Constructs Signature for the given python function'''
1809
1810 if not isinstance(func, types.FunctionType):
1811 raise TypeError('{!r} is not a Python function'.format(func))
1812
1813 Parameter = cls._parameter_cls
1814
1815 # Parameter information.
1816 func_code = func.__code__
1817 pos_count = func_code.co_argcount
1818 arg_names = func_code.co_varnames
1819 positional = tuple(arg_names[:pos_count])
1820 keyword_only_count = func_code.co_kwonlyargcount
1821 keyword_only = arg_names[pos_count:(pos_count + keyword_only_count)]
1822 annotations = func.__annotations__
1823 defaults = func.__defaults__
1824 kwdefaults = func.__kwdefaults__
1825
1826 if defaults:
1827 pos_default_count = len(defaults)
1828 else:
1829 pos_default_count = 0
1830
1831 parameters = []
1832
1833 # Non-keyword-only parameters w/o defaults.
1834 non_default_count = pos_count - pos_default_count
1835 for name in positional[:non_default_count]:
1836 annotation = annotations.get(name, _empty)
1837 parameters.append(Parameter(name, annotation=annotation,
1838 kind=_POSITIONAL_OR_KEYWORD))
1839
1840 # ... w/ defaults.
1841 for offset, name in enumerate(positional[non_default_count:]):
1842 annotation = annotations.get(name, _empty)
1843 parameters.append(Parameter(name, annotation=annotation,
1844 kind=_POSITIONAL_OR_KEYWORD,
1845 default=defaults[offset]))
1846
1847 # *args
1848 if func_code.co_flags & 0x04:
1849 name = arg_names[pos_count + keyword_only_count]
1850 annotation = annotations.get(name, _empty)
1851 parameters.append(Parameter(name, annotation=annotation,
1852 kind=_VAR_POSITIONAL))
1853
1854 # Keyword-only parameters.
1855 for name in keyword_only:
1856 default = _empty
1857 if kwdefaults is not None:
1858 default = kwdefaults.get(name, _empty)
1859
1860 annotation = annotations.get(name, _empty)
1861 parameters.append(Parameter(name, annotation=annotation,
1862 kind=_KEYWORD_ONLY,
1863 default=default))
1864 # **kwargs
1865 if func_code.co_flags & 0x08:
1866 index = pos_count + keyword_only_count
1867 if func_code.co_flags & 0x04:
1868 index += 1
1869
1870 name = arg_names[index]
1871 annotation = annotations.get(name, _empty)
1872 parameters.append(Parameter(name, annotation=annotation,
1873 kind=_VAR_KEYWORD))
1874
1875 return cls(parameters,
1876 return_annotation=annotations.get('return', _empty),
1877 __validate_parameters__=False)
1878
1879 @property
1880 def parameters(self):
1881 return self._parameters
1882
1883 @property
1884 def return_annotation(self):
1885 return self._return_annotation
1886
1887 def replace(self, *, parameters=_void, return_annotation=_void):
1888 '''Creates a customized copy of the Signature.
1889 Pass 'parameters' and/or 'return_annotation' arguments
1890 to override them in the new copy.
1891 '''
1892
1893 if parameters is _void:
1894 parameters = self.parameters.values()
1895
1896 if return_annotation is _void:
1897 return_annotation = self._return_annotation
1898
1899 return type(self)(parameters,
1900 return_annotation=return_annotation)
1901
1902 def __eq__(self, other):
1903 if (not issubclass(type(other), Signature) or
1904 self.return_annotation != other.return_annotation or
1905 len(self.parameters) != len(other.parameters)):
1906 return False
1907
1908 other_positions = {param: idx
1909 for idx, param in enumerate(other.parameters.keys())}
1910
1911 for idx, (param_name, param) in enumerate(self.parameters.items()):
1912 if param.kind == _KEYWORD_ONLY:
1913 try:
1914 other_param = other.parameters[param_name]
1915 except KeyError:
1916 return False
1917 else:
1918 if param != other_param:
1919 return False
1920 else:
1921 try:
1922 other_idx = other_positions[param_name]
1923 except KeyError:
1924 return False
1925 else:
1926 if (idx != other_idx or
1927 param != other.parameters[param_name]):
1928 return False
1929
1930 return True
1931
1932 def __ne__(self, other):
1933 return not self.__eq__(other)
1934
1935 def _bind(self, args, kwargs, *, partial=False):
1936 '''Private method. Don't use directly.'''
1937
1938 arguments = OrderedDict()
1939
1940 parameters = iter(self.parameters.values())
1941 parameters_ex = ()
1942 arg_vals = iter(args)
1943
1944 if partial:
1945 # Support for binding arguments to 'functools.partial' objects.
1946 # See 'functools.partial' case in 'signature()' implementation
1947 # for details.
1948 for param_name, param in self.parameters.items():
1949 if (param._partial_kwarg and param_name not in kwargs):
1950 # Simulating 'functools.partial' behavior
1951 kwargs[param_name] = param.default
1952
1953 while True:
1954 # Let's iterate through the positional arguments and corresponding
1955 # parameters
1956 try:
1957 arg_val = next(arg_vals)
1958 except StopIteration:
1959 # No more positional arguments
1960 try:
1961 param = next(parameters)
1962 except StopIteration:
1963 # No more parameters. That's it. Just need to check that
1964 # we have no `kwargs` after this while loop
1965 break
1966 else:
1967 if param.kind == _VAR_POSITIONAL:
1968 # That's OK, just empty *args. Let's start parsing
1969 # kwargs
1970 break
1971 elif param.name in kwargs:
1972 if param.kind == _POSITIONAL_ONLY:
1973 msg = '{arg!r} parameter is positional only, ' \
1974 'but was passed as a keyword'
1975 msg = msg.format(arg=param.name)
1976 raise TypeError(msg) from None
1977 parameters_ex = (param,)
1978 break
1979 elif (param.kind == _VAR_KEYWORD or
1980 param.default is not _empty):
1981 # That's fine too - we have a default value for this
1982 # parameter. So, lets start parsing `kwargs`, starting
1983 # with the current parameter
1984 parameters_ex = (param,)
1985 break
1986 else:
1987 if partial:
1988 parameters_ex = (param,)
1989 break
1990 else:
1991 msg = '{arg!r} parameter lacking default value'
1992 msg = msg.format(arg=param.name)
1993 raise TypeError(msg) from None
1994 else:
1995 # We have a positional argument to process
1996 try:
1997 param = next(parameters)
1998 except StopIteration:
1999 raise TypeError('too many positional arguments') from None
2000 else:
2001 if param.kind in (_VAR_KEYWORD, _KEYWORD_ONLY):
2002 # Looks like we have no parameter for this positional
2003 # argument
2004 raise TypeError('too many positional arguments')
2005
2006 if param.kind == _VAR_POSITIONAL:
2007 # We have an '*args'-like argument, let's fill it with
2008 # all positional arguments we have left and move on to
2009 # the next phase
2010 values = [arg_val]
2011 values.extend(arg_vals)
2012 arguments[param.name] = tuple(values)
2013 break
2014
2015 if param.name in kwargs:
2016 raise TypeError('multiple values for argument '
2017 '{arg!r}'.format(arg=param.name))
2018
2019 arguments[param.name] = arg_val
2020
2021 # Now, we iterate through the remaining parameters to process
2022 # keyword arguments
2023 kwargs_param = None
2024 for param in itertools.chain(parameters_ex, parameters):
2025 if param.kind == _POSITIONAL_ONLY:
2026 # This should never happen in case of a properly built
2027 # Signature object (but let's have this check here
2028 # to ensure correct behaviour just in case)
2029 raise TypeError('{arg!r} parameter is positional only, '
2030 'but was passed as a keyword'. \
2031 format(arg=param.name))
2032
2033 if param.kind == _VAR_KEYWORD:
2034 # Memorize that we have a '**kwargs'-like parameter
2035 kwargs_param = param
2036 continue
2037
2038 param_name = param.name
2039 try:
2040 arg_val = kwargs.pop(param_name)
2041 except KeyError:
2042 # We have no value for this parameter. It's fine though,
2043 # if it has a default value, or it is an '*args'-like
2044 # parameter, left alone by the processing of positional
2045 # arguments.
2046 if (not partial and param.kind != _VAR_POSITIONAL and
2047 param.default is _empty):
2048 raise TypeError('{arg!r} parameter lacking default value'. \
2049 format(arg=param_name)) from None
2050
2051 else:
2052 arguments[param_name] = arg_val
2053
2054 if kwargs:
2055 if kwargs_param is not None:
2056 # Process our '**kwargs'-like parameter
2057 arguments[kwargs_param.name] = kwargs
2058 else:
2059 raise TypeError('too many keyword arguments')
2060
2061 return self._bound_arguments_cls(self, arguments)
2062
Antoine Pitroubd41d1b2013-01-29 21:20:57 +01002063 def bind(__bind_self, *args, **kwargs):
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002064 '''Get a BoundArguments object, that maps the passed `args`
2065 and `kwargs` to the function's signature. Raises `TypeError`
2066 if the passed arguments can not be bound.
2067 '''
Antoine Pitroubd41d1b2013-01-29 21:20:57 +01002068 return __bind_self._bind(args, kwargs)
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002069
Antoine Pitroubd41d1b2013-01-29 21:20:57 +01002070 def bind_partial(__bind_self, *args, **kwargs):
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002071 '''Get a BoundArguments object, that partially maps the
2072 passed `args` and `kwargs` to the function's signature.
2073 Raises `TypeError` if the passed arguments can not be bound.
2074 '''
Antoine Pitroubd41d1b2013-01-29 21:20:57 +01002075 return __bind_self._bind(args, kwargs, partial=True)
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002076
2077 def __str__(self):
2078 result = []
2079 render_kw_only_separator = True
2080 for idx, param in enumerate(self.parameters.values()):
2081 formatted = str(param)
2082
2083 kind = param.kind
2084 if kind == _VAR_POSITIONAL:
2085 # OK, we have an '*args'-like parameter, so we won't need
2086 # a '*' to separate keyword-only arguments
2087 render_kw_only_separator = False
2088 elif kind == _KEYWORD_ONLY and render_kw_only_separator:
2089 # We have a keyword-only parameter to render and we haven't
2090 # rendered an '*args'-like parameter before, so add a '*'
2091 # separator to the parameters list ("foo(arg1, *, arg2)" case)
2092 result.append('*')
2093 # This condition should be only triggered once, so
2094 # reset the flag
2095 render_kw_only_separator = False
2096
2097 result.append(formatted)
2098
2099 rendered = '({})'.format(', '.join(result))
2100
2101 if self.return_annotation is not _empty:
2102 anno = formatannotation(self.return_annotation)
2103 rendered += ' -> {}'.format(anno)
2104
2105 return rendered