blob: 371bb355ba2b9b1ff71f7a45a5116df3be39befc [file] [log] [blame]
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001"""Get useful information from live Python objects.
2
3This module encapsulates the interface provided by the internal special
Neal Norwitz221085d2007-02-25 20:55:47 +00004attributes (co_*, im_*, tb_*, etc.) in a friendlier fashion.
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00005It also provides some help for examining source code and class layout.
6
7Here are some of the useful functions provided by this module:
8
Christian Heimes7131fd92008-02-19 14:21:46 +00009 ismodule(), isclass(), ismethod(), isfunction(), isgeneratorfunction(),
10 isgenerator(), istraceback(), isframe(), iscode(), isbuiltin(),
11 isroutine() - check object types
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +000012 getmembers() - get members of an object that satisfy a given condition
13
14 getfile(), getsourcefile(), getsource() - find an object's source code
15 getdoc(), getcomments() - get documentation on an object
16 getmodule() - determine the module that an object came from
17 getclasstree() - arrange classes so as to represent their hierarchy
18
Benjamin Peterson25cd7eb2010-03-30 18:42:32 +000019 getargspec(), getargvalues(), getcallargs() - get info about function arguments
Guido van Rossum2e65f892007-02-28 22:03:49 +000020 getfullargspec() - same, with support for Python-3000 features
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +000021 formatargspec(), formatargvalues() - format an argument spec
22 getouterframes(), getinnerframes() - get info about frames
23 currentframe() - get the current stack frame
24 stack(), trace() - get info about frames on the stack or in a traceback
Larry Hastings7c7cbfc2012-06-22 15:19:35 -070025
26 signature() - get a Signature object for the callable
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +000027"""
28
29# This module is in the public domain. No warranties.
30
Larry Hastings7c7cbfc2012-06-22 15:19:35 -070031__author__ = ('Ka-Ping Yee <ping@lfw.org>',
32 'Yury Selivanov <yselivanov@sprymix.com>')
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +000033
Brett Cannoncb66eb02012-05-11 12:58:42 -040034import importlib.machinery
35import itertools
Christian Heimes7131fd92008-02-19 14:21:46 +000036import linecache
Brett Cannoncb66eb02012-05-11 12:58:42 -040037import os
38import re
39import sys
40import tokenize
41import types
Brett Cannon2b88fcf2012-06-02 22:28:42 -040042import warnings
Larry Hastings7c7cbfc2012-06-22 15:19:35 -070043import functools
Nick Coghlan2f92e542012-06-23 19:39:55 +100044import builtins
Raymond Hettingera1a992c2005-03-11 06:46:45 +000045from operator import attrgetter
Larry Hastings7c7cbfc2012-06-22 15:19:35 -070046from collections import namedtuple, OrderedDict
Nick Coghlan09c81232010-08-17 10:18:16 +000047
48# Create constants for the compiler flags in Include/code.h
49# We try to get them from dis to avoid duplication, but fall
Ezio Melotti30b9d5d2013-08-17 15:50:46 +030050# back to hardcoding so the dependency is optional
Nick Coghlan09c81232010-08-17 10:18:16 +000051try:
52 from dis import COMPILER_FLAG_NAMES as _flag_names
Brett Cannoncd171c82013-07-04 17:43:24 -040053except ImportError:
Nick Coghlan09c81232010-08-17 10:18:16 +000054 CO_OPTIMIZED, CO_NEWLOCALS = 0x1, 0x2
55 CO_VARARGS, CO_VARKEYWORDS = 0x4, 0x8
56 CO_NESTED, CO_GENERATOR, CO_NOFREE = 0x10, 0x20, 0x40
57else:
58 mod_dict = globals()
59 for k, v in _flag_names.items():
60 mod_dict["CO_" + v] = k
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +000061
Christian Heimesbe5b30b2008-03-03 19:18:51 +000062# See Include/object.h
63TPFLAGS_IS_ABSTRACT = 1 << 20
64
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +000065# ----------------------------------------------------------- type-checking
66def ismodule(object):
67 """Return true if the object is a module.
68
69 Module objects provide these attributes:
Barry Warsaw28a691b2010-04-17 00:19:56 +000070 __cached__ pathname to byte compiled file
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +000071 __doc__ documentation string
72 __file__ filename (missing for built-in modules)"""
Tim Peters28bc59f2001-09-16 08:40:16 +000073 return isinstance(object, types.ModuleType)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +000074
75def isclass(object):
76 """Return true if the object is a class.
77
78 Class objects provide these attributes:
79 __doc__ documentation string
80 __module__ name of module in which this class was defined"""
Benjamin Petersonc4656002009-01-17 22:41:18 +000081 return isinstance(object, type)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +000082
83def ismethod(object):
84 """Return true if the object is an instance method.
85
86 Instance method objects provide these attributes:
87 __doc__ documentation string
88 __name__ name with which this method was defined
Christian Heimesff737952007-11-27 10:40:20 +000089 __func__ function object containing implementation of method
90 __self__ instance to which this method is bound"""
Tim Peters28bc59f2001-09-16 08:40:16 +000091 return isinstance(object, types.MethodType)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +000092
Tim Peters536d2262001-09-20 05:13:38 +000093def ismethoddescriptor(object):
Tim Petersf1d90b92001-09-20 05:47:55 +000094 """Return true if the object is a method descriptor.
95
96 But not if ismethod() or isclass() or isfunction() are true.
Tim Peters536d2262001-09-20 05:13:38 +000097
98 This is new in Python 2.2, and, for example, is true of int.__add__.
99 An object passing this test has a __get__ attribute but not a __set__
100 attribute, but beyond that the set of attributes varies. __name__ is
101 usually sensible, and __doc__ often is.
102
Tim Petersf1d90b92001-09-20 05:47:55 +0000103 Methods implemented via descriptors that also pass one of the other
104 tests return false from the ismethoddescriptor() test, simply because
105 the other tests promise more -- you can, e.g., count on having the
Christian Heimesff737952007-11-27 10:40:20 +0000106 __func__ attribute (etc) when an object passes ismethod()."""
Antoine Pitrou86a8a9a2011-12-21 09:57:40 +0100107 if isclass(object) or ismethod(object) or isfunction(object):
108 # mutual exclusion
109 return False
110 tp = type(object)
111 return hasattr(tp, "__get__") and not hasattr(tp, "__set__")
Tim Peters536d2262001-09-20 05:13:38 +0000112
Martin v. Löwise59e2ba2003-05-03 09:09:02 +0000113def isdatadescriptor(object):
114 """Return true if the object is a data descriptor.
115
116 Data descriptors have both a __get__ and a __set__ attribute. Examples are
117 properties (defined in Python) and getsets and members (defined in C).
118 Typically, data descriptors will also have __name__ and __doc__ attributes
119 (properties, getsets, and members have both of these attributes), but this
120 is not guaranteed."""
Antoine Pitrou86a8a9a2011-12-21 09:57:40 +0100121 if isclass(object) or ismethod(object) or isfunction(object):
122 # mutual exclusion
123 return False
124 tp = type(object)
125 return hasattr(tp, "__set__") and hasattr(tp, "__get__")
Martin v. Löwise59e2ba2003-05-03 09:09:02 +0000126
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000127if hasattr(types, 'MemberDescriptorType'):
128 # CPython and equivalent
129 def ismemberdescriptor(object):
130 """Return true if the object is a member descriptor.
131
132 Member descriptors are specialized descriptors defined in extension
133 modules."""
134 return isinstance(object, types.MemberDescriptorType)
135else:
136 # Other implementations
137 def ismemberdescriptor(object):
138 """Return true if the object is a member descriptor.
139
140 Member descriptors are specialized descriptors defined in extension
141 modules."""
142 return False
143
144if hasattr(types, 'GetSetDescriptorType'):
145 # CPython and equivalent
146 def isgetsetdescriptor(object):
147 """Return true if the object is a getset descriptor.
148
149 getset descriptors are specialized descriptors defined in extension
150 modules."""
151 return isinstance(object, types.GetSetDescriptorType)
152else:
153 # Other implementations
154 def isgetsetdescriptor(object):
155 """Return true if the object is a getset descriptor.
156
157 getset descriptors are specialized descriptors defined in extension
158 modules."""
159 return False
160
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000161def isfunction(object):
162 """Return true if the object is a user-defined function.
163
164 Function objects provide these attributes:
165 __doc__ documentation string
166 __name__ name with which this function was defined
Neal Norwitz221085d2007-02-25 20:55:47 +0000167 __code__ code object containing compiled function bytecode
168 __defaults__ tuple of any default values for arguments
169 __globals__ global namespace in which this function was defined
170 __annotations__ dict of parameter annotations
171 __kwdefaults__ dict of keyword only parameters with defaults"""
Tim Peters28bc59f2001-09-16 08:40:16 +0000172 return isinstance(object, types.FunctionType)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000173
Christian Heimes7131fd92008-02-19 14:21:46 +0000174def isgeneratorfunction(object):
175 """Return true if the object is a user-defined generator function.
176
177 Generator function objects provides same attributes as functions.
178
Alexander Belopolsky977a6842010-08-16 20:17:07 +0000179 See help(isfunction) for attributes listing."""
Georg Brandlb1441c72009-01-03 22:33:39 +0000180 return bool((isfunction(object) or ismethod(object)) and
181 object.__code__.co_flags & CO_GENERATOR)
Christian Heimes7131fd92008-02-19 14:21:46 +0000182
183def isgenerator(object):
184 """Return true if the object is a generator.
185
186 Generator objects provide these attributes:
Ezio Melotti30b9d5d2013-08-17 15:50:46 +0300187 __iter__ defined to support iteration over container
Christian Heimes7131fd92008-02-19 14:21:46 +0000188 close raises a new GeneratorExit exception inside the
189 generator to terminate the iteration
190 gi_code code object
191 gi_frame frame object or possibly None once the generator has
192 been exhausted
193 gi_running set to 1 when generator is executing, 0 otherwise
194 next return the next item from the container
195 send resumes the generator and "sends" a value that becomes
196 the result of the current yield-expression
197 throw used to raise an exception inside the generator"""
198 return isinstance(object, types.GeneratorType)
199
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000200def istraceback(object):
201 """Return true if the object is a traceback.
202
203 Traceback objects provide these attributes:
204 tb_frame frame object at this level
205 tb_lasti index of last attempted instruction in bytecode
206 tb_lineno current line number in Python source code
207 tb_next next inner traceback object (called by this level)"""
Tim Peters28bc59f2001-09-16 08:40:16 +0000208 return isinstance(object, types.TracebackType)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000209
210def isframe(object):
211 """Return true if the object is a frame object.
212
213 Frame objects provide these attributes:
214 f_back next outer frame object (this frame's caller)
215 f_builtins built-in namespace seen by this frame
216 f_code code object being executed in this frame
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000217 f_globals global namespace seen by this frame
218 f_lasti index of last attempted instruction in bytecode
219 f_lineno current line number in Python source code
220 f_locals local namespace seen by this frame
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000221 f_trace tracing function for this frame, or None"""
Tim Peters28bc59f2001-09-16 08:40:16 +0000222 return isinstance(object, types.FrameType)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000223
224def iscode(object):
225 """Return true if the object is a code object.
226
227 Code objects provide these attributes:
228 co_argcount number of arguments (not including * or ** args)
229 co_code string of raw compiled bytecode
230 co_consts tuple of constants used in the bytecode
231 co_filename name of file in which this code object was created
232 co_firstlineno number of first line in Python source code
233 co_flags bitmap: 1=optimized | 2=newlocals | 4=*arg | 8=**arg
234 co_lnotab encoded mapping of line numbers to bytecode indices
235 co_name name with which this code object was defined
236 co_names tuple of names of local variables
237 co_nlocals number of local variables
238 co_stacksize virtual machine stack space required
239 co_varnames tuple of names of arguments and local variables"""
Tim Peters28bc59f2001-09-16 08:40:16 +0000240 return isinstance(object, types.CodeType)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000241
242def isbuiltin(object):
243 """Return true if the object is a built-in function or method.
244
245 Built-in functions and methods provide these attributes:
246 __doc__ documentation string
247 __name__ original name of this function or method
248 __self__ instance to which a method is bound, or None"""
Tim Peters28bc59f2001-09-16 08:40:16 +0000249 return isinstance(object, types.BuiltinFunctionType)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000250
251def isroutine(object):
252 """Return true if the object is any kind of function or method."""
Tim Peters536d2262001-09-20 05:13:38 +0000253 return (isbuiltin(object)
254 or isfunction(object)
255 or ismethod(object)
256 or ismethoddescriptor(object))
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000257
Christian Heimesbe5b30b2008-03-03 19:18:51 +0000258def isabstract(object):
259 """Return true if the object is an abstract base class (ABC)."""
Benjamin Petersona0dfa822009-11-13 02:25:08 +0000260 return bool(isinstance(object, type) and object.__flags__ & TPFLAGS_IS_ABSTRACT)
Christian Heimesbe5b30b2008-03-03 19:18:51 +0000261
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000262def getmembers(object, predicate=None):
263 """Return all members of an object as (name, value) pairs sorted by name.
264 Optionally, only return members that satisfy a given predicate."""
Antoine Pitrou86a8a9a2011-12-21 09:57:40 +0100265 if isclass(object):
266 mro = (object,) + getmro(object)
267 else:
268 mro = ()
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000269 results = []
270 for key in dir(object):
Antoine Pitrou86a8a9a2011-12-21 09:57:40 +0100271 # First try to get the value via __dict__. Some descriptors don't
272 # like calling their __get__ (see bug #1785).
273 for base in mro:
274 if key in base.__dict__:
275 value = base.__dict__[key]
276 break
277 else:
278 try:
279 value = getattr(object, key)
280 except AttributeError:
281 continue
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000282 if not predicate or predicate(value):
283 results.append((key, value))
284 results.sort()
285 return results
286
Christian Heimes25bb7832008-01-11 16:17:00 +0000287Attribute = namedtuple('Attribute', 'name kind defining_class object')
288
Tim Peters13b49d32001-09-23 02:00:29 +0000289def classify_class_attrs(cls):
290 """Return list of attribute-descriptor tuples.
291
292 For each name in dir(cls), the return list contains a 4-tuple
293 with these elements:
294
295 0. The name (a string).
296
297 1. The kind of attribute this is, one of these strings:
298 'class method' created via classmethod()
299 'static method' created via staticmethod()
300 'property' created via property()
301 'method' any other flavor of method
302 'data' not a method
303
304 2. The class which defined this attribute (a class).
305
306 3. The object as obtained directly from the defining class's
307 __dict__, not via getattr. This is especially important for
308 data attributes: C.data is just a data object, but
309 C.__dict__['data'] may be a data descriptor with additional
310 info, like a __doc__ string.
Ethan Furman668dede2013-09-14 18:53:26 -0700311
312 If one of the items in dir(cls) is stored in the metaclass it will now
313 be discovered and not have None be listed as the class in which it was
314 defined.
Tim Peters13b49d32001-09-23 02:00:29 +0000315 """
316
317 mro = getmro(cls)
Ethan Furman668dede2013-09-14 18:53:26 -0700318 metamro = getmro(type(cls)) # for attributes stored in the metaclass
Tim Peters13b49d32001-09-23 02:00:29 +0000319 names = dir(cls)
320 result = []
321 for name in names:
Antoine Pitrou86a8a9a2011-12-21 09:57:40 +0100322 # Get the object associated with the name, and where it was defined.
Tim Peters13b49d32001-09-23 02:00:29 +0000323 # Getting an obj from the __dict__ sometimes reveals more than
324 # using getattr. Static and class methods are dramatic examples.
Antoine Pitrou86a8a9a2011-12-21 09:57:40 +0100325 # Furthermore, some objects may raise an Exception when fetched with
326 # getattr(). This is the case with some descriptors (bug #1785).
327 # Thus, we only use getattr() as a last resort.
328 homecls = None
Ethan Furman668dede2013-09-14 18:53:26 -0700329 for base in (cls,) + mro + metamro:
Antoine Pitrou86a8a9a2011-12-21 09:57:40 +0100330 if name in base.__dict__:
331 obj = base.__dict__[name]
332 homecls = base
333 break
Tim Peters13b49d32001-09-23 02:00:29 +0000334 else:
335 obj = getattr(cls, name)
Antoine Pitrou86a8a9a2011-12-21 09:57:40 +0100336 homecls = getattr(obj, "__objclass__", homecls)
Tim Peters13b49d32001-09-23 02:00:29 +0000337
338 # Classify the object.
339 if isinstance(obj, staticmethod):
340 kind = "static method"
341 elif isinstance(obj, classmethod):
342 kind = "class method"
343 elif isinstance(obj, property):
344 kind = "property"
Antoine Pitrou86a8a9a2011-12-21 09:57:40 +0100345 elif ismethoddescriptor(obj):
Tim Peters13b49d32001-09-23 02:00:29 +0000346 kind = "method"
Antoine Pitrou86a8a9a2011-12-21 09:57:40 +0100347 elif isdatadescriptor(obj):
Tim Peters13b49d32001-09-23 02:00:29 +0000348 kind = "data"
Antoine Pitrou86a8a9a2011-12-21 09:57:40 +0100349 else:
350 obj_via_getattr = getattr(cls, name)
351 if (isfunction(obj_via_getattr) or
352 ismethoddescriptor(obj_via_getattr)):
353 kind = "method"
354 else:
355 kind = "data"
356 obj = obj_via_getattr
Tim Peters13b49d32001-09-23 02:00:29 +0000357
Christian Heimes25bb7832008-01-11 16:17:00 +0000358 result.append(Attribute(name, kind, homecls, obj))
Tim Peters13b49d32001-09-23 02:00:29 +0000359
360 return result
361
Tim Peterse0b2d7a2001-09-22 06:10:55 +0000362# ----------------------------------------------------------- class helpers
Tim Peterse0b2d7a2001-09-22 06:10:55 +0000363
364def getmro(cls):
365 "Return tuple of base classes (including cls) in method resolution order."
Benjamin Petersonb82c8e52010-11-04 00:38:49 +0000366 return cls.__mro__
Tim Peterse0b2d7a2001-09-22 06:10:55 +0000367
Nick Coghlane8c45d62013-07-28 20:00:01 +1000368# -------------------------------------------------------- function helpers
369
370def unwrap(func, *, stop=None):
371 """Get the object wrapped by *func*.
372
373 Follows the chain of :attr:`__wrapped__` attributes returning the last
374 object in the chain.
375
376 *stop* is an optional callback accepting an object in the wrapper chain
377 as its sole argument that allows the unwrapping to be terminated early if
378 the callback returns a true value. If the callback never returns a true
379 value, the last object in the chain is returned as usual. For example,
380 :func:`signature` uses this to stop unwrapping if any object in the
381 chain has a ``__signature__`` attribute defined.
382
383 :exc:`ValueError` is raised if a cycle is encountered.
384
385 """
386 if stop is None:
387 def _is_wrapper(f):
388 return hasattr(f, '__wrapped__')
389 else:
390 def _is_wrapper(f):
391 return hasattr(f, '__wrapped__') and not stop(f)
392 f = func # remember the original func for error reporting
393 memo = {id(f)} # Memoise by id to tolerate non-hashable objects
394 while _is_wrapper(func):
395 func = func.__wrapped__
396 id_func = id(func)
397 if id_func in memo:
398 raise ValueError('wrapper loop when unwrapping {!r}'.format(f))
399 memo.add(id_func)
400 return func
401
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000402# -------------------------------------------------- source code extraction
403def indentsize(line):
404 """Return the indent size, in spaces, at the start of a line of text."""
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000405 expline = line.expandtabs()
406 return len(expline) - len(expline.lstrip())
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000407
408def getdoc(object):
409 """Get the documentation string for an object.
410
411 All tabs are expanded to spaces. To clean up docstrings that are
412 indented to line up with blocks of code, any whitespace than can be
413 uniformly removed from the second line onwards is removed."""
Tim Peters24008312002-03-17 18:56:20 +0000414 try:
415 doc = object.__doc__
416 except AttributeError:
417 return None
Guido van Rossum3172c5d2007-10-16 18:12:55 +0000418 if not isinstance(doc, str):
Tim Peters24008312002-03-17 18:56:20 +0000419 return None
Georg Brandl0c77a822008-06-10 16:37:50 +0000420 return cleandoc(doc)
421
422def cleandoc(doc):
423 """Clean up indentation from docstrings.
424
425 Any whitespace that can be uniformly removed from the second line
426 onwards is removed."""
Tim Peters24008312002-03-17 18:56:20 +0000427 try:
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000428 lines = doc.expandtabs().split('\n')
Tim Peters24008312002-03-17 18:56:20 +0000429 except UnicodeError:
430 return None
431 else:
Ka-Ping Yeea59ef7b2002-11-30 03:53:15 +0000432 # Find minimum indentation of any non-blank lines after first line.
Christian Heimesa37d4c62007-12-04 23:02:19 +0000433 margin = sys.maxsize
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000434 for line in lines[1:]:
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000435 content = len(line.lstrip())
Ka-Ping Yeea59ef7b2002-11-30 03:53:15 +0000436 if content:
437 indent = len(line) - content
438 margin = min(margin, indent)
439 # Remove indentation.
440 if lines:
441 lines[0] = lines[0].lstrip()
Christian Heimesa37d4c62007-12-04 23:02:19 +0000442 if margin < sys.maxsize:
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000443 for i in range(1, len(lines)): lines[i] = lines[i][margin:]
Ka-Ping Yeea59ef7b2002-11-30 03:53:15 +0000444 # Remove any trailing or leading blank lines.
445 while lines and not lines[-1]:
446 lines.pop()
447 while lines and not lines[0]:
448 lines.pop(0)
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000449 return '\n'.join(lines)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000450
451def getfile(object):
Ka-Ping Yeec113c242001-03-02 02:08:53 +0000452 """Work out which source or compiled file an object was defined in."""
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000453 if ismodule(object):
454 if hasattr(object, '__file__'):
455 return object.__file__
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +0000456 raise TypeError('{!r} is a built-in module'.format(object))
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000457 if isclass(object):
Ka-Ping Yeec99e0f12001-04-13 12:10:40 +0000458 object = sys.modules.get(object.__module__)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000459 if hasattr(object, '__file__'):
460 return object.__file__
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +0000461 raise TypeError('{!r} is a built-in class'.format(object))
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000462 if ismethod(object):
Christian Heimesff737952007-11-27 10:40:20 +0000463 object = object.__func__
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000464 if isfunction(object):
Neal Norwitz221085d2007-02-25 20:55:47 +0000465 object = object.__code__
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000466 if istraceback(object):
467 object = object.tb_frame
468 if isframe(object):
469 object = object.f_code
470 if iscode(object):
471 return object.co_filename
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +0000472 raise TypeError('{!r} is not a module, class, method, '
473 'function, traceback, frame, or code object'.format(object))
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000474
Christian Heimes25bb7832008-01-11 16:17:00 +0000475ModuleInfo = namedtuple('ModuleInfo', 'name suffix mode module_type')
476
Ka-Ping Yee4d6fc7f2001-04-10 11:43:00 +0000477def getmoduleinfo(path):
478 """Get the module name, suffix, mode, and module type for a given file."""
Brett Cannoncb66eb02012-05-11 12:58:42 -0400479 warnings.warn('inspect.getmoduleinfo() is deprecated', DeprecationWarning,
480 2)
Brett Cannone4f41de2013-06-16 13:13:40 -0400481 with warnings.catch_warnings():
482 warnings.simplefilter('ignore', PendingDeprecationWarning)
483 import imp
Ka-Ping Yee4d6fc7f2001-04-10 11:43:00 +0000484 filename = os.path.basename(path)
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000485 suffixes = [(-len(suffix), suffix, mode, mtype)
486 for suffix, mode, mtype in imp.get_suffixes()]
Ka-Ping Yee4d6fc7f2001-04-10 11:43:00 +0000487 suffixes.sort() # try longest suffixes first, in case they overlap
488 for neglen, suffix, mode, mtype in suffixes:
489 if filename[neglen:] == suffix:
Christian Heimes25bb7832008-01-11 16:17:00 +0000490 return ModuleInfo(filename[:neglen], suffix, mode, mtype)
Ka-Ping Yee4d6fc7f2001-04-10 11:43:00 +0000491
492def getmodulename(path):
493 """Return the module name for a given file, or None."""
Nick Coghlan76e07702012-07-18 23:14:57 +1000494 fname = os.path.basename(path)
495 # Check for paths that look like an actual module file
496 suffixes = [(-len(suffix), suffix)
497 for suffix in importlib.machinery.all_suffixes()]
498 suffixes.sort() # try longest suffixes first, in case they overlap
499 for neglen, suffix in suffixes:
500 if fname.endswith(suffix):
501 return fname[:neglen]
502 return None
Ka-Ping Yee4d6fc7f2001-04-10 11:43:00 +0000503
Ka-Ping Yeec113c242001-03-02 02:08:53 +0000504def getsourcefile(object):
R. David Murraya1b37402010-06-17 02:04:29 +0000505 """Return the filename that can be used to locate an object's source.
506 Return None if no way can be identified to get the source.
507 """
Ka-Ping Yeec113c242001-03-02 02:08:53 +0000508 filename = getfile(object)
Brett Cannoncb66eb02012-05-11 12:58:42 -0400509 all_bytecode_suffixes = importlib.machinery.DEBUG_BYTECODE_SUFFIXES[:]
510 all_bytecode_suffixes += importlib.machinery.OPTIMIZED_BYTECODE_SUFFIXES[:]
511 if any(filename.endswith(s) for s in all_bytecode_suffixes):
512 filename = (os.path.splitext(filename)[0] +
513 importlib.machinery.SOURCE_SUFFIXES[0])
514 elif any(filename.endswith(s) for s in
515 importlib.machinery.EXTENSION_SUFFIXES):
516 return None
Thomas Wouters477c8d52006-05-27 19:21:47 +0000517 if os.path.exists(filename):
518 return filename
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000519 # only return a non-existent filename if the module has a PEP 302 loader
Brett Cannon4c14b5d2013-05-04 13:56:58 -0400520 if getattr(getmodule(object, filename), '__loader__', None) is not None:
Ka-Ping Yeec113c242001-03-02 02:08:53 +0000521 return filename
R. David Murraya1b37402010-06-17 02:04:29 +0000522 # or it is in the linecache
523 if filename in linecache.cache:
524 return filename
Ka-Ping Yeec113c242001-03-02 02:08:53 +0000525
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000526def getabsfile(object, _filename=None):
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000527 """Return an absolute path to the source or compiled file for an object.
Ka-Ping Yeec113c242001-03-02 02:08:53 +0000528
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000529 The idea is for each object to have a unique origin, so this routine
530 normalizes the result as much as possible."""
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000531 if _filename is None:
532 _filename = getsourcefile(object) or getfile(object)
533 return os.path.normcase(os.path.abspath(_filename))
Ka-Ping Yeec113c242001-03-02 02:08:53 +0000534
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000535modulesbyfile = {}
Thomas Wouters89f507f2006-12-13 04:49:30 +0000536_filesbymodname = {}
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000537
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000538def getmodule(object, _filename=None):
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000539 """Return the module an object was defined in, or None if not found."""
Ka-Ping Yee202c99b2001-04-13 09:15:08 +0000540 if ismodule(object):
541 return object
Johannes Gijsbers93245262004-09-11 15:53:22 +0000542 if hasattr(object, '__module__'):
Ka-Ping Yee8b58b842001-03-01 13:56:16 +0000543 return sys.modules.get(object.__module__)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000544 # Try the filename to modulename cache
545 if _filename is not None and _filename in modulesbyfile:
546 return sys.modules.get(modulesbyfile[_filename])
547 # Try the cache again with the absolute file name
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000548 try:
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000549 file = getabsfile(object, _filename)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000550 except TypeError:
551 return None
Raymond Hettinger54f02222002-06-01 14:18:47 +0000552 if file in modulesbyfile:
Ka-Ping Yeeb38bbbd2003-03-28 16:29:50 +0000553 return sys.modules.get(modulesbyfile[file])
Thomas Wouters89f507f2006-12-13 04:49:30 +0000554 # Update the filename to module name cache and check yet again
555 # Copy sys.modules in order to cope with changes while iterating
Éric Araujoa74f8ef2011-11-29 16:58:53 +0100556 for modname, module in list(sys.modules.items()):
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000557 if ismodule(module) and hasattr(module, '__file__'):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000558 f = module.__file__
559 if f == _filesbymodname.get(modname, None):
560 # Have already mapped this module, so skip it
561 continue
562 _filesbymodname[modname] = f
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000563 f = getabsfile(module)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000564 # Always map to the name the module knows itself by
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000565 modulesbyfile[f] = modulesbyfile[
566 os.path.realpath(f)] = module.__name__
Raymond Hettinger54f02222002-06-01 14:18:47 +0000567 if file in modulesbyfile:
Ka-Ping Yeeb38bbbd2003-03-28 16:29:50 +0000568 return sys.modules.get(modulesbyfile[file])
Thomas Wouters89f507f2006-12-13 04:49:30 +0000569 # Check the main module
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000570 main = sys.modules['__main__']
Brett Cannon4a671fe2003-06-15 22:33:28 +0000571 if not hasattr(object, '__name__'):
572 return None
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000573 if hasattr(main, object.__name__):
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000574 mainobject = getattr(main, object.__name__)
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000575 if mainobject is object:
576 return main
Thomas Wouters89f507f2006-12-13 04:49:30 +0000577 # Check builtins
Georg Brandl1a3284e2007-12-02 09:40:06 +0000578 builtin = sys.modules['builtins']
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000579 if hasattr(builtin, object.__name__):
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000580 builtinobject = getattr(builtin, object.__name__)
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000581 if builtinobject is object:
582 return builtin
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000583
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000584def findsource(object):
585 """Return the entire source file and starting line number for an object.
586
587 The argument may be a module, class, method, function, traceback, frame,
588 or code object. The source code is returned as a list of all the lines
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200589 in the file and the line number indexes a line in that list. An OSError
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000590 is raised if the source code cannot be retrieved."""
Benjamin Peterson9620cc02011-06-11 15:53:11 -0500591
592 file = getfile(object)
593 sourcefile = getsourcefile(object)
Ezio Melotti1b145922013-03-30 05:17:24 +0200594 if not sourcefile and file[:1] + file[-1:] != '<>':
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200595 raise OSError('source code not available')
Benjamin Peterson9620cc02011-06-11 15:53:11 -0500596 file = sourcefile if sourcefile else file
597
Thomas Wouters89f507f2006-12-13 04:49:30 +0000598 module = getmodule(object, file)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000599 if module:
600 lines = linecache.getlines(file, module.__dict__)
601 else:
602 lines = linecache.getlines(file)
Neil Schemenauerf06f8532002-03-23 23:51:04 +0000603 if not lines:
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200604 raise OSError('could not get source code')
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000605
606 if ismodule(object):
607 return lines, 0
608
609 if isclass(object):
610 name = object.__name__
Thomas Wouters89f507f2006-12-13 04:49:30 +0000611 pat = re.compile(r'^(\s*)class\s*' + name + r'\b')
612 # make some effort to find the best matching class definition:
613 # use the one with the least indentation, which is the one
614 # that's most probably not inside a function definition.
615 candidates = []
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000616 for i in range(len(lines)):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000617 match = pat.match(lines[i])
618 if match:
619 # if it's at toplevel, it's already the best one
620 if lines[i][0] == 'c':
621 return lines, i
622 # else add whitespace to candidate list
623 candidates.append((match.group(1), i))
624 if candidates:
625 # this will sort by whitespace, and by line number,
626 # less whitespace first
627 candidates.sort()
628 return lines, candidates[0][1]
Jeremy Hyltonab919022003-06-27 18:41:20 +0000629 else:
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200630 raise OSError('could not find class definition')
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000631
632 if ismethod(object):
Christian Heimesff737952007-11-27 10:40:20 +0000633 object = object.__func__
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000634 if isfunction(object):
Neal Norwitz221085d2007-02-25 20:55:47 +0000635 object = object.__code__
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000636 if istraceback(object):
637 object = object.tb_frame
638 if isframe(object):
639 object = object.f_code
640 if iscode(object):
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000641 if not hasattr(object, 'co_firstlineno'):
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200642 raise OSError('could not find function definition')
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000643 lnum = object.co_firstlineno - 1
Johannes Gijsbers1542f342004-12-12 16:46:28 +0000644 pat = re.compile(r'^(\s*def\s)|(.*(?<!\w)lambda(:|\s))|^(\s*@)')
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000645 while lnum > 0:
Ka-Ping Yeea6e59712001-03-10 09:31:55 +0000646 if pat.match(lines[lnum]): break
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000647 lnum = lnum - 1
648 return lines, lnum
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200649 raise OSError('could not find code object')
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000650
651def getcomments(object):
Jeremy Hyltonb4c17c82002-03-28 23:01:56 +0000652 """Get lines of comments immediately preceding an object's source code.
653
654 Returns None when source can't be found.
655 """
656 try:
657 lines, lnum = findsource(object)
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200658 except (OSError, TypeError):
Jeremy Hyltonb4c17c82002-03-28 23:01:56 +0000659 return None
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000660
661 if ismodule(object):
662 # Look for a comment block at the top of the file.
663 start = 0
Ka-Ping Yeeb910efe2001-04-12 13:17:17 +0000664 if lines and lines[0][:2] == '#!': start = 1
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000665 while start < len(lines) and lines[start].strip() in ('', '#'):
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000666 start = start + 1
Ka-Ping Yeeb910efe2001-04-12 13:17:17 +0000667 if start < len(lines) and lines[start][:1] == '#':
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000668 comments = []
669 end = start
670 while end < len(lines) and lines[end][:1] == '#':
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000671 comments.append(lines[end].expandtabs())
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000672 end = end + 1
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000673 return ''.join(comments)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000674
675 # Look for a preceding block of comments at the same indentation.
676 elif lnum > 0:
677 indent = indentsize(lines[lnum])
678 end = lnum - 1
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000679 if end >= 0 and lines[end].lstrip()[:1] == '#' and \
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000680 indentsize(lines[end]) == indent:
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000681 comments = [lines[end].expandtabs().lstrip()]
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000682 if end > 0:
683 end = end - 1
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000684 comment = lines[end].expandtabs().lstrip()
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000685 while comment[:1] == '#' and indentsize(lines[end]) == indent:
686 comments[:0] = [comment]
687 end = end - 1
688 if end < 0: break
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000689 comment = lines[end].expandtabs().lstrip()
690 while comments and comments[0].strip() == '#':
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000691 comments[:1] = []
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000692 while comments and comments[-1].strip() == '#':
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000693 comments[-1:] = []
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000694 return ''.join(comments)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000695
Tim Peters4efb6e92001-06-29 23:51:08 +0000696class EndOfBlock(Exception): pass
697
698class BlockFinder:
699 """Provide a tokeneater() method to detect the end of a code block."""
700 def __init__(self):
701 self.indent = 0
Johannes Gijsbersa5855d52005-03-12 16:37:11 +0000702 self.islambda = False
Johannes Gijsbers1542f342004-12-12 16:46:28 +0000703 self.started = False
704 self.passline = False
Armin Rigodd5c0232005-09-25 11:45:45 +0000705 self.last = 1
Tim Peters4efb6e92001-06-29 23:51:08 +0000706
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000707 def tokeneater(self, type, token, srowcol, erowcol, line):
Tim Peters4efb6e92001-06-29 23:51:08 +0000708 if not self.started:
Armin Rigodd5c0232005-09-25 11:45:45 +0000709 # look for the first "def", "class" or "lambda"
Johannes Gijsbers1542f342004-12-12 16:46:28 +0000710 if token in ("def", "class", "lambda"):
Johannes Gijsbersa5855d52005-03-12 16:37:11 +0000711 if token == "lambda":
712 self.islambda = True
Johannes Gijsbers1542f342004-12-12 16:46:28 +0000713 self.started = True
Armin Rigodd5c0232005-09-25 11:45:45 +0000714 self.passline = True # skip to the end of the line
Tim Peters4efb6e92001-06-29 23:51:08 +0000715 elif type == tokenize.NEWLINE:
Armin Rigodd5c0232005-09-25 11:45:45 +0000716 self.passline = False # stop skipping when a NEWLINE is seen
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000717 self.last = srowcol[0]
Armin Rigodd5c0232005-09-25 11:45:45 +0000718 if self.islambda: # lambdas always end at the first NEWLINE
719 raise EndOfBlock
Johannes Gijsbers1542f342004-12-12 16:46:28 +0000720 elif self.passline:
721 pass
Tim Peters4efb6e92001-06-29 23:51:08 +0000722 elif type == tokenize.INDENT:
723 self.indent = self.indent + 1
Johannes Gijsbers1542f342004-12-12 16:46:28 +0000724 self.passline = True
Tim Peters4efb6e92001-06-29 23:51:08 +0000725 elif type == tokenize.DEDENT:
726 self.indent = self.indent - 1
Armin Rigodd5c0232005-09-25 11:45:45 +0000727 # the end of matching indent/dedent pairs end a block
728 # (note that this only works for "def"/"class" blocks,
729 # not e.g. for "if: else:" or "try: finally:" blocks)
730 if self.indent <= 0:
731 raise EndOfBlock
732 elif self.indent == 0 and type not in (tokenize.COMMENT, tokenize.NL):
733 # any other token on the same indentation level end the previous
734 # block as well, except the pseudo-tokens COMMENT and NL.
735 raise EndOfBlock
Tim Peters4efb6e92001-06-29 23:51:08 +0000736
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000737def getblock(lines):
738 """Extract the block of code at the top of the given list of lines."""
Armin Rigodd5c0232005-09-25 11:45:45 +0000739 blockfinder = BlockFinder()
Tim Peters4efb6e92001-06-29 23:51:08 +0000740 try:
Trent Nelson428de652008-03-18 22:41:35 +0000741 tokens = tokenize.generate_tokens(iter(lines).__next__)
742 for _token in tokens:
743 blockfinder.tokeneater(*_token)
Armin Rigodd5c0232005-09-25 11:45:45 +0000744 except (EndOfBlock, IndentationError):
745 pass
746 return lines[:blockfinder.last]
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000747
748def getsourcelines(object):
749 """Return a list of source lines and starting line number for an object.
750
751 The argument may be a module, class, method, function, traceback, frame,
752 or code object. The source code is returned as a list of the lines
753 corresponding to the object and the line number indicates where in the
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200754 original source file the first line of code was found. An OSError is
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000755 raised if the source code cannot be retrieved."""
756 lines, lnum = findsource(object)
757
758 if ismodule(object): return lines, 0
759 else: return getblock(lines[lnum:]), lnum + 1
760
761def getsource(object):
762 """Return the text of the source code for an object.
763
764 The argument may be a module, class, method, function, traceback, frame,
765 or code object. The source code is returned as a single string. An
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200766 OSError is raised if the source code cannot be retrieved."""
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000767 lines, lnum = getsourcelines(object)
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000768 return ''.join(lines)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000769
770# --------------------------------------------------- class tree extraction
771def walktree(classes, children, parent):
772 """Recursive helper function for getclasstree()."""
773 results = []
Raymond Hettingera1a992c2005-03-11 06:46:45 +0000774 classes.sort(key=attrgetter('__module__', '__name__'))
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000775 for c in classes:
776 results.append((c, c.__bases__))
Raymond Hettinger54f02222002-06-01 14:18:47 +0000777 if c in children:
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000778 results.append(walktree(children[c], children, c))
779 return results
780
Georg Brandl5ce83a02009-06-01 17:23:51 +0000781def getclasstree(classes, unique=False):
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000782 """Arrange the given list of classes into a hierarchy of nested lists.
783
784 Where a nested list appears, it contains classes derived from the class
785 whose entry immediately precedes the list. Each entry is a 2-tuple
786 containing a class and a tuple of its base classes. If the 'unique'
787 argument is true, exactly one entry appears in the returned structure
788 for each class in the given list. Otherwise, classes using multiple
789 inheritance and their descendants will appear multiple times."""
790 children = {}
791 roots = []
792 for c in classes:
793 if c.__bases__:
794 for parent in c.__bases__:
Raymond Hettinger54f02222002-06-01 14:18:47 +0000795 if not parent in children:
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000796 children[parent] = []
Serhiy Storchaka362c1b52013-09-05 17:14:32 +0300797 if c not in children[parent]:
798 children[parent].append(c)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000799 if unique and parent in classes: break
800 elif c not in roots:
801 roots.append(c)
Raymond Hettingere0d49722002-06-02 18:55:56 +0000802 for parent in children:
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000803 if parent not in classes:
804 roots.append(parent)
805 return walktree(roots, children, None)
806
807# ------------------------------------------------ argument list extraction
Christian Heimes25bb7832008-01-11 16:17:00 +0000808Arguments = namedtuple('Arguments', 'args, varargs, varkw')
809
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000810def getargs(co):
811 """Get information about the arguments accepted by a code object.
812
Guido van Rossum2e65f892007-02-28 22:03:49 +0000813 Three things are returned: (args, varargs, varkw), where
Georg Brandlc1c4bf82010-10-15 16:07:41 +0000814 'args' is the list of argument names. Keyword-only arguments are
815 appended. 'varargs' and 'varkw' are the names of the * and **
816 arguments or None."""
Guido van Rossum2e65f892007-02-28 22:03:49 +0000817 args, varargs, kwonlyargs, varkw = _getfullargs(co)
Christian Heimes25bb7832008-01-11 16:17:00 +0000818 return Arguments(args + kwonlyargs, varargs, varkw)
Guido van Rossum2e65f892007-02-28 22:03:49 +0000819
820def _getfullargs(co):
821 """Get information about the arguments accepted by a code object.
822
823 Four things are returned: (args, varargs, kwonlyargs, varkw), where
Georg Brandlc1c4bf82010-10-15 16:07:41 +0000824 'args' and 'kwonlyargs' are lists of argument names, and 'varargs'
825 and 'varkw' are the names of the * and ** arguments or None."""
Jeremy Hylton64967882003-06-27 18:14:39 +0000826
827 if not iscode(co):
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +0000828 raise TypeError('{!r} is not a code object'.format(co))
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000829
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000830 nargs = co.co_argcount
831 names = co.co_varnames
Guido van Rossum2e65f892007-02-28 22:03:49 +0000832 nkwargs = co.co_kwonlyargcount
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000833 args = list(names[:nargs])
Guido van Rossum2e65f892007-02-28 22:03:49 +0000834 kwonlyargs = list(names[nargs:nargs+nkwargs])
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000835 step = 0
836
Guido van Rossum2e65f892007-02-28 22:03:49 +0000837 nargs += nkwargs
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000838 varargs = None
839 if co.co_flags & CO_VARARGS:
840 varargs = co.co_varnames[nargs]
841 nargs = nargs + 1
842 varkw = None
843 if co.co_flags & CO_VARKEYWORDS:
844 varkw = co.co_varnames[nargs]
Guido van Rossum2e65f892007-02-28 22:03:49 +0000845 return args, varargs, kwonlyargs, varkw
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000846
Christian Heimes25bb7832008-01-11 16:17:00 +0000847
848ArgSpec = namedtuple('ArgSpec', 'args varargs keywords defaults')
849
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000850def getargspec(func):
851 """Get the names and default values of a function's arguments.
852
853 A tuple of four things is returned: (args, varargs, varkw, defaults).
Georg Brandlc1c4bf82010-10-15 16:07:41 +0000854 'args' is a list of the argument names.
Guido van Rossum2e65f892007-02-28 22:03:49 +0000855 'args' will include keyword-only argument names.
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000856 'varargs' and 'varkw' are the names of the * and ** arguments or None.
Jeremy Hylton64967882003-06-27 18:14:39 +0000857 'defaults' is an n-tuple of the default values of the last n arguments.
Guido van Rossuma8add0e2007-05-14 22:03:55 +0000858
Guido van Rossum2e65f892007-02-28 22:03:49 +0000859 Use the getfullargspec() API for Python-3000 code, as annotations
860 and keyword arguments are supported. getargspec() will raise ValueError
861 if the func has either annotations or keyword arguments.
862 """
863
864 args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults, ann = \
865 getfullargspec(func)
866 if kwonlyargs or ann:
Collin Winterce36ad82007-08-30 01:19:48 +0000867 raise ValueError("Function has keyword-only arguments or annotations"
868 ", use getfullargspec() API which can support them")
Christian Heimes25bb7832008-01-11 16:17:00 +0000869 return ArgSpec(args, varargs, varkw, defaults)
870
871FullArgSpec = namedtuple('FullArgSpec',
Benjamin Peterson3d4ca742008-11-12 21:39:01 +0000872 'args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults, annotations')
Guido van Rossum2e65f892007-02-28 22:03:49 +0000873
874def getfullargspec(func):
875 """Get the names and default values of a function's arguments.
876
Brett Cannon504d8852007-09-07 02:12:14 +0000877 A tuple of seven things is returned:
878 (args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults annotations).
Georg Brandlc1c4bf82010-10-15 16:07:41 +0000879 'args' is a list of the argument names.
Guido van Rossum2e65f892007-02-28 22:03:49 +0000880 'varargs' and 'varkw' are the names of the * and ** arguments or None.
881 'defaults' is an n-tuple of the default values of the last n arguments.
882 'kwonlyargs' is a list of keyword-only argument names.
883 'kwonlydefaults' is a dictionary mapping names from kwonlyargs to defaults.
884 'annotations' is a dictionary mapping argument names to annotations.
Guido van Rossuma8add0e2007-05-14 22:03:55 +0000885
Guido van Rossum2e65f892007-02-28 22:03:49 +0000886 The first four items in the tuple correspond to getargspec().
Jeremy Hylton64967882003-06-27 18:14:39 +0000887 """
888
889 if ismethod(func):
Christian Heimesff737952007-11-27 10:40:20 +0000890 func = func.__func__
Jeremy Hylton64967882003-06-27 18:14:39 +0000891 if not isfunction(func):
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +0000892 raise TypeError('{!r} is not a Python function'.format(func))
Guido van Rossum2e65f892007-02-28 22:03:49 +0000893 args, varargs, kwonlyargs, varkw = _getfullargs(func.__code__)
Christian Heimes25bb7832008-01-11 16:17:00 +0000894 return FullArgSpec(args, varargs, varkw, func.__defaults__,
Guido van Rossum2e65f892007-02-28 22:03:49 +0000895 kwonlyargs, func.__kwdefaults__, func.__annotations__)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000896
Christian Heimes25bb7832008-01-11 16:17:00 +0000897ArgInfo = namedtuple('ArgInfo', 'args varargs keywords locals')
898
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000899def getargvalues(frame):
900 """Get information about arguments passed into a particular frame.
901
902 A tuple of four things is returned: (args, varargs, varkw, locals).
Georg Brandlc1c4bf82010-10-15 16:07:41 +0000903 'args' is a list of the argument names.
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000904 'varargs' and 'varkw' are the names of the * and ** arguments or None.
905 'locals' is the locals dictionary of the given frame."""
906 args, varargs, varkw = getargs(frame.f_code)
Benjamin Peterson1a6e0d02008-10-25 15:49:17 +0000907 return ArgInfo(args, varargs, varkw, frame.f_locals)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000908
Guido van Rossum2e65f892007-02-28 22:03:49 +0000909def formatannotation(annotation, base_module=None):
910 if isinstance(annotation, type):
Georg Brandl1a3284e2007-12-02 09:40:06 +0000911 if annotation.__module__ in ('builtins', base_module):
Guido van Rossum2e65f892007-02-28 22:03:49 +0000912 return annotation.__name__
913 return annotation.__module__+'.'+annotation.__name__
914 return repr(annotation)
Guido van Rossuma8add0e2007-05-14 22:03:55 +0000915
Guido van Rossum2e65f892007-02-28 22:03:49 +0000916def formatannotationrelativeto(object):
Guido van Rossuma8add0e2007-05-14 22:03:55 +0000917 module = getattr(object, '__module__', None)
918 def _formatannotation(annotation):
919 return formatannotation(annotation, module)
920 return _formatannotation
Guido van Rossum2e65f892007-02-28 22:03:49 +0000921
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000922def formatargspec(args, varargs=None, varkw=None, defaults=None,
Guido van Rossum2e65f892007-02-28 22:03:49 +0000923 kwonlyargs=(), kwonlydefaults={}, annotations={},
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000924 formatarg=str,
925 formatvarargs=lambda name: '*' + name,
926 formatvarkw=lambda name: '**' + name,
927 formatvalue=lambda value: '=' + repr(value),
Guido van Rossum2e65f892007-02-28 22:03:49 +0000928 formatreturns=lambda text: ' -> ' + text,
Georg Brandlc1c4bf82010-10-15 16:07:41 +0000929 formatannotation=formatannotation):
Guido van Rossuma8add0e2007-05-14 22:03:55 +0000930 """Format an argument spec from the values returned by getargspec
Guido van Rossum2e65f892007-02-28 22:03:49 +0000931 or getfullargspec.
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000932
Guido van Rossum2e65f892007-02-28 22:03:49 +0000933 The first seven arguments are (args, varargs, varkw, defaults,
934 kwonlyargs, kwonlydefaults, annotations). The other five arguments
935 are the corresponding optional formatting functions that are called to
936 turn names and values into strings. The last argument is an optional
937 function to format the sequence of arguments."""
938 def formatargandannotation(arg):
939 result = formatarg(arg)
940 if arg in annotations:
941 result += ': ' + formatannotation(annotations[arg])
942 return result
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000943 specs = []
944 if defaults:
945 firstdefault = len(args) - len(defaults)
Benjamin Petersonb58dda72009-01-18 22:27:04 +0000946 for i, arg in enumerate(args):
Georg Brandlc1c4bf82010-10-15 16:07:41 +0000947 spec = formatargandannotation(arg)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000948 if defaults and i >= firstdefault:
949 spec = spec + formatvalue(defaults[i - firstdefault])
950 specs.append(spec)
Raymond Hettinger936654b2002-06-01 03:06:31 +0000951 if varargs is not None:
Guido van Rossum2e65f892007-02-28 22:03:49 +0000952 specs.append(formatvarargs(formatargandannotation(varargs)))
953 else:
954 if kwonlyargs:
955 specs.append('*')
956 if kwonlyargs:
957 for kwonlyarg in kwonlyargs:
958 spec = formatargandannotation(kwonlyarg)
Benjamin Peterson9953a8d2009-01-17 04:15:01 +0000959 if kwonlydefaults and kwonlyarg in kwonlydefaults:
Guido van Rossum2e65f892007-02-28 22:03:49 +0000960 spec += formatvalue(kwonlydefaults[kwonlyarg])
961 specs.append(spec)
Raymond Hettinger936654b2002-06-01 03:06:31 +0000962 if varkw is not None:
Guido van Rossum2e65f892007-02-28 22:03:49 +0000963 specs.append(formatvarkw(formatargandannotation(varkw)))
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000964 result = '(' + ', '.join(specs) + ')'
Guido van Rossum2e65f892007-02-28 22:03:49 +0000965 if 'return' in annotations:
966 result += formatreturns(formatannotation(annotations['return']))
967 return result
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000968
969def formatargvalues(args, varargs, varkw, locals,
970 formatarg=str,
971 formatvarargs=lambda name: '*' + name,
972 formatvarkw=lambda name: '**' + name,
Georg Brandlc1c4bf82010-10-15 16:07:41 +0000973 formatvalue=lambda value: '=' + repr(value)):
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000974 """Format an argument spec from the 4 values returned by getargvalues.
975
976 The first four arguments are (args, varargs, varkw, locals). The
977 next four arguments are the corresponding optional formatting functions
978 that are called to turn names and values into strings. The ninth
979 argument is an optional function to format the sequence of arguments."""
980 def convert(name, locals=locals,
981 formatarg=formatarg, formatvalue=formatvalue):
982 return formatarg(name) + formatvalue(locals[name])
983 specs = []
984 for i in range(len(args)):
Georg Brandlc1c4bf82010-10-15 16:07:41 +0000985 specs.append(convert(args[i]))
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000986 if varargs:
987 specs.append(formatvarargs(varargs) + formatvalue(locals[varargs]))
988 if varkw:
989 specs.append(formatvarkw(varkw) + formatvalue(locals[varkw]))
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000990 return '(' + ', '.join(specs) + ')'
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000991
Benjamin Petersone109c702011-06-24 09:37:26 -0500992def _missing_arguments(f_name, argnames, pos, values):
993 names = [repr(name) for name in argnames if name not in values]
994 missing = len(names)
995 if missing == 1:
996 s = names[0]
997 elif missing == 2:
998 s = "{} and {}".format(*names)
999 else:
1000 tail = ", {} and {}".format(names[-2:])
1001 del names[-2:]
1002 s = ", ".join(names) + tail
1003 raise TypeError("%s() missing %i required %s argument%s: %s" %
1004 (f_name, missing,
1005 "positional" if pos else "keyword-only",
1006 "" if missing == 1 else "s", s))
1007
1008def _too_many(f_name, args, kwonly, varargs, defcount, given, values):
Benjamin Petersonb204a422011-06-05 22:04:07 -05001009 atleast = len(args) - defcount
Benjamin Petersonb204a422011-06-05 22:04:07 -05001010 kwonly_given = len([arg for arg in kwonly if arg in values])
1011 if varargs:
1012 plural = atleast != 1
1013 sig = "at least %d" % (atleast,)
1014 elif defcount:
1015 plural = True
1016 sig = "from %d to %d" % (atleast, len(args))
1017 else:
1018 plural = len(args) != 1
1019 sig = str(len(args))
1020 kwonly_sig = ""
1021 if kwonly_given:
1022 msg = " positional argument%s (and %d keyword-only argument%s)"
1023 kwonly_sig = (msg % ("s" if given != 1 else "", kwonly_given,
1024 "s" if kwonly_given != 1 else ""))
1025 raise TypeError("%s() takes %s positional argument%s but %d%s %s given" %
1026 (f_name, sig, "s" if plural else "", given, kwonly_sig,
1027 "was" if given == 1 and not kwonly_given else "were"))
1028
Benjamin Peterson25cd7eb2010-03-30 18:42:32 +00001029def getcallargs(func, *positional, **named):
1030 """Get the mapping of arguments to values.
1031
1032 A dict is returned, with keys the function argument names (including the
1033 names of the * and ** arguments, if any), and values the respective bound
1034 values from 'positional' and 'named'."""
1035 spec = getfullargspec(func)
1036 args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults, ann = spec
1037 f_name = func.__name__
1038 arg2value = {}
1039
Benjamin Petersonb204a422011-06-05 22:04:07 -05001040
Benjamin Peterson25cd7eb2010-03-30 18:42:32 +00001041 if ismethod(func) and func.__self__ is not None:
1042 # implicit 'self' (or 'cls' for classmethods) argument
1043 positional = (func.__self__,) + positional
1044 num_pos = len(positional)
Benjamin Peterson25cd7eb2010-03-30 18:42:32 +00001045 num_args = len(args)
1046 num_defaults = len(defaults) if defaults else 0
Benjamin Peterson25cd7eb2010-03-30 18:42:32 +00001047
Benjamin Petersonb204a422011-06-05 22:04:07 -05001048 n = min(num_pos, num_args)
1049 for i in range(n):
1050 arg2value[args[i]] = positional[i]
1051 if varargs:
1052 arg2value[varargs] = tuple(positional[n:])
1053 possible_kwargs = set(args + kwonlyargs)
Benjamin Peterson25cd7eb2010-03-30 18:42:32 +00001054 if varkw:
Benjamin Petersonb204a422011-06-05 22:04:07 -05001055 arg2value[varkw] = {}
1056 for kw, value in named.items():
1057 if kw not in possible_kwargs:
1058 if not varkw:
1059 raise TypeError("%s() got an unexpected keyword argument %r" %
1060 (f_name, kw))
1061 arg2value[varkw][kw] = value
1062 continue
1063 if kw in arg2value:
1064 raise TypeError("%s() got multiple values for argument %r" %
1065 (f_name, kw))
1066 arg2value[kw] = value
1067 if num_pos > num_args and not varargs:
Benjamin Petersone109c702011-06-24 09:37:26 -05001068 _too_many(f_name, args, kwonlyargs, varargs, num_defaults,
1069 num_pos, arg2value)
Benjamin Petersonb204a422011-06-05 22:04:07 -05001070 if num_pos < num_args:
Benjamin Petersone109c702011-06-24 09:37:26 -05001071 req = args[:num_args - num_defaults]
1072 for arg in req:
Benjamin Petersonb204a422011-06-05 22:04:07 -05001073 if arg not in arg2value:
Benjamin Petersone109c702011-06-24 09:37:26 -05001074 _missing_arguments(f_name, req, True, arg2value)
Benjamin Petersonb204a422011-06-05 22:04:07 -05001075 for i, arg in enumerate(args[num_args - num_defaults:]):
1076 if arg not in arg2value:
1077 arg2value[arg] = defaults[i]
Benjamin Petersone109c702011-06-24 09:37:26 -05001078 missing = 0
Benjamin Petersonb204a422011-06-05 22:04:07 -05001079 for kwarg in kwonlyargs:
1080 if kwarg not in arg2value:
Benjamin Petersone109c702011-06-24 09:37:26 -05001081 if kwarg in kwonlydefaults:
1082 arg2value[kwarg] = kwonlydefaults[kwarg]
1083 else:
1084 missing += 1
1085 if missing:
1086 _missing_arguments(f_name, kwonlyargs, False, arg2value)
Benjamin Peterson25cd7eb2010-03-30 18:42:32 +00001087 return arg2value
1088
Nick Coghlan2f92e542012-06-23 19:39:55 +10001089ClosureVars = namedtuple('ClosureVars', 'nonlocals globals builtins unbound')
1090
1091def getclosurevars(func):
1092 """
1093 Get the mapping of free variables to their current values.
1094
Meador Inge8fda3592012-07-19 21:33:21 -05001095 Returns a named tuple of dicts mapping the current nonlocal, global
Nick Coghlan2f92e542012-06-23 19:39:55 +10001096 and builtin references as seen by the body of the function. A final
1097 set of unbound names that could not be resolved is also provided.
1098 """
1099
1100 if ismethod(func):
1101 func = func.__func__
1102
1103 if not isfunction(func):
1104 raise TypeError("'{!r}' is not a Python function".format(func))
1105
1106 code = func.__code__
1107 # Nonlocal references are named in co_freevars and resolved
1108 # by looking them up in __closure__ by positional index
1109 if func.__closure__ is None:
1110 nonlocal_vars = {}
1111 else:
1112 nonlocal_vars = {
1113 var : cell.cell_contents
1114 for var, cell in zip(code.co_freevars, func.__closure__)
1115 }
1116
1117 # Global and builtin references are named in co_names and resolved
1118 # by looking them up in __globals__ or __builtins__
1119 global_ns = func.__globals__
1120 builtin_ns = global_ns.get("__builtins__", builtins.__dict__)
1121 if ismodule(builtin_ns):
1122 builtin_ns = builtin_ns.__dict__
1123 global_vars = {}
1124 builtin_vars = {}
1125 unbound_names = set()
1126 for name in code.co_names:
1127 if name in ("None", "True", "False"):
1128 # Because these used to be builtins instead of keywords, they
1129 # may still show up as name references. We ignore them.
1130 continue
1131 try:
1132 global_vars[name] = global_ns[name]
1133 except KeyError:
1134 try:
1135 builtin_vars[name] = builtin_ns[name]
1136 except KeyError:
1137 unbound_names.add(name)
1138
1139 return ClosureVars(nonlocal_vars, global_vars,
1140 builtin_vars, unbound_names)
1141
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001142# -------------------------------------------------- stack frame extraction
Christian Heimes25bb7832008-01-11 16:17:00 +00001143
1144Traceback = namedtuple('Traceback', 'filename lineno function code_context index')
1145
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001146def getframeinfo(frame, context=1):
1147 """Get information about a frame or traceback object.
1148
1149 A tuple of five things is returned: the filename, the line number of
1150 the current line, the function name, a list of lines of context from
1151 the source code, and the index of the current line within that list.
1152 The optional second argument specifies the number of lines of context
1153 to return, which are centered around the current line."""
1154 if istraceback(frame):
Andrew M. Kuchlingba8b6bc2004-06-05 14:11:59 +00001155 lineno = frame.tb_lineno
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001156 frame = frame.tb_frame
Andrew M. Kuchlingba8b6bc2004-06-05 14:11:59 +00001157 else:
1158 lineno = frame.f_lineno
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001159 if not isframe(frame):
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00001160 raise TypeError('{!r} is not a frame or traceback object'.format(frame))
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001161
Neil Schemenauerf06f8532002-03-23 23:51:04 +00001162 filename = getsourcefile(frame) or getfile(frame)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001163 if context > 0:
Guido van Rossum54e54c62001-09-04 19:14:14 +00001164 start = lineno - 1 - context//2
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001165 try:
1166 lines, lnum = findsource(frame)
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02001167 except OSError:
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +00001168 lines = index = None
1169 else:
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001170 start = max(start, 1)
Raymond Hettingera0501712004-06-15 11:22:53 +00001171 start = max(0, min(start, len(lines) - context))
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001172 lines = lines[start:start+context]
Ka-Ping Yee59ade082001-03-01 03:55:35 +00001173 index = lineno - 1 - start
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001174 else:
1175 lines = index = None
1176
Christian Heimes25bb7832008-01-11 16:17:00 +00001177 return Traceback(filename, lineno, frame.f_code.co_name, lines, index)
Ka-Ping Yee59ade082001-03-01 03:55:35 +00001178
1179def getlineno(frame):
1180 """Get the line number from a frame object, allowing for optimization."""
Michael W. Hudsondd32a912002-08-15 14:59:02 +00001181 # FrameType.f_lineno is now a descriptor that grovels co_lnotab
1182 return frame.f_lineno
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001183
1184def getouterframes(frame, context=1):
1185 """Get a list of records for a frame and all higher (calling) frames.
1186
1187 Each record contains a frame object, filename, line number, function
1188 name, a list of lines of context, and index within the context."""
1189 framelist = []
1190 while frame:
1191 framelist.append((frame,) + getframeinfo(frame, context))
1192 frame = frame.f_back
1193 return framelist
1194
1195def getinnerframes(tb, context=1):
1196 """Get a list of records for a traceback's frame and all lower frames.
1197
1198 Each record contains a frame object, filename, line number, function
1199 name, a list of lines of context, and index within the context."""
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001200 framelist = []
1201 while tb:
1202 framelist.append((tb.tb_frame,) + getframeinfo(tb, context))
1203 tb = tb.tb_next
1204 return framelist
1205
Benjamin Peterson42ac4752010-08-09 13:05:35 +00001206def currentframe():
Benjamin Petersona3a3fc62010-08-09 15:49:56 +00001207 """Return the frame of the caller or None if this is not possible."""
Benjamin Peterson42ac4752010-08-09 13:05:35 +00001208 return sys._getframe(1) if hasattr(sys, "_getframe") else None
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001209
1210def stack(context=1):
1211 """Return a list of records for the stack above the caller's frame."""
Jeremy Hyltonab919022003-06-27 18:41:20 +00001212 return getouterframes(sys._getframe(1), context)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001213
1214def trace(context=1):
Tim Peters85ba6732001-02-28 08:26:44 +00001215 """Return a list of records for the stack below the current exception."""
Fred Draked451ec12002-04-26 02:29:55 +00001216 return getinnerframes(sys.exc_info()[2], context)
Michael Foord95fc51d2010-11-20 15:07:30 +00001217
1218
1219# ------------------------------------------------ static version of getattr
1220
1221_sentinel = object()
1222
Michael Foorde5162652010-11-20 16:40:44 +00001223def _static_getmro(klass):
1224 return type.__dict__['__mro__'].__get__(klass)
1225
Michael Foord95fc51d2010-11-20 15:07:30 +00001226def _check_instance(obj, attr):
1227 instance_dict = {}
1228 try:
1229 instance_dict = object.__getattribute__(obj, "__dict__")
1230 except AttributeError:
1231 pass
Michael Foorddcebe0f2011-03-15 19:20:44 -04001232 return dict.get(instance_dict, attr, _sentinel)
Michael Foord95fc51d2010-11-20 15:07:30 +00001233
1234
1235def _check_class(klass, attr):
Michael Foorde5162652010-11-20 16:40:44 +00001236 for entry in _static_getmro(klass):
Michael Foorda51623b2011-12-18 22:01:40 +00001237 if _shadowed_dict(type(entry)) is _sentinel:
Michael Foorddcebe0f2011-03-15 19:20:44 -04001238 try:
1239 return entry.__dict__[attr]
1240 except KeyError:
1241 pass
Michael Foord95fc51d2010-11-20 15:07:30 +00001242 return _sentinel
1243
Michael Foord35184ed2010-11-20 16:58:30 +00001244def _is_type(obj):
1245 try:
1246 _static_getmro(obj)
1247 except TypeError:
1248 return False
1249 return True
1250
Michael Foorddcebe0f2011-03-15 19:20:44 -04001251def _shadowed_dict(klass):
1252 dict_attr = type.__dict__["__dict__"]
1253 for entry in _static_getmro(klass):
1254 try:
1255 class_dict = dict_attr.__get__(entry)["__dict__"]
1256 except KeyError:
1257 pass
1258 else:
1259 if not (type(class_dict) is types.GetSetDescriptorType and
1260 class_dict.__name__ == "__dict__" and
1261 class_dict.__objclass__ is entry):
Michael Foorda51623b2011-12-18 22:01:40 +00001262 return class_dict
1263 return _sentinel
Michael Foord95fc51d2010-11-20 15:07:30 +00001264
1265def getattr_static(obj, attr, default=_sentinel):
1266 """Retrieve attributes without triggering dynamic lookup via the
1267 descriptor protocol, __getattr__ or __getattribute__.
1268
1269 Note: this function may not be able to retrieve all attributes
1270 that getattr can fetch (like dynamically created attributes)
1271 and may find attributes that getattr can't (like descriptors
1272 that raise AttributeError). It can also return descriptor objects
1273 instead of instance members in some cases. See the
1274 documentation for details.
1275 """
1276 instance_result = _sentinel
Michael Foord35184ed2010-11-20 16:58:30 +00001277 if not _is_type(obj):
Michael Foordcc7ebb82010-11-20 16:20:16 +00001278 klass = type(obj)
Michael Foorda51623b2011-12-18 22:01:40 +00001279 dict_attr = _shadowed_dict(klass)
1280 if (dict_attr is _sentinel or
1281 type(dict_attr) is types.MemberDescriptorType):
Michael Foorddcebe0f2011-03-15 19:20:44 -04001282 instance_result = _check_instance(obj, attr)
Michael Foord95fc51d2010-11-20 15:07:30 +00001283 else:
1284 klass = obj
1285
1286 klass_result = _check_class(klass, attr)
1287
1288 if instance_result is not _sentinel and klass_result is not _sentinel:
1289 if (_check_class(type(klass_result), '__get__') is not _sentinel and
1290 _check_class(type(klass_result), '__set__') is not _sentinel):
1291 return klass_result
1292
1293 if instance_result is not _sentinel:
1294 return instance_result
1295 if klass_result is not _sentinel:
1296 return klass_result
1297
1298 if obj is klass:
1299 # for types we check the metaclass too
Michael Foorde5162652010-11-20 16:40:44 +00001300 for entry in _static_getmro(type(klass)):
Michael Foord3ba95f82011-12-22 01:13:37 +00001301 if _shadowed_dict(type(entry)) is _sentinel:
1302 try:
1303 return entry.__dict__[attr]
1304 except KeyError:
1305 pass
Michael Foord95fc51d2010-11-20 15:07:30 +00001306 if default is not _sentinel:
1307 return default
1308 raise AttributeError(attr)
Nick Coghlane0f04652010-11-21 03:44:04 +00001309
1310
Nick Coghlan04e2e3f2012-06-23 19:52:05 +10001311# ------------------------------------------------ generator introspection
1312
Nick Coghlan7921b9f2010-11-30 06:36:04 +00001313GEN_CREATED = 'GEN_CREATED'
1314GEN_RUNNING = 'GEN_RUNNING'
1315GEN_SUSPENDED = 'GEN_SUSPENDED'
1316GEN_CLOSED = 'GEN_CLOSED'
Nick Coghlane0f04652010-11-21 03:44:04 +00001317
1318def getgeneratorstate(generator):
1319 """Get current state of a generator-iterator.
1320
1321 Possible states are:
1322 GEN_CREATED: Waiting to start execution.
1323 GEN_RUNNING: Currently being executed by the interpreter.
1324 GEN_SUSPENDED: Currently suspended at a yield expression.
1325 GEN_CLOSED: Execution has completed.
1326 """
1327 if generator.gi_running:
1328 return GEN_RUNNING
1329 if generator.gi_frame is None:
1330 return GEN_CLOSED
1331 if generator.gi_frame.f_lasti == -1:
1332 return GEN_CREATED
1333 return GEN_SUSPENDED
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07001334
1335
Nick Coghlan04e2e3f2012-06-23 19:52:05 +10001336def getgeneratorlocals(generator):
1337 """
1338 Get the mapping of generator local variables to their current values.
1339
1340 A dict is returned, with the keys the local variable names and values the
1341 bound values."""
1342
1343 if not isgenerator(generator):
1344 raise TypeError("'{!r}' is not a Python generator".format(generator))
1345
1346 frame = getattr(generator, "gi_frame", None)
1347 if frame is not None:
1348 return generator.gi_frame.f_locals
1349 else:
1350 return {}
1351
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07001352###############################################################################
1353### Function Signature Object (PEP 362)
1354###############################################################################
1355
1356
1357_WrapperDescriptor = type(type.__call__)
1358_MethodWrapper = type(all.__call__)
1359
1360_NonUserDefinedCallables = (_WrapperDescriptor,
1361 _MethodWrapper,
1362 types.BuiltinFunctionType)
1363
1364
1365def _get_user_defined_method(cls, method_name):
1366 try:
1367 meth = getattr(cls, method_name)
1368 except AttributeError:
1369 return
1370 else:
1371 if not isinstance(meth, _NonUserDefinedCallables):
1372 # Once '__signature__' will be added to 'C'-level
1373 # callables, this check won't be necessary
1374 return meth
1375
1376
1377def signature(obj):
1378 '''Get a signature object for the passed callable.'''
1379
1380 if not callable(obj):
1381 raise TypeError('{!r} is not a callable object'.format(obj))
1382
1383 if isinstance(obj, types.MethodType):
1384 # In this case we skip the first parameter of the underlying
1385 # function (usually `self` or `cls`).
1386 sig = signature(obj.__func__)
1387 return sig.replace(parameters=tuple(sig.parameters.values())[1:])
1388
Nick Coghlane8c45d62013-07-28 20:00:01 +10001389 # Was this function wrapped by a decorator?
1390 obj = unwrap(obj, stop=(lambda f: hasattr(f, "__signature__")))
1391
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07001392 try:
1393 sig = obj.__signature__
1394 except AttributeError:
1395 pass
1396 else:
1397 if sig is not None:
1398 return sig
1399
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07001400
1401 if isinstance(obj, types.FunctionType):
1402 return Signature.from_function(obj)
1403
1404 if isinstance(obj, functools.partial):
1405 sig = signature(obj.func)
1406
1407 new_params = OrderedDict(sig.parameters.items())
1408
1409 partial_args = obj.args or ()
1410 partial_keywords = obj.keywords or {}
1411 try:
1412 ba = sig.bind_partial(*partial_args, **partial_keywords)
1413 except TypeError as ex:
1414 msg = 'partial object {!r} has incorrect arguments'.format(obj)
1415 raise ValueError(msg) from ex
1416
1417 for arg_name, arg_value in ba.arguments.items():
1418 param = new_params[arg_name]
1419 if arg_name in partial_keywords:
1420 # We set a new default value, because the following code
1421 # is correct:
1422 #
1423 # >>> def foo(a): print(a)
1424 # >>> print(partial(partial(foo, a=10), a=20)())
1425 # 20
1426 # >>> print(partial(partial(foo, a=10), a=20)(a=30))
1427 # 30
1428 #
1429 # So, with 'partial' objects, passing a keyword argument is
1430 # like setting a new default value for the corresponding
1431 # parameter
1432 #
1433 # We also mark this parameter with '_partial_kwarg'
1434 # flag. Later, in '_bind', the 'default' value of this
1435 # parameter will be added to 'kwargs', to simulate
1436 # the 'functools.partial' real call.
1437 new_params[arg_name] = param.replace(default=arg_value,
1438 _partial_kwarg=True)
1439
1440 elif (param.kind not in (_VAR_KEYWORD, _VAR_POSITIONAL) and
1441 not param._partial_kwarg):
1442 new_params.pop(arg_name)
1443
1444 return sig.replace(parameters=new_params.values())
1445
1446 sig = None
1447 if isinstance(obj, type):
1448 # obj is a class or a metaclass
1449
1450 # First, let's see if it has an overloaded __call__ defined
1451 # in its metaclass
1452 call = _get_user_defined_method(type(obj), '__call__')
1453 if call is not None:
1454 sig = signature(call)
1455 else:
1456 # Now we check if the 'obj' class has a '__new__' method
1457 new = _get_user_defined_method(obj, '__new__')
1458 if new is not None:
1459 sig = signature(new)
1460 else:
1461 # Finally, we should have at least __init__ implemented
1462 init = _get_user_defined_method(obj, '__init__')
1463 if init is not None:
1464 sig = signature(init)
1465 elif not isinstance(obj, _NonUserDefinedCallables):
1466 # An object with __call__
1467 # We also check that the 'obj' is not an instance of
1468 # _WrapperDescriptor or _MethodWrapper to avoid
1469 # infinite recursion (and even potential segfault)
1470 call = _get_user_defined_method(type(obj), '__call__')
1471 if call is not None:
1472 sig = signature(call)
1473
1474 if sig is not None:
1475 # For classes and objects we skip the first parameter of their
1476 # __call__, __new__, or __init__ methods
1477 return sig.replace(parameters=tuple(sig.parameters.values())[1:])
1478
1479 if isinstance(obj, types.BuiltinFunctionType):
1480 # Raise a nicer error message for builtins
1481 msg = 'no signature found for builtin function {!r}'.format(obj)
1482 raise ValueError(msg)
1483
1484 raise ValueError('callable {!r} is not supported by signature'.format(obj))
1485
1486
1487class _void:
1488 '''A private marker - used in Parameter & Signature'''
1489
1490
1491class _empty:
1492 pass
1493
1494
1495class _ParameterKind(int):
1496 def __new__(self, *args, name):
1497 obj = int.__new__(self, *args)
1498 obj._name = name
1499 return obj
1500
1501 def __str__(self):
1502 return self._name
1503
1504 def __repr__(self):
1505 return '<_ParameterKind: {!r}>'.format(self._name)
1506
1507
1508_POSITIONAL_ONLY = _ParameterKind(0, name='POSITIONAL_ONLY')
1509_POSITIONAL_OR_KEYWORD = _ParameterKind(1, name='POSITIONAL_OR_KEYWORD')
1510_VAR_POSITIONAL = _ParameterKind(2, name='VAR_POSITIONAL')
1511_KEYWORD_ONLY = _ParameterKind(3, name='KEYWORD_ONLY')
1512_VAR_KEYWORD = _ParameterKind(4, name='VAR_KEYWORD')
1513
1514
1515class Parameter:
1516 '''Represents a parameter in a function signature.
1517
1518 Has the following public attributes:
1519
1520 * name : str
1521 The name of the parameter as a string.
1522 * default : object
1523 The default value for the parameter if specified. If the
1524 parameter has no default value, this attribute is not set.
1525 * annotation
1526 The annotation for the parameter if specified. If the
1527 parameter has no annotation, this attribute is not set.
1528 * kind : str
1529 Describes how argument values are bound to the parameter.
1530 Possible values: `Parameter.POSITIONAL_ONLY`,
1531 `Parameter.POSITIONAL_OR_KEYWORD`, `Parameter.VAR_POSITIONAL`,
1532 `Parameter.KEYWORD_ONLY`, `Parameter.VAR_KEYWORD`.
1533 '''
1534
1535 __slots__ = ('_name', '_kind', '_default', '_annotation', '_partial_kwarg')
1536
1537 POSITIONAL_ONLY = _POSITIONAL_ONLY
1538 POSITIONAL_OR_KEYWORD = _POSITIONAL_OR_KEYWORD
1539 VAR_POSITIONAL = _VAR_POSITIONAL
1540 KEYWORD_ONLY = _KEYWORD_ONLY
1541 VAR_KEYWORD = _VAR_KEYWORD
1542
1543 empty = _empty
1544
1545 def __init__(self, name, kind, *, default=_empty, annotation=_empty,
1546 _partial_kwarg=False):
1547
1548 if kind not in (_POSITIONAL_ONLY, _POSITIONAL_OR_KEYWORD,
1549 _VAR_POSITIONAL, _KEYWORD_ONLY, _VAR_KEYWORD):
1550 raise ValueError("invalid value for 'Parameter.kind' attribute")
1551 self._kind = kind
1552
1553 if default is not _empty:
1554 if kind in (_VAR_POSITIONAL, _VAR_KEYWORD):
1555 msg = '{} parameters cannot have default values'.format(kind)
1556 raise ValueError(msg)
1557 self._default = default
1558 self._annotation = annotation
1559
1560 if name is None:
1561 if kind != _POSITIONAL_ONLY:
1562 raise ValueError("None is not a valid name for a "
1563 "non-positional-only parameter")
1564 self._name = name
1565 else:
1566 name = str(name)
1567 if kind != _POSITIONAL_ONLY and not name.isidentifier():
1568 msg = '{!r} is not a valid parameter name'.format(name)
1569 raise ValueError(msg)
1570 self._name = name
1571
1572 self._partial_kwarg = _partial_kwarg
1573
1574 @property
1575 def name(self):
1576 return self._name
1577
1578 @property
1579 def default(self):
1580 return self._default
1581
1582 @property
1583 def annotation(self):
1584 return self._annotation
1585
1586 @property
1587 def kind(self):
1588 return self._kind
1589
1590 def replace(self, *, name=_void, kind=_void, annotation=_void,
1591 default=_void, _partial_kwarg=_void):
1592 '''Creates a customized copy of the Parameter.'''
1593
1594 if name is _void:
1595 name = self._name
1596
1597 if kind is _void:
1598 kind = self._kind
1599
1600 if annotation is _void:
1601 annotation = self._annotation
1602
1603 if default is _void:
1604 default = self._default
1605
1606 if _partial_kwarg is _void:
1607 _partial_kwarg = self._partial_kwarg
1608
1609 return type(self)(name, kind, default=default, annotation=annotation,
1610 _partial_kwarg=_partial_kwarg)
1611
1612 def __str__(self):
1613 kind = self.kind
1614
1615 formatted = self._name
1616 if kind == _POSITIONAL_ONLY:
1617 if formatted is None:
1618 formatted = ''
1619 formatted = '<{}>'.format(formatted)
1620
1621 # Add annotation and default value
1622 if self._annotation is not _empty:
1623 formatted = '{}:{}'.format(formatted,
1624 formatannotation(self._annotation))
1625
1626 if self._default is not _empty:
1627 formatted = '{}={}'.format(formatted, repr(self._default))
1628
1629 if kind == _VAR_POSITIONAL:
1630 formatted = '*' + formatted
1631 elif kind == _VAR_KEYWORD:
1632 formatted = '**' + formatted
1633
1634 return formatted
1635
1636 def __repr__(self):
1637 return '<{} at {:#x} {!r}>'.format(self.__class__.__name__,
1638 id(self), self.name)
1639
1640 def __eq__(self, other):
1641 return (issubclass(other.__class__, Parameter) and
1642 self._name == other._name and
1643 self._kind == other._kind and
1644 self._default == other._default and
1645 self._annotation == other._annotation)
1646
1647 def __ne__(self, other):
1648 return not self.__eq__(other)
1649
1650
1651class BoundArguments:
1652 '''Result of `Signature.bind` call. Holds the mapping of arguments
1653 to the function's parameters.
1654
1655 Has the following public attributes:
1656
1657 * arguments : OrderedDict
1658 An ordered mutable mapping of parameters' names to arguments' values.
1659 Does not contain arguments' default values.
1660 * signature : Signature
1661 The Signature object that created this instance.
1662 * args : tuple
1663 Tuple of positional arguments values.
1664 * kwargs : dict
1665 Dict of keyword arguments values.
1666 '''
1667
1668 def __init__(self, signature, arguments):
1669 self.arguments = arguments
1670 self._signature = signature
1671
1672 @property
1673 def signature(self):
1674 return self._signature
1675
1676 @property
1677 def args(self):
1678 args = []
1679 for param_name, param in self._signature.parameters.items():
1680 if (param.kind in (_VAR_KEYWORD, _KEYWORD_ONLY) or
1681 param._partial_kwarg):
1682 # Keyword arguments mapped by 'functools.partial'
1683 # (Parameter._partial_kwarg is True) are mapped
1684 # in 'BoundArguments.kwargs', along with VAR_KEYWORD &
1685 # KEYWORD_ONLY
1686 break
1687
1688 try:
1689 arg = self.arguments[param_name]
1690 except KeyError:
1691 # We're done here. Other arguments
1692 # will be mapped in 'BoundArguments.kwargs'
1693 break
1694 else:
1695 if param.kind == _VAR_POSITIONAL:
1696 # *args
1697 args.extend(arg)
1698 else:
1699 # plain argument
1700 args.append(arg)
1701
1702 return tuple(args)
1703
1704 @property
1705 def kwargs(self):
1706 kwargs = {}
1707 kwargs_started = False
1708 for param_name, param in self._signature.parameters.items():
1709 if not kwargs_started:
1710 if (param.kind in (_VAR_KEYWORD, _KEYWORD_ONLY) or
1711 param._partial_kwarg):
1712 kwargs_started = True
1713 else:
1714 if param_name not in self.arguments:
1715 kwargs_started = True
1716 continue
1717
1718 if not kwargs_started:
1719 continue
1720
1721 try:
1722 arg = self.arguments[param_name]
1723 except KeyError:
1724 pass
1725 else:
1726 if param.kind == _VAR_KEYWORD:
1727 # **kwargs
1728 kwargs.update(arg)
1729 else:
1730 # plain keyword argument
1731 kwargs[param_name] = arg
1732
1733 return kwargs
1734
1735 def __eq__(self, other):
1736 return (issubclass(other.__class__, BoundArguments) and
1737 self.signature == other.signature and
1738 self.arguments == other.arguments)
1739
1740 def __ne__(self, other):
1741 return not self.__eq__(other)
1742
1743
1744class Signature:
1745 '''A Signature object represents the overall signature of a function.
1746 It stores a Parameter object for each parameter accepted by the
1747 function, as well as information specific to the function itself.
1748
1749 A Signature object has the following public attributes and methods:
1750
1751 * parameters : OrderedDict
1752 An ordered mapping of parameters' names to the corresponding
1753 Parameter objects (keyword-only arguments are in the same order
1754 as listed in `code.co_varnames`).
1755 * return_annotation : object
1756 The annotation for the return type of the function if specified.
1757 If the function has no annotation for its return type, this
1758 attribute is not set.
1759 * bind(*args, **kwargs) -> BoundArguments
1760 Creates a mapping from positional and keyword arguments to
1761 parameters.
1762 * bind_partial(*args, **kwargs) -> BoundArguments
1763 Creates a partial mapping from positional and keyword arguments
1764 to parameters (simulating 'functools.partial' behavior.)
1765 '''
1766
1767 __slots__ = ('_return_annotation', '_parameters')
1768
1769 _parameter_cls = Parameter
1770 _bound_arguments_cls = BoundArguments
1771
1772 empty = _empty
1773
1774 def __init__(self, parameters=None, *, return_annotation=_empty,
1775 __validate_parameters__=True):
1776 '''Constructs Signature from the given list of Parameter
1777 objects and 'return_annotation'. All arguments are optional.
1778 '''
1779
1780 if parameters is None:
1781 params = OrderedDict()
1782 else:
1783 if __validate_parameters__:
1784 params = OrderedDict()
1785 top_kind = _POSITIONAL_ONLY
1786
1787 for idx, param in enumerate(parameters):
1788 kind = param.kind
1789 if kind < top_kind:
1790 msg = 'wrong parameter order: {} before {}'
1791 msg = msg.format(top_kind, param.kind)
1792 raise ValueError(msg)
1793 else:
1794 top_kind = kind
1795
1796 name = param.name
1797 if name is None:
1798 name = str(idx)
1799 param = param.replace(name=name)
1800
1801 if name in params:
1802 msg = 'duplicate parameter name: {!r}'.format(name)
1803 raise ValueError(msg)
1804 params[name] = param
1805 else:
1806 params = OrderedDict(((param.name, param)
1807 for param in parameters))
1808
1809 self._parameters = types.MappingProxyType(params)
1810 self._return_annotation = return_annotation
1811
1812 @classmethod
1813 def from_function(cls, func):
1814 '''Constructs Signature for the given python function'''
1815
1816 if not isinstance(func, types.FunctionType):
1817 raise TypeError('{!r} is not a Python function'.format(func))
1818
1819 Parameter = cls._parameter_cls
1820
1821 # Parameter information.
1822 func_code = func.__code__
1823 pos_count = func_code.co_argcount
1824 arg_names = func_code.co_varnames
1825 positional = tuple(arg_names[:pos_count])
1826 keyword_only_count = func_code.co_kwonlyargcount
1827 keyword_only = arg_names[pos_count:(pos_count + keyword_only_count)]
1828 annotations = func.__annotations__
1829 defaults = func.__defaults__
1830 kwdefaults = func.__kwdefaults__
1831
1832 if defaults:
1833 pos_default_count = len(defaults)
1834 else:
1835 pos_default_count = 0
1836
1837 parameters = []
1838
1839 # Non-keyword-only parameters w/o defaults.
1840 non_default_count = pos_count - pos_default_count
1841 for name in positional[:non_default_count]:
1842 annotation = annotations.get(name, _empty)
1843 parameters.append(Parameter(name, annotation=annotation,
1844 kind=_POSITIONAL_OR_KEYWORD))
1845
1846 # ... w/ defaults.
1847 for offset, name in enumerate(positional[non_default_count:]):
1848 annotation = annotations.get(name, _empty)
1849 parameters.append(Parameter(name, annotation=annotation,
1850 kind=_POSITIONAL_OR_KEYWORD,
1851 default=defaults[offset]))
1852
1853 # *args
1854 if func_code.co_flags & 0x04:
1855 name = arg_names[pos_count + keyword_only_count]
1856 annotation = annotations.get(name, _empty)
1857 parameters.append(Parameter(name, annotation=annotation,
1858 kind=_VAR_POSITIONAL))
1859
1860 # Keyword-only parameters.
1861 for name in keyword_only:
1862 default = _empty
1863 if kwdefaults is not None:
1864 default = kwdefaults.get(name, _empty)
1865
1866 annotation = annotations.get(name, _empty)
1867 parameters.append(Parameter(name, annotation=annotation,
1868 kind=_KEYWORD_ONLY,
1869 default=default))
1870 # **kwargs
1871 if func_code.co_flags & 0x08:
1872 index = pos_count + keyword_only_count
1873 if func_code.co_flags & 0x04:
1874 index += 1
1875
1876 name = arg_names[index]
1877 annotation = annotations.get(name, _empty)
1878 parameters.append(Parameter(name, annotation=annotation,
1879 kind=_VAR_KEYWORD))
1880
1881 return cls(parameters,
1882 return_annotation=annotations.get('return', _empty),
1883 __validate_parameters__=False)
1884
1885 @property
1886 def parameters(self):
1887 return self._parameters
1888
1889 @property
1890 def return_annotation(self):
1891 return self._return_annotation
1892
1893 def replace(self, *, parameters=_void, return_annotation=_void):
1894 '''Creates a customized copy of the Signature.
1895 Pass 'parameters' and/or 'return_annotation' arguments
1896 to override them in the new copy.
1897 '''
1898
1899 if parameters is _void:
1900 parameters = self.parameters.values()
1901
1902 if return_annotation is _void:
1903 return_annotation = self._return_annotation
1904
1905 return type(self)(parameters,
1906 return_annotation=return_annotation)
1907
1908 def __eq__(self, other):
1909 if (not issubclass(type(other), Signature) or
1910 self.return_annotation != other.return_annotation or
1911 len(self.parameters) != len(other.parameters)):
1912 return False
1913
1914 other_positions = {param: idx
1915 for idx, param in enumerate(other.parameters.keys())}
1916
1917 for idx, (param_name, param) in enumerate(self.parameters.items()):
1918 if param.kind == _KEYWORD_ONLY:
1919 try:
1920 other_param = other.parameters[param_name]
1921 except KeyError:
1922 return False
1923 else:
1924 if param != other_param:
1925 return False
1926 else:
1927 try:
1928 other_idx = other_positions[param_name]
1929 except KeyError:
1930 return False
1931 else:
1932 if (idx != other_idx or
1933 param != other.parameters[param_name]):
1934 return False
1935
1936 return True
1937
1938 def __ne__(self, other):
1939 return not self.__eq__(other)
1940
1941 def _bind(self, args, kwargs, *, partial=False):
1942 '''Private method. Don't use directly.'''
1943
1944 arguments = OrderedDict()
1945
1946 parameters = iter(self.parameters.values())
1947 parameters_ex = ()
1948 arg_vals = iter(args)
1949
1950 if partial:
1951 # Support for binding arguments to 'functools.partial' objects.
1952 # See 'functools.partial' case in 'signature()' implementation
1953 # for details.
1954 for param_name, param in self.parameters.items():
1955 if (param._partial_kwarg and param_name not in kwargs):
1956 # Simulating 'functools.partial' behavior
1957 kwargs[param_name] = param.default
1958
1959 while True:
1960 # Let's iterate through the positional arguments and corresponding
1961 # parameters
1962 try:
1963 arg_val = next(arg_vals)
1964 except StopIteration:
1965 # No more positional arguments
1966 try:
1967 param = next(parameters)
1968 except StopIteration:
1969 # No more parameters. That's it. Just need to check that
1970 # we have no `kwargs` after this while loop
1971 break
1972 else:
1973 if param.kind == _VAR_POSITIONAL:
1974 # That's OK, just empty *args. Let's start parsing
1975 # kwargs
1976 break
1977 elif param.name in kwargs:
1978 if param.kind == _POSITIONAL_ONLY:
1979 msg = '{arg!r} parameter is positional only, ' \
1980 'but was passed as a keyword'
1981 msg = msg.format(arg=param.name)
1982 raise TypeError(msg) from None
1983 parameters_ex = (param,)
1984 break
1985 elif (param.kind == _VAR_KEYWORD or
1986 param.default is not _empty):
1987 # That's fine too - we have a default value for this
1988 # parameter. So, lets start parsing `kwargs`, starting
1989 # with the current parameter
1990 parameters_ex = (param,)
1991 break
1992 else:
1993 if partial:
1994 parameters_ex = (param,)
1995 break
1996 else:
1997 msg = '{arg!r} parameter lacking default value'
1998 msg = msg.format(arg=param.name)
1999 raise TypeError(msg) from None
2000 else:
2001 # We have a positional argument to process
2002 try:
2003 param = next(parameters)
2004 except StopIteration:
2005 raise TypeError('too many positional arguments') from None
2006 else:
2007 if param.kind in (_VAR_KEYWORD, _KEYWORD_ONLY):
2008 # Looks like we have no parameter for this positional
2009 # argument
2010 raise TypeError('too many positional arguments')
2011
2012 if param.kind == _VAR_POSITIONAL:
2013 # We have an '*args'-like argument, let's fill it with
2014 # all positional arguments we have left and move on to
2015 # the next phase
2016 values = [arg_val]
2017 values.extend(arg_vals)
2018 arguments[param.name] = tuple(values)
2019 break
2020
2021 if param.name in kwargs:
2022 raise TypeError('multiple values for argument '
2023 '{arg!r}'.format(arg=param.name))
2024
2025 arguments[param.name] = arg_val
2026
2027 # Now, we iterate through the remaining parameters to process
2028 # keyword arguments
2029 kwargs_param = None
2030 for param in itertools.chain(parameters_ex, parameters):
2031 if param.kind == _POSITIONAL_ONLY:
2032 # This should never happen in case of a properly built
2033 # Signature object (but let's have this check here
2034 # to ensure correct behaviour just in case)
2035 raise TypeError('{arg!r} parameter is positional only, '
2036 'but was passed as a keyword'. \
2037 format(arg=param.name))
2038
2039 if param.kind == _VAR_KEYWORD:
2040 # Memorize that we have a '**kwargs'-like parameter
2041 kwargs_param = param
2042 continue
2043
2044 param_name = param.name
2045 try:
2046 arg_val = kwargs.pop(param_name)
2047 except KeyError:
2048 # We have no value for this parameter. It's fine though,
2049 # if it has a default value, or it is an '*args'-like
2050 # parameter, left alone by the processing of positional
2051 # arguments.
2052 if (not partial and param.kind != _VAR_POSITIONAL and
2053 param.default is _empty):
2054 raise TypeError('{arg!r} parameter lacking default value'. \
2055 format(arg=param_name)) from None
2056
2057 else:
2058 arguments[param_name] = arg_val
2059
2060 if kwargs:
2061 if kwargs_param is not None:
2062 # Process our '**kwargs'-like parameter
2063 arguments[kwargs_param.name] = kwargs
2064 else:
2065 raise TypeError('too many keyword arguments')
2066
2067 return self._bound_arguments_cls(self, arguments)
2068
Antoine Pitroubd41d1b2013-01-29 21:20:57 +01002069 def bind(__bind_self, *args, **kwargs):
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002070 '''Get a BoundArguments object, that maps the passed `args`
2071 and `kwargs` to the function's signature. Raises `TypeError`
2072 if the passed arguments can not be bound.
2073 '''
Antoine Pitroubd41d1b2013-01-29 21:20:57 +01002074 return __bind_self._bind(args, kwargs)
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002075
Antoine Pitroubd41d1b2013-01-29 21:20:57 +01002076 def bind_partial(__bind_self, *args, **kwargs):
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002077 '''Get a BoundArguments object, that partially maps the
2078 passed `args` and `kwargs` to the function's signature.
2079 Raises `TypeError` if the passed arguments can not be bound.
2080 '''
Antoine Pitroubd41d1b2013-01-29 21:20:57 +01002081 return __bind_self._bind(args, kwargs, partial=True)
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002082
2083 def __str__(self):
2084 result = []
2085 render_kw_only_separator = True
2086 for idx, param in enumerate(self.parameters.values()):
2087 formatted = str(param)
2088
2089 kind = param.kind
2090 if kind == _VAR_POSITIONAL:
2091 # OK, we have an '*args'-like parameter, so we won't need
2092 # a '*' to separate keyword-only arguments
2093 render_kw_only_separator = False
2094 elif kind == _KEYWORD_ONLY and render_kw_only_separator:
2095 # We have a keyword-only parameter to render and we haven't
2096 # rendered an '*args'-like parameter before, so add a '*'
2097 # separator to the parameters list ("foo(arg1, *, arg2)" case)
2098 result.append('*')
2099 # This condition should be only triggered once, so
2100 # reset the flag
2101 render_kw_only_separator = False
2102
2103 result.append(formatted)
2104
2105 rendered = '({})'.format(', '.join(result))
2106
2107 if self.return_annotation is not _empty:
2108 anno = formatannotation(self.return_annotation)
2109 rendered += ' -> {}'.format(anno)
2110
2111 return rendered