blob: 484c9c358d30a236f248e3a1bcd68bf9d14d112d [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
Christian Heimes7131fd92008-02-19 14:21:46 +000034import imp
Brett Cannoncb66eb02012-05-11 12:58:42 -040035import importlib.machinery
36import itertools
Christian Heimes7131fd92008-02-19 14:21:46 +000037import linecache
Brett Cannoncb66eb02012-05-11 12:58:42 -040038import os
39import re
40import sys
41import tokenize
42import types
Brett Cannon2b88fcf2012-06-02 22:28:42 -040043import warnings
Larry Hastings7c7cbfc2012-06-22 15:19:35 -070044import functools
Raymond Hettingera1a992c2005-03-11 06:46:45 +000045from operator import attrgetter
Larry Hastings7c7cbfc2012-06-22 15:19:35 -070046from collections import namedtuple, OrderedDict
Nick Coghlan09c81232010-08-17 10:18:16 +000047
48# Create constants for the compiler flags in Include/code.h
49# We try to get them from dis to avoid duplication, but fall
50# back to hardcording so the dependency is optional
51try:
52 from dis import COMPILER_FLAG_NAMES as _flag_names
53except ImportError:
54 CO_OPTIMIZED, CO_NEWLOCALS = 0x1, 0x2
55 CO_VARARGS, CO_VARKEYWORDS = 0x4, 0x8
56 CO_NESTED, CO_GENERATOR, CO_NOFREE = 0x10, 0x20, 0x40
57else:
58 mod_dict = globals()
59 for k, v in _flag_names.items():
60 mod_dict["CO_" + v] = k
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +000061
Christian Heimesbe5b30b2008-03-03 19:18:51 +000062# See Include/object.h
63TPFLAGS_IS_ABSTRACT = 1 << 20
64
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +000065# ----------------------------------------------------------- type-checking
66def ismodule(object):
67 """Return true if the object is a module.
68
69 Module objects provide these attributes:
Barry Warsaw28a691b2010-04-17 00:19:56 +000070 __cached__ pathname to byte compiled file
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +000071 __doc__ documentation string
72 __file__ filename (missing for built-in modules)"""
Tim Peters28bc59f2001-09-16 08:40:16 +000073 return isinstance(object, types.ModuleType)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +000074
75def isclass(object):
76 """Return true if the object is a class.
77
78 Class objects provide these attributes:
79 __doc__ documentation string
80 __module__ name of module in which this class was defined"""
Benjamin Petersonc4656002009-01-17 22:41:18 +000081 return isinstance(object, type)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +000082
83def ismethod(object):
84 """Return true if the object is an instance method.
85
86 Instance method objects provide these attributes:
87 __doc__ documentation string
88 __name__ name with which this method was defined
Christian Heimesff737952007-11-27 10:40:20 +000089 __func__ function object containing implementation of method
90 __self__ instance to which this method is bound"""
Tim Peters28bc59f2001-09-16 08:40:16 +000091 return isinstance(object, types.MethodType)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +000092
Tim Peters536d2262001-09-20 05:13:38 +000093def ismethoddescriptor(object):
Tim Petersf1d90b92001-09-20 05:47:55 +000094 """Return true if the object is a method descriptor.
95
96 But not if ismethod() or isclass() or isfunction() are true.
Tim Peters536d2262001-09-20 05:13:38 +000097
98 This is new in Python 2.2, and, for example, is true of int.__add__.
99 An object passing this test has a __get__ attribute but not a __set__
100 attribute, but beyond that the set of attributes varies. __name__ is
101 usually sensible, and __doc__ often is.
102
Tim Petersf1d90b92001-09-20 05:47:55 +0000103 Methods implemented via descriptors that also pass one of the other
104 tests return false from the ismethoddescriptor() test, simply because
105 the other tests promise more -- you can, e.g., count on having the
Christian Heimesff737952007-11-27 10:40:20 +0000106 __func__ attribute (etc) when an object passes ismethod()."""
Antoine Pitrou86a8a9a2011-12-21 09:57:40 +0100107 if isclass(object) or ismethod(object) or isfunction(object):
108 # mutual exclusion
109 return False
110 tp = type(object)
111 return hasattr(tp, "__get__") and not hasattr(tp, "__set__")
Tim Peters536d2262001-09-20 05:13:38 +0000112
Martin v. Löwise59e2ba2003-05-03 09:09:02 +0000113def isdatadescriptor(object):
114 """Return true if the object is a data descriptor.
115
116 Data descriptors have both a __get__ and a __set__ attribute. Examples are
117 properties (defined in Python) and getsets and members (defined in C).
118 Typically, data descriptors will also have __name__ and __doc__ attributes
119 (properties, getsets, and members have both of these attributes), but this
120 is not guaranteed."""
Antoine Pitrou86a8a9a2011-12-21 09:57:40 +0100121 if isclass(object) or ismethod(object) or isfunction(object):
122 # mutual exclusion
123 return False
124 tp = type(object)
125 return hasattr(tp, "__set__") and hasattr(tp, "__get__")
Martin v. Löwise59e2ba2003-05-03 09:09:02 +0000126
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000127if hasattr(types, 'MemberDescriptorType'):
128 # CPython and equivalent
129 def ismemberdescriptor(object):
130 """Return true if the object is a member descriptor.
131
132 Member descriptors are specialized descriptors defined in extension
133 modules."""
134 return isinstance(object, types.MemberDescriptorType)
135else:
136 # Other implementations
137 def ismemberdescriptor(object):
138 """Return true if the object is a member descriptor.
139
140 Member descriptors are specialized descriptors defined in extension
141 modules."""
142 return False
143
144if hasattr(types, 'GetSetDescriptorType'):
145 # CPython and equivalent
146 def isgetsetdescriptor(object):
147 """Return true if the object is a getset descriptor.
148
149 getset descriptors are specialized descriptors defined in extension
150 modules."""
151 return isinstance(object, types.GetSetDescriptorType)
152else:
153 # Other implementations
154 def isgetsetdescriptor(object):
155 """Return true if the object is a getset descriptor.
156
157 getset descriptors are specialized descriptors defined in extension
158 modules."""
159 return False
160
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000161def isfunction(object):
162 """Return true if the object is a user-defined function.
163
164 Function objects provide these attributes:
165 __doc__ documentation string
166 __name__ name with which this function was defined
Neal Norwitz221085d2007-02-25 20:55:47 +0000167 __code__ code object containing compiled function bytecode
168 __defaults__ tuple of any default values for arguments
169 __globals__ global namespace in which this function was defined
170 __annotations__ dict of parameter annotations
171 __kwdefaults__ dict of keyword only parameters with defaults"""
Tim Peters28bc59f2001-09-16 08:40:16 +0000172 return isinstance(object, types.FunctionType)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000173
Christian Heimes7131fd92008-02-19 14:21:46 +0000174def isgeneratorfunction(object):
175 """Return true if the object is a user-defined generator function.
176
177 Generator function objects provides same attributes as functions.
178
Alexander Belopolsky977a6842010-08-16 20:17:07 +0000179 See help(isfunction) for attributes listing."""
Georg Brandlb1441c72009-01-03 22:33:39 +0000180 return bool((isfunction(object) or ismethod(object)) and
181 object.__code__.co_flags & CO_GENERATOR)
Christian Heimes7131fd92008-02-19 14:21:46 +0000182
183def isgenerator(object):
184 """Return true if the object is a generator.
185
186 Generator objects provide these attributes:
187 __iter__ defined to support interation over container
188 close raises a new GeneratorExit exception inside the
189 generator to terminate the iteration
190 gi_code code object
191 gi_frame frame object or possibly None once the generator has
192 been exhausted
193 gi_running set to 1 when generator is executing, 0 otherwise
194 next return the next item from the container
195 send resumes the generator and "sends" a value that becomes
196 the result of the current yield-expression
197 throw used to raise an exception inside the generator"""
198 return isinstance(object, types.GeneratorType)
199
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000200def istraceback(object):
201 """Return true if the object is a traceback.
202
203 Traceback objects provide these attributes:
204 tb_frame frame object at this level
205 tb_lasti index of last attempted instruction in bytecode
206 tb_lineno current line number in Python source code
207 tb_next next inner traceback object (called by this level)"""
Tim Peters28bc59f2001-09-16 08:40:16 +0000208 return isinstance(object, types.TracebackType)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000209
210def isframe(object):
211 """Return true if the object is a frame object.
212
213 Frame objects provide these attributes:
214 f_back next outer frame object (this frame's caller)
215 f_builtins built-in namespace seen by this frame
216 f_code code object being executed in this frame
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000217 f_globals global namespace seen by this frame
218 f_lasti index of last attempted instruction in bytecode
219 f_lineno current line number in Python source code
220 f_locals local namespace seen by this frame
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000221 f_trace tracing function for this frame, or None"""
Tim Peters28bc59f2001-09-16 08:40:16 +0000222 return isinstance(object, types.FrameType)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000223
224def iscode(object):
225 """Return true if the object is a code object.
226
227 Code objects provide these attributes:
228 co_argcount number of arguments (not including * or ** args)
229 co_code string of raw compiled bytecode
230 co_consts tuple of constants used in the bytecode
231 co_filename name of file in which this code object was created
232 co_firstlineno number of first line in Python source code
233 co_flags bitmap: 1=optimized | 2=newlocals | 4=*arg | 8=**arg
234 co_lnotab encoded mapping of line numbers to bytecode indices
235 co_name name with which this code object was defined
236 co_names tuple of names of local variables
237 co_nlocals number of local variables
238 co_stacksize virtual machine stack space required
239 co_varnames tuple of names of arguments and local variables"""
Tim Peters28bc59f2001-09-16 08:40:16 +0000240 return isinstance(object, types.CodeType)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000241
242def isbuiltin(object):
243 """Return true if the object is a built-in function or method.
244
245 Built-in functions and methods provide these attributes:
246 __doc__ documentation string
247 __name__ original name of this function or method
248 __self__ instance to which a method is bound, or None"""
Tim Peters28bc59f2001-09-16 08:40:16 +0000249 return isinstance(object, types.BuiltinFunctionType)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000250
251def isroutine(object):
252 """Return true if the object is any kind of function or method."""
Tim Peters536d2262001-09-20 05:13:38 +0000253 return (isbuiltin(object)
254 or isfunction(object)
255 or ismethod(object)
256 or ismethoddescriptor(object))
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000257
Christian Heimesbe5b30b2008-03-03 19:18:51 +0000258def isabstract(object):
259 """Return true if the object is an abstract base class (ABC)."""
Benjamin Petersona0dfa822009-11-13 02:25:08 +0000260 return bool(isinstance(object, type) and object.__flags__ & TPFLAGS_IS_ABSTRACT)
Christian Heimesbe5b30b2008-03-03 19:18:51 +0000261
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000262def getmembers(object, predicate=None):
263 """Return all members of an object as (name, value) pairs sorted by name.
264 Optionally, only return members that satisfy a given predicate."""
Antoine Pitrou86a8a9a2011-12-21 09:57:40 +0100265 if isclass(object):
266 mro = (object,) + getmro(object)
267 else:
268 mro = ()
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000269 results = []
270 for key in dir(object):
Antoine Pitrou86a8a9a2011-12-21 09:57:40 +0100271 # First try to get the value via __dict__. Some descriptors don't
272 # like calling their __get__ (see bug #1785).
273 for base in mro:
274 if key in base.__dict__:
275 value = base.__dict__[key]
276 break
277 else:
278 try:
279 value = getattr(object, key)
280 except AttributeError:
281 continue
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000282 if not predicate or predicate(value):
283 results.append((key, value))
284 results.sort()
285 return results
286
Christian Heimes25bb7832008-01-11 16:17:00 +0000287Attribute = namedtuple('Attribute', 'name kind defining_class object')
288
Tim Peters13b49d32001-09-23 02:00:29 +0000289def classify_class_attrs(cls):
290 """Return list of attribute-descriptor tuples.
291
292 For each name in dir(cls), the return list contains a 4-tuple
293 with these elements:
294
295 0. The name (a string).
296
297 1. The kind of attribute this is, one of these strings:
298 'class method' created via classmethod()
299 'static method' created via staticmethod()
300 'property' created via property()
301 'method' any other flavor of method
302 'data' not a method
303
304 2. The class which defined this attribute (a class).
305
306 3. The object as obtained directly from the defining class's
307 __dict__, not via getattr. This is especially important for
308 data attributes: C.data is just a data object, but
309 C.__dict__['data'] may be a data descriptor with additional
310 info, like a __doc__ string.
311 """
312
313 mro = getmro(cls)
314 names = dir(cls)
315 result = []
316 for name in names:
Antoine Pitrou86a8a9a2011-12-21 09:57:40 +0100317 # Get the object associated with the name, and where it was defined.
Tim Peters13b49d32001-09-23 02:00:29 +0000318 # Getting an obj from the __dict__ sometimes reveals more than
319 # using getattr. Static and class methods are dramatic examples.
Antoine Pitrou86a8a9a2011-12-21 09:57:40 +0100320 # Furthermore, some objects may raise an Exception when fetched with
321 # getattr(). This is the case with some descriptors (bug #1785).
322 # Thus, we only use getattr() as a last resort.
323 homecls = None
324 for base in (cls,) + mro:
325 if name in base.__dict__:
326 obj = base.__dict__[name]
327 homecls = base
328 break
Tim Peters13b49d32001-09-23 02:00:29 +0000329 else:
330 obj = getattr(cls, name)
Antoine Pitrou86a8a9a2011-12-21 09:57:40 +0100331 homecls = getattr(obj, "__objclass__", homecls)
Tim Peters13b49d32001-09-23 02:00:29 +0000332
333 # Classify the object.
334 if isinstance(obj, staticmethod):
335 kind = "static method"
336 elif isinstance(obj, classmethod):
337 kind = "class method"
338 elif isinstance(obj, property):
339 kind = "property"
Antoine Pitrou86a8a9a2011-12-21 09:57:40 +0100340 elif ismethoddescriptor(obj):
Tim Peters13b49d32001-09-23 02:00:29 +0000341 kind = "method"
Antoine Pitrou86a8a9a2011-12-21 09:57:40 +0100342 elif isdatadescriptor(obj):
Tim Peters13b49d32001-09-23 02:00:29 +0000343 kind = "data"
Antoine Pitrou86a8a9a2011-12-21 09:57:40 +0100344 else:
345 obj_via_getattr = getattr(cls, name)
346 if (isfunction(obj_via_getattr) or
347 ismethoddescriptor(obj_via_getattr)):
348 kind = "method"
349 else:
350 kind = "data"
351 obj = obj_via_getattr
Tim Peters13b49d32001-09-23 02:00:29 +0000352
Christian Heimes25bb7832008-01-11 16:17:00 +0000353 result.append(Attribute(name, kind, homecls, obj))
Tim Peters13b49d32001-09-23 02:00:29 +0000354
355 return result
356
Tim Peterse0b2d7a2001-09-22 06:10:55 +0000357# ----------------------------------------------------------- class helpers
Tim Peterse0b2d7a2001-09-22 06:10:55 +0000358
359def getmro(cls):
360 "Return tuple of base classes (including cls) in method resolution order."
Benjamin Petersonb82c8e52010-11-04 00:38:49 +0000361 return cls.__mro__
Tim Peterse0b2d7a2001-09-22 06:10:55 +0000362
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000363# -------------------------------------------------- source code extraction
364def indentsize(line):
365 """Return the indent size, in spaces, at the start of a line of text."""
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000366 expline = line.expandtabs()
367 return len(expline) - len(expline.lstrip())
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000368
369def getdoc(object):
370 """Get the documentation string for an object.
371
372 All tabs are expanded to spaces. To clean up docstrings that are
373 indented to line up with blocks of code, any whitespace than can be
374 uniformly removed from the second line onwards is removed."""
Tim Peters24008312002-03-17 18:56:20 +0000375 try:
376 doc = object.__doc__
377 except AttributeError:
378 return None
Guido van Rossum3172c5d2007-10-16 18:12:55 +0000379 if not isinstance(doc, str):
Tim Peters24008312002-03-17 18:56:20 +0000380 return None
Georg Brandl0c77a822008-06-10 16:37:50 +0000381 return cleandoc(doc)
382
383def cleandoc(doc):
384 """Clean up indentation from docstrings.
385
386 Any whitespace that can be uniformly removed from the second line
387 onwards is removed."""
Tim Peters24008312002-03-17 18:56:20 +0000388 try:
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000389 lines = doc.expandtabs().split('\n')
Tim Peters24008312002-03-17 18:56:20 +0000390 except UnicodeError:
391 return None
392 else:
Ka-Ping Yeea59ef7b2002-11-30 03:53:15 +0000393 # Find minimum indentation of any non-blank lines after first line.
Christian Heimesa37d4c62007-12-04 23:02:19 +0000394 margin = sys.maxsize
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000395 for line in lines[1:]:
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000396 content = len(line.lstrip())
Ka-Ping Yeea59ef7b2002-11-30 03:53:15 +0000397 if content:
398 indent = len(line) - content
399 margin = min(margin, indent)
400 # Remove indentation.
401 if lines:
402 lines[0] = lines[0].lstrip()
Christian Heimesa37d4c62007-12-04 23:02:19 +0000403 if margin < sys.maxsize:
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000404 for i in range(1, len(lines)): lines[i] = lines[i][margin:]
Ka-Ping Yeea59ef7b2002-11-30 03:53:15 +0000405 # Remove any trailing or leading blank lines.
406 while lines and not lines[-1]:
407 lines.pop()
408 while lines and not lines[0]:
409 lines.pop(0)
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000410 return '\n'.join(lines)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000411
412def getfile(object):
Ka-Ping Yeec113c242001-03-02 02:08:53 +0000413 """Work out which source or compiled file an object was defined in."""
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000414 if ismodule(object):
415 if hasattr(object, '__file__'):
416 return object.__file__
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +0000417 raise TypeError('{!r} is a built-in module'.format(object))
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000418 if isclass(object):
Ka-Ping Yeec99e0f12001-04-13 12:10:40 +0000419 object = sys.modules.get(object.__module__)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000420 if hasattr(object, '__file__'):
421 return object.__file__
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +0000422 raise TypeError('{!r} is a built-in class'.format(object))
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000423 if ismethod(object):
Christian Heimesff737952007-11-27 10:40:20 +0000424 object = object.__func__
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000425 if isfunction(object):
Neal Norwitz221085d2007-02-25 20:55:47 +0000426 object = object.__code__
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000427 if istraceback(object):
428 object = object.tb_frame
429 if isframe(object):
430 object = object.f_code
431 if iscode(object):
432 return object.co_filename
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +0000433 raise TypeError('{!r} is not a module, class, method, '
434 'function, traceback, frame, or code object'.format(object))
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000435
Christian Heimes25bb7832008-01-11 16:17:00 +0000436ModuleInfo = namedtuple('ModuleInfo', 'name suffix mode module_type')
437
Ka-Ping Yee4d6fc7f2001-04-10 11:43:00 +0000438def getmoduleinfo(path):
439 """Get the module name, suffix, mode, and module type for a given file."""
Brett Cannoncb66eb02012-05-11 12:58:42 -0400440 warnings.warn('inspect.getmoduleinfo() is deprecated', DeprecationWarning,
441 2)
Ka-Ping Yee4d6fc7f2001-04-10 11:43:00 +0000442 filename = os.path.basename(path)
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000443 suffixes = [(-len(suffix), suffix, mode, mtype)
444 for suffix, mode, mtype in imp.get_suffixes()]
Ka-Ping Yee4d6fc7f2001-04-10 11:43:00 +0000445 suffixes.sort() # try longest suffixes first, in case they overlap
446 for neglen, suffix, mode, mtype in suffixes:
447 if filename[neglen:] == suffix:
Christian Heimes25bb7832008-01-11 16:17:00 +0000448 return ModuleInfo(filename[:neglen], suffix, mode, mtype)
Ka-Ping Yee4d6fc7f2001-04-10 11:43:00 +0000449
450def getmodulename(path):
451 """Return the module name for a given file, or None."""
452 info = getmoduleinfo(path)
453 if info: return info[0]
454
Ka-Ping Yeec113c242001-03-02 02:08:53 +0000455def getsourcefile(object):
R. David Murraya1b37402010-06-17 02:04:29 +0000456 """Return the filename that can be used to locate an object's source.
457 Return None if no way can be identified to get the source.
458 """
Ka-Ping Yeec113c242001-03-02 02:08:53 +0000459 filename = getfile(object)
Brett Cannoncb66eb02012-05-11 12:58:42 -0400460 all_bytecode_suffixes = importlib.machinery.DEBUG_BYTECODE_SUFFIXES[:]
461 all_bytecode_suffixes += importlib.machinery.OPTIMIZED_BYTECODE_SUFFIXES[:]
462 if any(filename.endswith(s) for s in all_bytecode_suffixes):
463 filename = (os.path.splitext(filename)[0] +
464 importlib.machinery.SOURCE_SUFFIXES[0])
465 elif any(filename.endswith(s) for s in
466 importlib.machinery.EXTENSION_SUFFIXES):
467 return None
Thomas Wouters477c8d52006-05-27 19:21:47 +0000468 if os.path.exists(filename):
469 return filename
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000470 # only return a non-existent filename if the module has a PEP 302 loader
471 if hasattr(getmodule(object, filename), '__loader__'):
Ka-Ping Yeec113c242001-03-02 02:08:53 +0000472 return filename
R. David Murraya1b37402010-06-17 02:04:29 +0000473 # or it is in the linecache
474 if filename in linecache.cache:
475 return filename
Ka-Ping Yeec113c242001-03-02 02:08:53 +0000476
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000477def getabsfile(object, _filename=None):
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000478 """Return an absolute path to the source or compiled file for an object.
Ka-Ping Yeec113c242001-03-02 02:08:53 +0000479
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000480 The idea is for each object to have a unique origin, so this routine
481 normalizes the result as much as possible."""
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000482 if _filename is None:
483 _filename = getsourcefile(object) or getfile(object)
484 return os.path.normcase(os.path.abspath(_filename))
Ka-Ping Yeec113c242001-03-02 02:08:53 +0000485
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000486modulesbyfile = {}
Thomas Wouters89f507f2006-12-13 04:49:30 +0000487_filesbymodname = {}
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000488
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000489def getmodule(object, _filename=None):
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000490 """Return the module an object was defined in, or None if not found."""
Ka-Ping Yee202c99b2001-04-13 09:15:08 +0000491 if ismodule(object):
492 return object
Johannes Gijsbers93245262004-09-11 15:53:22 +0000493 if hasattr(object, '__module__'):
Ka-Ping Yee8b58b842001-03-01 13:56:16 +0000494 return sys.modules.get(object.__module__)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000495 # Try the filename to modulename cache
496 if _filename is not None and _filename in modulesbyfile:
497 return sys.modules.get(modulesbyfile[_filename])
498 # Try the cache again with the absolute file name
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000499 try:
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000500 file = getabsfile(object, _filename)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000501 except TypeError:
502 return None
Raymond Hettinger54f02222002-06-01 14:18:47 +0000503 if file in modulesbyfile:
Ka-Ping Yeeb38bbbd2003-03-28 16:29:50 +0000504 return sys.modules.get(modulesbyfile[file])
Thomas Wouters89f507f2006-12-13 04:49:30 +0000505 # Update the filename to module name cache and check yet again
506 # Copy sys.modules in order to cope with changes while iterating
Éric Araujoa74f8ef2011-11-29 16:58:53 +0100507 for modname, module in list(sys.modules.items()):
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000508 if ismodule(module) and hasattr(module, '__file__'):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000509 f = module.__file__
510 if f == _filesbymodname.get(modname, None):
511 # Have already mapped this module, so skip it
512 continue
513 _filesbymodname[modname] = f
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000514 f = getabsfile(module)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000515 # Always map to the name the module knows itself by
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000516 modulesbyfile[f] = modulesbyfile[
517 os.path.realpath(f)] = module.__name__
Raymond Hettinger54f02222002-06-01 14:18:47 +0000518 if file in modulesbyfile:
Ka-Ping Yeeb38bbbd2003-03-28 16:29:50 +0000519 return sys.modules.get(modulesbyfile[file])
Thomas Wouters89f507f2006-12-13 04:49:30 +0000520 # Check the main module
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000521 main = sys.modules['__main__']
Brett Cannon4a671fe2003-06-15 22:33:28 +0000522 if not hasattr(object, '__name__'):
523 return None
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000524 if hasattr(main, object.__name__):
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000525 mainobject = getattr(main, object.__name__)
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000526 if mainobject is object:
527 return main
Thomas Wouters89f507f2006-12-13 04:49:30 +0000528 # Check builtins
Georg Brandl1a3284e2007-12-02 09:40:06 +0000529 builtin = sys.modules['builtins']
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000530 if hasattr(builtin, object.__name__):
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000531 builtinobject = getattr(builtin, object.__name__)
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000532 if builtinobject is object:
533 return builtin
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000534
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000535def findsource(object):
536 """Return the entire source file and starting line number for an object.
537
538 The argument may be a module, class, method, function, traceback, frame,
539 or code object. The source code is returned as a list of all the lines
540 in the file and the line number indexes a line in that list. An IOError
541 is raised if the source code cannot be retrieved."""
Benjamin Peterson9620cc02011-06-11 15:53:11 -0500542
543 file = getfile(object)
544 sourcefile = getsourcefile(object)
545 if not sourcefile and file[0] + file[-1] != '<>':
R. David Murray74b89242009-05-13 17:33:03 +0000546 raise IOError('source code not available')
Benjamin Peterson9620cc02011-06-11 15:53:11 -0500547 file = sourcefile if sourcefile else file
548
Thomas Wouters89f507f2006-12-13 04:49:30 +0000549 module = getmodule(object, file)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000550 if module:
551 lines = linecache.getlines(file, module.__dict__)
552 else:
553 lines = linecache.getlines(file)
Neil Schemenauerf06f8532002-03-23 23:51:04 +0000554 if not lines:
Jeremy Hyltonab919022003-06-27 18:41:20 +0000555 raise IOError('could not get source code')
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000556
557 if ismodule(object):
558 return lines, 0
559
560 if isclass(object):
561 name = object.__name__
Thomas Wouters89f507f2006-12-13 04:49:30 +0000562 pat = re.compile(r'^(\s*)class\s*' + name + r'\b')
563 # make some effort to find the best matching class definition:
564 # use the one with the least indentation, which is the one
565 # that's most probably not inside a function definition.
566 candidates = []
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000567 for i in range(len(lines)):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000568 match = pat.match(lines[i])
569 if match:
570 # if it's at toplevel, it's already the best one
571 if lines[i][0] == 'c':
572 return lines, i
573 # else add whitespace to candidate list
574 candidates.append((match.group(1), i))
575 if candidates:
576 # this will sort by whitespace, and by line number,
577 # less whitespace first
578 candidates.sort()
579 return lines, candidates[0][1]
Jeremy Hyltonab919022003-06-27 18:41:20 +0000580 else:
581 raise IOError('could not find class definition')
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000582
583 if ismethod(object):
Christian Heimesff737952007-11-27 10:40:20 +0000584 object = object.__func__
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000585 if isfunction(object):
Neal Norwitz221085d2007-02-25 20:55:47 +0000586 object = object.__code__
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000587 if istraceback(object):
588 object = object.tb_frame
589 if isframe(object):
590 object = object.f_code
591 if iscode(object):
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000592 if not hasattr(object, 'co_firstlineno'):
Jeremy Hyltonab919022003-06-27 18:41:20 +0000593 raise IOError('could not find function definition')
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000594 lnum = object.co_firstlineno - 1
Johannes Gijsbers1542f342004-12-12 16:46:28 +0000595 pat = re.compile(r'^(\s*def\s)|(.*(?<!\w)lambda(:|\s))|^(\s*@)')
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000596 while lnum > 0:
Ka-Ping Yeea6e59712001-03-10 09:31:55 +0000597 if pat.match(lines[lnum]): break
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000598 lnum = lnum - 1
599 return lines, lnum
Jeremy Hyltonab919022003-06-27 18:41:20 +0000600 raise IOError('could not find code object')
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000601
602def getcomments(object):
Jeremy Hyltonb4c17c82002-03-28 23:01:56 +0000603 """Get lines of comments immediately preceding an object's source code.
604
605 Returns None when source can't be found.
606 """
607 try:
608 lines, lnum = findsource(object)
609 except (IOError, TypeError):
610 return None
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000611
612 if ismodule(object):
613 # Look for a comment block at the top of the file.
614 start = 0
Ka-Ping Yeeb910efe2001-04-12 13:17:17 +0000615 if lines and lines[0][:2] == '#!': start = 1
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000616 while start < len(lines) and lines[start].strip() in ('', '#'):
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000617 start = start + 1
Ka-Ping Yeeb910efe2001-04-12 13:17:17 +0000618 if start < len(lines) and lines[start][:1] == '#':
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000619 comments = []
620 end = start
621 while end < len(lines) and lines[end][:1] == '#':
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000622 comments.append(lines[end].expandtabs())
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000623 end = end + 1
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000624 return ''.join(comments)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000625
626 # Look for a preceding block of comments at the same indentation.
627 elif lnum > 0:
628 indent = indentsize(lines[lnum])
629 end = lnum - 1
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000630 if end >= 0 and lines[end].lstrip()[:1] == '#' and \
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000631 indentsize(lines[end]) == indent:
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000632 comments = [lines[end].expandtabs().lstrip()]
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000633 if end > 0:
634 end = end - 1
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000635 comment = lines[end].expandtabs().lstrip()
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000636 while comment[:1] == '#' and indentsize(lines[end]) == indent:
637 comments[:0] = [comment]
638 end = end - 1
639 if end < 0: break
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000640 comment = lines[end].expandtabs().lstrip()
641 while comments and comments[0].strip() == '#':
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000642 comments[:1] = []
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000643 while comments and comments[-1].strip() == '#':
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000644 comments[-1:] = []
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000645 return ''.join(comments)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000646
Tim Peters4efb6e92001-06-29 23:51:08 +0000647class EndOfBlock(Exception): pass
648
649class BlockFinder:
650 """Provide a tokeneater() method to detect the end of a code block."""
651 def __init__(self):
652 self.indent = 0
Johannes Gijsbersa5855d52005-03-12 16:37:11 +0000653 self.islambda = False
Johannes Gijsbers1542f342004-12-12 16:46:28 +0000654 self.started = False
655 self.passline = False
Armin Rigodd5c0232005-09-25 11:45:45 +0000656 self.last = 1
Tim Peters4efb6e92001-06-29 23:51:08 +0000657
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000658 def tokeneater(self, type, token, srowcol, erowcol, line):
Tim Peters4efb6e92001-06-29 23:51:08 +0000659 if not self.started:
Armin Rigodd5c0232005-09-25 11:45:45 +0000660 # look for the first "def", "class" or "lambda"
Johannes Gijsbers1542f342004-12-12 16:46:28 +0000661 if token in ("def", "class", "lambda"):
Johannes Gijsbersa5855d52005-03-12 16:37:11 +0000662 if token == "lambda":
663 self.islambda = True
Johannes Gijsbers1542f342004-12-12 16:46:28 +0000664 self.started = True
Armin Rigodd5c0232005-09-25 11:45:45 +0000665 self.passline = True # skip to the end of the line
Tim Peters4efb6e92001-06-29 23:51:08 +0000666 elif type == tokenize.NEWLINE:
Armin Rigodd5c0232005-09-25 11:45:45 +0000667 self.passline = False # stop skipping when a NEWLINE is seen
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000668 self.last = srowcol[0]
Armin Rigodd5c0232005-09-25 11:45:45 +0000669 if self.islambda: # lambdas always end at the first NEWLINE
670 raise EndOfBlock
Johannes Gijsbers1542f342004-12-12 16:46:28 +0000671 elif self.passline:
672 pass
Tim Peters4efb6e92001-06-29 23:51:08 +0000673 elif type == tokenize.INDENT:
674 self.indent = self.indent + 1
Johannes Gijsbers1542f342004-12-12 16:46:28 +0000675 self.passline = True
Tim Peters4efb6e92001-06-29 23:51:08 +0000676 elif type == tokenize.DEDENT:
677 self.indent = self.indent - 1
Armin Rigodd5c0232005-09-25 11:45:45 +0000678 # the end of matching indent/dedent pairs end a block
679 # (note that this only works for "def"/"class" blocks,
680 # not e.g. for "if: else:" or "try: finally:" blocks)
681 if self.indent <= 0:
682 raise EndOfBlock
683 elif self.indent == 0 and type not in (tokenize.COMMENT, tokenize.NL):
684 # any other token on the same indentation level end the previous
685 # block as well, except the pseudo-tokens COMMENT and NL.
686 raise EndOfBlock
Tim Peters4efb6e92001-06-29 23:51:08 +0000687
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000688def getblock(lines):
689 """Extract the block of code at the top of the given list of lines."""
Armin Rigodd5c0232005-09-25 11:45:45 +0000690 blockfinder = BlockFinder()
Tim Peters4efb6e92001-06-29 23:51:08 +0000691 try:
Trent Nelson428de652008-03-18 22:41:35 +0000692 tokens = tokenize.generate_tokens(iter(lines).__next__)
693 for _token in tokens:
694 blockfinder.tokeneater(*_token)
Armin Rigodd5c0232005-09-25 11:45:45 +0000695 except (EndOfBlock, IndentationError):
696 pass
697 return lines[:blockfinder.last]
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000698
699def getsourcelines(object):
700 """Return a list of source lines and starting line number for an object.
701
702 The argument may be a module, class, method, function, traceback, frame,
703 or code object. The source code is returned as a list of the lines
704 corresponding to the object and the line number indicates where in the
705 original source file the first line of code was found. An IOError is
706 raised if the source code cannot be retrieved."""
707 lines, lnum = findsource(object)
708
709 if ismodule(object): return lines, 0
710 else: return getblock(lines[lnum:]), lnum + 1
711
712def getsource(object):
713 """Return the text of the source code for an object.
714
715 The argument may be a module, class, method, function, traceback, frame,
716 or code object. The source code is returned as a single string. An
717 IOError is raised if the source code cannot be retrieved."""
718 lines, lnum = getsourcelines(object)
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000719 return ''.join(lines)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000720
721# --------------------------------------------------- class tree extraction
722def walktree(classes, children, parent):
723 """Recursive helper function for getclasstree()."""
724 results = []
Raymond Hettingera1a992c2005-03-11 06:46:45 +0000725 classes.sort(key=attrgetter('__module__', '__name__'))
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000726 for c in classes:
727 results.append((c, c.__bases__))
Raymond Hettinger54f02222002-06-01 14:18:47 +0000728 if c in children:
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000729 results.append(walktree(children[c], children, c))
730 return results
731
Georg Brandl5ce83a02009-06-01 17:23:51 +0000732def getclasstree(classes, unique=False):
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000733 """Arrange the given list of classes into a hierarchy of nested lists.
734
735 Where a nested list appears, it contains classes derived from the class
736 whose entry immediately precedes the list. Each entry is a 2-tuple
737 containing a class and a tuple of its base classes. If the 'unique'
738 argument is true, exactly one entry appears in the returned structure
739 for each class in the given list. Otherwise, classes using multiple
740 inheritance and their descendants will appear multiple times."""
741 children = {}
742 roots = []
743 for c in classes:
744 if c.__bases__:
745 for parent in c.__bases__:
Raymond Hettinger54f02222002-06-01 14:18:47 +0000746 if not parent in children:
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000747 children[parent] = []
748 children[parent].append(c)
749 if unique and parent in classes: break
750 elif c not in roots:
751 roots.append(c)
Raymond Hettingere0d49722002-06-02 18:55:56 +0000752 for parent in children:
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000753 if parent not in classes:
754 roots.append(parent)
755 return walktree(roots, children, None)
756
757# ------------------------------------------------ argument list extraction
Christian Heimes25bb7832008-01-11 16:17:00 +0000758Arguments = namedtuple('Arguments', 'args, varargs, varkw')
759
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000760def getargs(co):
761 """Get information about the arguments accepted by a code object.
762
Guido van Rossum2e65f892007-02-28 22:03:49 +0000763 Three things are returned: (args, varargs, varkw), where
Georg Brandlc1c4bf82010-10-15 16:07:41 +0000764 'args' is the list of argument names. Keyword-only arguments are
765 appended. 'varargs' and 'varkw' are the names of the * and **
766 arguments or None."""
Guido van Rossum2e65f892007-02-28 22:03:49 +0000767 args, varargs, kwonlyargs, varkw = _getfullargs(co)
Christian Heimes25bb7832008-01-11 16:17:00 +0000768 return Arguments(args + kwonlyargs, varargs, varkw)
Guido van Rossum2e65f892007-02-28 22:03:49 +0000769
770def _getfullargs(co):
771 """Get information about the arguments accepted by a code object.
772
773 Four things are returned: (args, varargs, kwonlyargs, varkw), where
Georg Brandlc1c4bf82010-10-15 16:07:41 +0000774 'args' and 'kwonlyargs' are lists of argument names, and 'varargs'
775 and 'varkw' are the names of the * and ** arguments or None."""
Jeremy Hylton64967882003-06-27 18:14:39 +0000776
777 if not iscode(co):
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +0000778 raise TypeError('{!r} is not a code object'.format(co))
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000779
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000780 nargs = co.co_argcount
781 names = co.co_varnames
Guido van Rossum2e65f892007-02-28 22:03:49 +0000782 nkwargs = co.co_kwonlyargcount
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000783 args = list(names[:nargs])
Guido van Rossum2e65f892007-02-28 22:03:49 +0000784 kwonlyargs = list(names[nargs:nargs+nkwargs])
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000785 step = 0
786
Guido van Rossum2e65f892007-02-28 22:03:49 +0000787 nargs += nkwargs
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000788 varargs = None
789 if co.co_flags & CO_VARARGS:
790 varargs = co.co_varnames[nargs]
791 nargs = nargs + 1
792 varkw = None
793 if co.co_flags & CO_VARKEYWORDS:
794 varkw = co.co_varnames[nargs]
Guido van Rossum2e65f892007-02-28 22:03:49 +0000795 return args, varargs, kwonlyargs, varkw
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000796
Christian Heimes25bb7832008-01-11 16:17:00 +0000797
798ArgSpec = namedtuple('ArgSpec', 'args varargs keywords defaults')
799
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000800def getargspec(func):
801 """Get the names and default values of a function's arguments.
802
803 A tuple of four things is returned: (args, varargs, varkw, defaults).
Georg Brandlc1c4bf82010-10-15 16:07:41 +0000804 'args' is a list of the argument names.
Guido van Rossum2e65f892007-02-28 22:03:49 +0000805 'args' will include keyword-only argument names.
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000806 'varargs' and 'varkw' are the names of the * and ** arguments or None.
Jeremy Hylton64967882003-06-27 18:14:39 +0000807 'defaults' is an n-tuple of the default values of the last n arguments.
Guido van Rossuma8add0e2007-05-14 22:03:55 +0000808
Guido van Rossum2e65f892007-02-28 22:03:49 +0000809 Use the getfullargspec() API for Python-3000 code, as annotations
810 and keyword arguments are supported. getargspec() will raise ValueError
811 if the func has either annotations or keyword arguments.
812 """
813
814 args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults, ann = \
815 getfullargspec(func)
816 if kwonlyargs or ann:
Collin Winterce36ad82007-08-30 01:19:48 +0000817 raise ValueError("Function has keyword-only arguments or annotations"
818 ", use getfullargspec() API which can support them")
Christian Heimes25bb7832008-01-11 16:17:00 +0000819 return ArgSpec(args, varargs, varkw, defaults)
820
821FullArgSpec = namedtuple('FullArgSpec',
Benjamin Peterson3d4ca742008-11-12 21:39:01 +0000822 'args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults, annotations')
Guido van Rossum2e65f892007-02-28 22:03:49 +0000823
824def getfullargspec(func):
825 """Get the names and default values of a function's arguments.
826
Brett Cannon504d8852007-09-07 02:12:14 +0000827 A tuple of seven things is returned:
828 (args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults annotations).
Georg Brandlc1c4bf82010-10-15 16:07:41 +0000829 'args' is a list of the argument names.
Guido van Rossum2e65f892007-02-28 22:03:49 +0000830 'varargs' and 'varkw' are the names of the * and ** arguments or None.
831 'defaults' is an n-tuple of the default values of the last n arguments.
832 'kwonlyargs' is a list of keyword-only argument names.
833 'kwonlydefaults' is a dictionary mapping names from kwonlyargs to defaults.
834 'annotations' is a dictionary mapping argument names to annotations.
Guido van Rossuma8add0e2007-05-14 22:03:55 +0000835
Guido van Rossum2e65f892007-02-28 22:03:49 +0000836 The first four items in the tuple correspond to getargspec().
Jeremy Hylton64967882003-06-27 18:14:39 +0000837 """
838
839 if ismethod(func):
Christian Heimesff737952007-11-27 10:40:20 +0000840 func = func.__func__
Jeremy Hylton64967882003-06-27 18:14:39 +0000841 if not isfunction(func):
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +0000842 raise TypeError('{!r} is not a Python function'.format(func))
Guido van Rossum2e65f892007-02-28 22:03:49 +0000843 args, varargs, kwonlyargs, varkw = _getfullargs(func.__code__)
Christian Heimes25bb7832008-01-11 16:17:00 +0000844 return FullArgSpec(args, varargs, varkw, func.__defaults__,
Guido van Rossum2e65f892007-02-28 22:03:49 +0000845 kwonlyargs, func.__kwdefaults__, func.__annotations__)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000846
Christian Heimes25bb7832008-01-11 16:17:00 +0000847ArgInfo = namedtuple('ArgInfo', 'args varargs keywords locals')
848
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000849def getargvalues(frame):
850 """Get information about arguments passed into a particular frame.
851
852 A tuple of four things is returned: (args, varargs, varkw, locals).
Georg Brandlc1c4bf82010-10-15 16:07:41 +0000853 'args' is a list of the argument names.
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000854 'varargs' and 'varkw' are the names of the * and ** arguments or None.
855 'locals' is the locals dictionary of the given frame."""
856 args, varargs, varkw = getargs(frame.f_code)
Benjamin Peterson1a6e0d02008-10-25 15:49:17 +0000857 return ArgInfo(args, varargs, varkw, frame.f_locals)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000858
Guido van Rossum2e65f892007-02-28 22:03:49 +0000859def formatannotation(annotation, base_module=None):
860 if isinstance(annotation, type):
Georg Brandl1a3284e2007-12-02 09:40:06 +0000861 if annotation.__module__ in ('builtins', base_module):
Guido van Rossum2e65f892007-02-28 22:03:49 +0000862 return annotation.__name__
863 return annotation.__module__+'.'+annotation.__name__
864 return repr(annotation)
Guido van Rossuma8add0e2007-05-14 22:03:55 +0000865
Guido van Rossum2e65f892007-02-28 22:03:49 +0000866def formatannotationrelativeto(object):
Guido van Rossuma8add0e2007-05-14 22:03:55 +0000867 module = getattr(object, '__module__', None)
868 def _formatannotation(annotation):
869 return formatannotation(annotation, module)
870 return _formatannotation
Guido van Rossum2e65f892007-02-28 22:03:49 +0000871
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000872def formatargspec(args, varargs=None, varkw=None, defaults=None,
Guido van Rossum2e65f892007-02-28 22:03:49 +0000873 kwonlyargs=(), kwonlydefaults={}, annotations={},
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000874 formatarg=str,
875 formatvarargs=lambda name: '*' + name,
876 formatvarkw=lambda name: '**' + name,
877 formatvalue=lambda value: '=' + repr(value),
Guido van Rossum2e65f892007-02-28 22:03:49 +0000878 formatreturns=lambda text: ' -> ' + text,
Georg Brandlc1c4bf82010-10-15 16:07:41 +0000879 formatannotation=formatannotation):
Guido van Rossuma8add0e2007-05-14 22:03:55 +0000880 """Format an argument spec from the values returned by getargspec
Guido van Rossum2e65f892007-02-28 22:03:49 +0000881 or getfullargspec.
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000882
Guido van Rossum2e65f892007-02-28 22:03:49 +0000883 The first seven arguments are (args, varargs, varkw, defaults,
884 kwonlyargs, kwonlydefaults, annotations). The other five arguments
885 are the corresponding optional formatting functions that are called to
886 turn names and values into strings. The last argument is an optional
887 function to format the sequence of arguments."""
888 def formatargandannotation(arg):
889 result = formatarg(arg)
890 if arg in annotations:
891 result += ': ' + formatannotation(annotations[arg])
892 return result
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000893 specs = []
894 if defaults:
895 firstdefault = len(args) - len(defaults)
Benjamin Petersonb58dda72009-01-18 22:27:04 +0000896 for i, arg in enumerate(args):
Georg Brandlc1c4bf82010-10-15 16:07:41 +0000897 spec = formatargandannotation(arg)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000898 if defaults and i >= firstdefault:
899 spec = spec + formatvalue(defaults[i - firstdefault])
900 specs.append(spec)
Raymond Hettinger936654b2002-06-01 03:06:31 +0000901 if varargs is not None:
Guido van Rossum2e65f892007-02-28 22:03:49 +0000902 specs.append(formatvarargs(formatargandannotation(varargs)))
903 else:
904 if kwonlyargs:
905 specs.append('*')
906 if kwonlyargs:
907 for kwonlyarg in kwonlyargs:
908 spec = formatargandannotation(kwonlyarg)
Benjamin Peterson9953a8d2009-01-17 04:15:01 +0000909 if kwonlydefaults and kwonlyarg in kwonlydefaults:
Guido van Rossum2e65f892007-02-28 22:03:49 +0000910 spec += formatvalue(kwonlydefaults[kwonlyarg])
911 specs.append(spec)
Raymond Hettinger936654b2002-06-01 03:06:31 +0000912 if varkw is not None:
Guido van Rossum2e65f892007-02-28 22:03:49 +0000913 specs.append(formatvarkw(formatargandannotation(varkw)))
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000914 result = '(' + ', '.join(specs) + ')'
Guido van Rossum2e65f892007-02-28 22:03:49 +0000915 if 'return' in annotations:
916 result += formatreturns(formatannotation(annotations['return']))
917 return result
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000918
919def formatargvalues(args, varargs, varkw, locals,
920 formatarg=str,
921 formatvarargs=lambda name: '*' + name,
922 formatvarkw=lambda name: '**' + name,
Georg Brandlc1c4bf82010-10-15 16:07:41 +0000923 formatvalue=lambda value: '=' + repr(value)):
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000924 """Format an argument spec from the 4 values returned by getargvalues.
925
926 The first four arguments are (args, varargs, varkw, locals). The
927 next four arguments are the corresponding optional formatting functions
928 that are called to turn names and values into strings. The ninth
929 argument is an optional function to format the sequence of arguments."""
930 def convert(name, locals=locals,
931 formatarg=formatarg, formatvalue=formatvalue):
932 return formatarg(name) + formatvalue(locals[name])
933 specs = []
934 for i in range(len(args)):
Georg Brandlc1c4bf82010-10-15 16:07:41 +0000935 specs.append(convert(args[i]))
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000936 if varargs:
937 specs.append(formatvarargs(varargs) + formatvalue(locals[varargs]))
938 if varkw:
939 specs.append(formatvarkw(varkw) + formatvalue(locals[varkw]))
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000940 return '(' + ', '.join(specs) + ')'
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000941
Benjamin Petersone109c702011-06-24 09:37:26 -0500942def _missing_arguments(f_name, argnames, pos, values):
943 names = [repr(name) for name in argnames if name not in values]
944 missing = len(names)
945 if missing == 1:
946 s = names[0]
947 elif missing == 2:
948 s = "{} and {}".format(*names)
949 else:
950 tail = ", {} and {}".format(names[-2:])
951 del names[-2:]
952 s = ", ".join(names) + tail
953 raise TypeError("%s() missing %i required %s argument%s: %s" %
954 (f_name, missing,
955 "positional" if pos else "keyword-only",
956 "" if missing == 1 else "s", s))
957
958def _too_many(f_name, args, kwonly, varargs, defcount, given, values):
Benjamin Petersonb204a422011-06-05 22:04:07 -0500959 atleast = len(args) - defcount
Benjamin Petersonb204a422011-06-05 22:04:07 -0500960 kwonly_given = len([arg for arg in kwonly if arg in values])
961 if varargs:
962 plural = atleast != 1
963 sig = "at least %d" % (atleast,)
964 elif defcount:
965 plural = True
966 sig = "from %d to %d" % (atleast, len(args))
967 else:
968 plural = len(args) != 1
969 sig = str(len(args))
970 kwonly_sig = ""
971 if kwonly_given:
972 msg = " positional argument%s (and %d keyword-only argument%s)"
973 kwonly_sig = (msg % ("s" if given != 1 else "", kwonly_given,
974 "s" if kwonly_given != 1 else ""))
975 raise TypeError("%s() takes %s positional argument%s but %d%s %s given" %
976 (f_name, sig, "s" if plural else "", given, kwonly_sig,
977 "was" if given == 1 and not kwonly_given else "were"))
978
Benjamin Peterson25cd7eb2010-03-30 18:42:32 +0000979def getcallargs(func, *positional, **named):
980 """Get the mapping of arguments to values.
981
982 A dict is returned, with keys the function argument names (including the
983 names of the * and ** arguments, if any), and values the respective bound
984 values from 'positional' and 'named'."""
985 spec = getfullargspec(func)
986 args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults, ann = spec
987 f_name = func.__name__
988 arg2value = {}
989
Benjamin Petersonb204a422011-06-05 22:04:07 -0500990
Benjamin Peterson25cd7eb2010-03-30 18:42:32 +0000991 if ismethod(func) and func.__self__ is not None:
992 # implicit 'self' (or 'cls' for classmethods) argument
993 positional = (func.__self__,) + positional
994 num_pos = len(positional)
Benjamin Peterson25cd7eb2010-03-30 18:42:32 +0000995 num_args = len(args)
996 num_defaults = len(defaults) if defaults else 0
Benjamin Peterson25cd7eb2010-03-30 18:42:32 +0000997
Benjamin Petersonb204a422011-06-05 22:04:07 -0500998 n = min(num_pos, num_args)
999 for i in range(n):
1000 arg2value[args[i]] = positional[i]
1001 if varargs:
1002 arg2value[varargs] = tuple(positional[n:])
1003 possible_kwargs = set(args + kwonlyargs)
Benjamin Peterson25cd7eb2010-03-30 18:42:32 +00001004 if varkw:
Benjamin Petersonb204a422011-06-05 22:04:07 -05001005 arg2value[varkw] = {}
1006 for kw, value in named.items():
1007 if kw not in possible_kwargs:
1008 if not varkw:
1009 raise TypeError("%s() got an unexpected keyword argument %r" %
1010 (f_name, kw))
1011 arg2value[varkw][kw] = value
1012 continue
1013 if kw in arg2value:
1014 raise TypeError("%s() got multiple values for argument %r" %
1015 (f_name, kw))
1016 arg2value[kw] = value
1017 if num_pos > num_args and not varargs:
Benjamin Petersone109c702011-06-24 09:37:26 -05001018 _too_many(f_name, args, kwonlyargs, varargs, num_defaults,
1019 num_pos, arg2value)
Benjamin Petersonb204a422011-06-05 22:04:07 -05001020 if num_pos < num_args:
Benjamin Petersone109c702011-06-24 09:37:26 -05001021 req = args[:num_args - num_defaults]
1022 for arg in req:
Benjamin Petersonb204a422011-06-05 22:04:07 -05001023 if arg not in arg2value:
Benjamin Petersone109c702011-06-24 09:37:26 -05001024 _missing_arguments(f_name, req, True, arg2value)
Benjamin Petersonb204a422011-06-05 22:04:07 -05001025 for i, arg in enumerate(args[num_args - num_defaults:]):
1026 if arg not in arg2value:
1027 arg2value[arg] = defaults[i]
Benjamin Petersone109c702011-06-24 09:37:26 -05001028 missing = 0
Benjamin Petersonb204a422011-06-05 22:04:07 -05001029 for kwarg in kwonlyargs:
1030 if kwarg not in arg2value:
Benjamin Petersone109c702011-06-24 09:37:26 -05001031 if kwarg in kwonlydefaults:
1032 arg2value[kwarg] = kwonlydefaults[kwarg]
1033 else:
1034 missing += 1
1035 if missing:
1036 _missing_arguments(f_name, kwonlyargs, False, arg2value)
Benjamin Peterson25cd7eb2010-03-30 18:42:32 +00001037 return arg2value
1038
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001039# -------------------------------------------------- stack frame extraction
Christian Heimes25bb7832008-01-11 16:17:00 +00001040
1041Traceback = namedtuple('Traceback', 'filename lineno function code_context index')
1042
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001043def getframeinfo(frame, context=1):
1044 """Get information about a frame or traceback object.
1045
1046 A tuple of five things is returned: the filename, the line number of
1047 the current line, the function name, a list of lines of context from
1048 the source code, and the index of the current line within that list.
1049 The optional second argument specifies the number of lines of context
1050 to return, which are centered around the current line."""
1051 if istraceback(frame):
Andrew M. Kuchlingba8b6bc2004-06-05 14:11:59 +00001052 lineno = frame.tb_lineno
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001053 frame = frame.tb_frame
Andrew M. Kuchlingba8b6bc2004-06-05 14:11:59 +00001054 else:
1055 lineno = frame.f_lineno
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001056 if not isframe(frame):
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00001057 raise TypeError('{!r} is not a frame or traceback object'.format(frame))
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001058
Neil Schemenauerf06f8532002-03-23 23:51:04 +00001059 filename = getsourcefile(frame) or getfile(frame)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001060 if context > 0:
Guido van Rossum54e54c62001-09-04 19:14:14 +00001061 start = lineno - 1 - context//2
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001062 try:
1063 lines, lnum = findsource(frame)
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +00001064 except IOError:
1065 lines = index = None
1066 else:
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001067 start = max(start, 1)
Raymond Hettingera0501712004-06-15 11:22:53 +00001068 start = max(0, min(start, len(lines) - context))
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001069 lines = lines[start:start+context]
Ka-Ping Yee59ade082001-03-01 03:55:35 +00001070 index = lineno - 1 - start
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001071 else:
1072 lines = index = None
1073
Christian Heimes25bb7832008-01-11 16:17:00 +00001074 return Traceback(filename, lineno, frame.f_code.co_name, lines, index)
Ka-Ping Yee59ade082001-03-01 03:55:35 +00001075
1076def getlineno(frame):
1077 """Get the line number from a frame object, allowing for optimization."""
Michael W. Hudsondd32a912002-08-15 14:59:02 +00001078 # FrameType.f_lineno is now a descriptor that grovels co_lnotab
1079 return frame.f_lineno
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001080
1081def getouterframes(frame, context=1):
1082 """Get a list of records for a frame and all higher (calling) frames.
1083
1084 Each record contains a frame object, filename, line number, function
1085 name, a list of lines of context, and index within the context."""
1086 framelist = []
1087 while frame:
1088 framelist.append((frame,) + getframeinfo(frame, context))
1089 frame = frame.f_back
1090 return framelist
1091
1092def getinnerframes(tb, context=1):
1093 """Get a list of records for a traceback's frame and all lower frames.
1094
1095 Each record contains a frame object, filename, line number, function
1096 name, a list of lines of context, and index within the context."""
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001097 framelist = []
1098 while tb:
1099 framelist.append((tb.tb_frame,) + getframeinfo(tb, context))
1100 tb = tb.tb_next
1101 return framelist
1102
Benjamin Peterson42ac4752010-08-09 13:05:35 +00001103def currentframe():
Benjamin Petersona3a3fc62010-08-09 15:49:56 +00001104 """Return the frame of the caller or None if this is not possible."""
Benjamin Peterson42ac4752010-08-09 13:05:35 +00001105 return sys._getframe(1) if hasattr(sys, "_getframe") else None
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001106
1107def stack(context=1):
1108 """Return a list of records for the stack above the caller's frame."""
Jeremy Hyltonab919022003-06-27 18:41:20 +00001109 return getouterframes(sys._getframe(1), context)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001110
1111def trace(context=1):
Tim Peters85ba6732001-02-28 08:26:44 +00001112 """Return a list of records for the stack below the current exception."""
Fred Draked451ec12002-04-26 02:29:55 +00001113 return getinnerframes(sys.exc_info()[2], context)
Michael Foord95fc51d2010-11-20 15:07:30 +00001114
1115
1116# ------------------------------------------------ static version of getattr
1117
1118_sentinel = object()
1119
Michael Foorde5162652010-11-20 16:40:44 +00001120def _static_getmro(klass):
1121 return type.__dict__['__mro__'].__get__(klass)
1122
Michael Foord95fc51d2010-11-20 15:07:30 +00001123def _check_instance(obj, attr):
1124 instance_dict = {}
1125 try:
1126 instance_dict = object.__getattribute__(obj, "__dict__")
1127 except AttributeError:
1128 pass
Michael Foorddcebe0f2011-03-15 19:20:44 -04001129 return dict.get(instance_dict, attr, _sentinel)
Michael Foord95fc51d2010-11-20 15:07:30 +00001130
1131
1132def _check_class(klass, attr):
Michael Foorde5162652010-11-20 16:40:44 +00001133 for entry in _static_getmro(klass):
Michael Foorda51623b2011-12-18 22:01:40 +00001134 if _shadowed_dict(type(entry)) is _sentinel:
Michael Foorddcebe0f2011-03-15 19:20:44 -04001135 try:
1136 return entry.__dict__[attr]
1137 except KeyError:
1138 pass
Michael Foord95fc51d2010-11-20 15:07:30 +00001139 return _sentinel
1140
Michael Foord35184ed2010-11-20 16:58:30 +00001141def _is_type(obj):
1142 try:
1143 _static_getmro(obj)
1144 except TypeError:
1145 return False
1146 return True
1147
Michael Foorddcebe0f2011-03-15 19:20:44 -04001148def _shadowed_dict(klass):
1149 dict_attr = type.__dict__["__dict__"]
1150 for entry in _static_getmro(klass):
1151 try:
1152 class_dict = dict_attr.__get__(entry)["__dict__"]
1153 except KeyError:
1154 pass
1155 else:
1156 if not (type(class_dict) is types.GetSetDescriptorType and
1157 class_dict.__name__ == "__dict__" and
1158 class_dict.__objclass__ is entry):
Michael Foorda51623b2011-12-18 22:01:40 +00001159 return class_dict
1160 return _sentinel
Michael Foord95fc51d2010-11-20 15:07:30 +00001161
1162def getattr_static(obj, attr, default=_sentinel):
1163 """Retrieve attributes without triggering dynamic lookup via the
1164 descriptor protocol, __getattr__ or __getattribute__.
1165
1166 Note: this function may not be able to retrieve all attributes
1167 that getattr can fetch (like dynamically created attributes)
1168 and may find attributes that getattr can't (like descriptors
1169 that raise AttributeError). It can also return descriptor objects
1170 instead of instance members in some cases. See the
1171 documentation for details.
1172 """
1173 instance_result = _sentinel
Michael Foord35184ed2010-11-20 16:58:30 +00001174 if not _is_type(obj):
Michael Foordcc7ebb82010-11-20 16:20:16 +00001175 klass = type(obj)
Michael Foorda51623b2011-12-18 22:01:40 +00001176 dict_attr = _shadowed_dict(klass)
1177 if (dict_attr is _sentinel or
1178 type(dict_attr) is types.MemberDescriptorType):
Michael Foorddcebe0f2011-03-15 19:20:44 -04001179 instance_result = _check_instance(obj, attr)
Michael Foord95fc51d2010-11-20 15:07:30 +00001180 else:
1181 klass = obj
1182
1183 klass_result = _check_class(klass, attr)
1184
1185 if instance_result is not _sentinel and klass_result is not _sentinel:
1186 if (_check_class(type(klass_result), '__get__') is not _sentinel and
1187 _check_class(type(klass_result), '__set__') is not _sentinel):
1188 return klass_result
1189
1190 if instance_result is not _sentinel:
1191 return instance_result
1192 if klass_result is not _sentinel:
1193 return klass_result
1194
1195 if obj is klass:
1196 # for types we check the metaclass too
Michael Foorde5162652010-11-20 16:40:44 +00001197 for entry in _static_getmro(type(klass)):
Michael Foord3ba95f82011-12-22 01:13:37 +00001198 if _shadowed_dict(type(entry)) is _sentinel:
1199 try:
1200 return entry.__dict__[attr]
1201 except KeyError:
1202 pass
Michael Foord95fc51d2010-11-20 15:07:30 +00001203 if default is not _sentinel:
1204 return default
1205 raise AttributeError(attr)
Nick Coghlane0f04652010-11-21 03:44:04 +00001206
1207
Nick Coghlan7921b9f2010-11-30 06:36:04 +00001208GEN_CREATED = 'GEN_CREATED'
1209GEN_RUNNING = 'GEN_RUNNING'
1210GEN_SUSPENDED = 'GEN_SUSPENDED'
1211GEN_CLOSED = 'GEN_CLOSED'
Nick Coghlane0f04652010-11-21 03:44:04 +00001212
1213def getgeneratorstate(generator):
1214 """Get current state of a generator-iterator.
1215
1216 Possible states are:
1217 GEN_CREATED: Waiting to start execution.
1218 GEN_RUNNING: Currently being executed by the interpreter.
1219 GEN_SUSPENDED: Currently suspended at a yield expression.
1220 GEN_CLOSED: Execution has completed.
1221 """
1222 if generator.gi_running:
1223 return GEN_RUNNING
1224 if generator.gi_frame is None:
1225 return GEN_CLOSED
1226 if generator.gi_frame.f_lasti == -1:
1227 return GEN_CREATED
1228 return GEN_SUSPENDED
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07001229
1230
1231###############################################################################
1232### Function Signature Object (PEP 362)
1233###############################################################################
1234
1235
1236_WrapperDescriptor = type(type.__call__)
1237_MethodWrapper = type(all.__call__)
1238
1239_NonUserDefinedCallables = (_WrapperDescriptor,
1240 _MethodWrapper,
1241 types.BuiltinFunctionType)
1242
1243
1244def _get_user_defined_method(cls, method_name):
1245 try:
1246 meth = getattr(cls, method_name)
1247 except AttributeError:
1248 return
1249 else:
1250 if not isinstance(meth, _NonUserDefinedCallables):
1251 # Once '__signature__' will be added to 'C'-level
1252 # callables, this check won't be necessary
1253 return meth
1254
1255
1256def signature(obj):
1257 '''Get a signature object for the passed callable.'''
1258
1259 if not callable(obj):
1260 raise TypeError('{!r} is not a callable object'.format(obj))
1261
1262 if isinstance(obj, types.MethodType):
1263 # In this case we skip the first parameter of the underlying
1264 # function (usually `self` or `cls`).
1265 sig = signature(obj.__func__)
1266 return sig.replace(parameters=tuple(sig.parameters.values())[1:])
1267
1268 try:
1269 sig = obj.__signature__
1270 except AttributeError:
1271 pass
1272 else:
1273 if sig is not None:
1274 return sig
1275
1276 try:
1277 # Was this function wrapped by a decorator?
1278 wrapped = obj.__wrapped__
1279 except AttributeError:
1280 pass
1281 else:
1282 return signature(wrapped)
1283
1284 if isinstance(obj, types.FunctionType):
1285 return Signature.from_function(obj)
1286
1287 if isinstance(obj, functools.partial):
1288 sig = signature(obj.func)
1289
1290 new_params = OrderedDict(sig.parameters.items())
1291
1292 partial_args = obj.args or ()
1293 partial_keywords = obj.keywords or {}
1294 try:
1295 ba = sig.bind_partial(*partial_args, **partial_keywords)
1296 except TypeError as ex:
1297 msg = 'partial object {!r} has incorrect arguments'.format(obj)
1298 raise ValueError(msg) from ex
1299
1300 for arg_name, arg_value in ba.arguments.items():
1301 param = new_params[arg_name]
1302 if arg_name in partial_keywords:
1303 # We set a new default value, because the following code
1304 # is correct:
1305 #
1306 # >>> def foo(a): print(a)
1307 # >>> print(partial(partial(foo, a=10), a=20)())
1308 # 20
1309 # >>> print(partial(partial(foo, a=10), a=20)(a=30))
1310 # 30
1311 #
1312 # So, with 'partial' objects, passing a keyword argument is
1313 # like setting a new default value for the corresponding
1314 # parameter
1315 #
1316 # We also mark this parameter with '_partial_kwarg'
1317 # flag. Later, in '_bind', the 'default' value of this
1318 # parameter will be added to 'kwargs', to simulate
1319 # the 'functools.partial' real call.
1320 new_params[arg_name] = param.replace(default=arg_value,
1321 _partial_kwarg=True)
1322
1323 elif (param.kind not in (_VAR_KEYWORD, _VAR_POSITIONAL) and
1324 not param._partial_kwarg):
1325 new_params.pop(arg_name)
1326
1327 return sig.replace(parameters=new_params.values())
1328
1329 sig = None
1330 if isinstance(obj, type):
1331 # obj is a class or a metaclass
1332
1333 # First, let's see if it has an overloaded __call__ defined
1334 # in its metaclass
1335 call = _get_user_defined_method(type(obj), '__call__')
1336 if call is not None:
1337 sig = signature(call)
1338 else:
1339 # Now we check if the 'obj' class has a '__new__' method
1340 new = _get_user_defined_method(obj, '__new__')
1341 if new is not None:
1342 sig = signature(new)
1343 else:
1344 # Finally, we should have at least __init__ implemented
1345 init = _get_user_defined_method(obj, '__init__')
1346 if init is not None:
1347 sig = signature(init)
1348 elif not isinstance(obj, _NonUserDefinedCallables):
1349 # An object with __call__
1350 # We also check that the 'obj' is not an instance of
1351 # _WrapperDescriptor or _MethodWrapper to avoid
1352 # infinite recursion (and even potential segfault)
1353 call = _get_user_defined_method(type(obj), '__call__')
1354 if call is not None:
1355 sig = signature(call)
1356
1357 if sig is not None:
1358 # For classes and objects we skip the first parameter of their
1359 # __call__, __new__, or __init__ methods
1360 return sig.replace(parameters=tuple(sig.parameters.values())[1:])
1361
1362 if isinstance(obj, types.BuiltinFunctionType):
1363 # Raise a nicer error message for builtins
1364 msg = 'no signature found for builtin function {!r}'.format(obj)
1365 raise ValueError(msg)
1366
1367 raise ValueError('callable {!r} is not supported by signature'.format(obj))
1368
1369
1370class _void:
1371 '''A private marker - used in Parameter & Signature'''
1372
1373
1374class _empty:
1375 pass
1376
1377
1378class _ParameterKind(int):
1379 def __new__(self, *args, name):
1380 obj = int.__new__(self, *args)
1381 obj._name = name
1382 return obj
1383
1384 def __str__(self):
1385 return self._name
1386
1387 def __repr__(self):
1388 return '<_ParameterKind: {!r}>'.format(self._name)
1389
1390
1391_POSITIONAL_ONLY = _ParameterKind(0, name='POSITIONAL_ONLY')
1392_POSITIONAL_OR_KEYWORD = _ParameterKind(1, name='POSITIONAL_OR_KEYWORD')
1393_VAR_POSITIONAL = _ParameterKind(2, name='VAR_POSITIONAL')
1394_KEYWORD_ONLY = _ParameterKind(3, name='KEYWORD_ONLY')
1395_VAR_KEYWORD = _ParameterKind(4, name='VAR_KEYWORD')
1396
1397
1398class Parameter:
1399 '''Represents a parameter in a function signature.
1400
1401 Has the following public attributes:
1402
1403 * name : str
1404 The name of the parameter as a string.
1405 * default : object
1406 The default value for the parameter if specified. If the
1407 parameter has no default value, this attribute is not set.
1408 * annotation
1409 The annotation for the parameter if specified. If the
1410 parameter has no annotation, this attribute is not set.
1411 * kind : str
1412 Describes how argument values are bound to the parameter.
1413 Possible values: `Parameter.POSITIONAL_ONLY`,
1414 `Parameter.POSITIONAL_OR_KEYWORD`, `Parameter.VAR_POSITIONAL`,
1415 `Parameter.KEYWORD_ONLY`, `Parameter.VAR_KEYWORD`.
1416 '''
1417
1418 __slots__ = ('_name', '_kind', '_default', '_annotation', '_partial_kwarg')
1419
1420 POSITIONAL_ONLY = _POSITIONAL_ONLY
1421 POSITIONAL_OR_KEYWORD = _POSITIONAL_OR_KEYWORD
1422 VAR_POSITIONAL = _VAR_POSITIONAL
1423 KEYWORD_ONLY = _KEYWORD_ONLY
1424 VAR_KEYWORD = _VAR_KEYWORD
1425
1426 empty = _empty
1427
1428 def __init__(self, name, kind, *, default=_empty, annotation=_empty,
1429 _partial_kwarg=False):
1430
1431 if kind not in (_POSITIONAL_ONLY, _POSITIONAL_OR_KEYWORD,
1432 _VAR_POSITIONAL, _KEYWORD_ONLY, _VAR_KEYWORD):
1433 raise ValueError("invalid value for 'Parameter.kind' attribute")
1434 self._kind = kind
1435
1436 if default is not _empty:
1437 if kind in (_VAR_POSITIONAL, _VAR_KEYWORD):
1438 msg = '{} parameters cannot have default values'.format(kind)
1439 raise ValueError(msg)
1440 self._default = default
1441 self._annotation = annotation
1442
1443 if name is None:
1444 if kind != _POSITIONAL_ONLY:
1445 raise ValueError("None is not a valid name for a "
1446 "non-positional-only parameter")
1447 self._name = name
1448 else:
1449 name = str(name)
1450 if kind != _POSITIONAL_ONLY and not name.isidentifier():
1451 msg = '{!r} is not a valid parameter name'.format(name)
1452 raise ValueError(msg)
1453 self._name = name
1454
1455 self._partial_kwarg = _partial_kwarg
1456
1457 @property
1458 def name(self):
1459 return self._name
1460
1461 @property
1462 def default(self):
1463 return self._default
1464
1465 @property
1466 def annotation(self):
1467 return self._annotation
1468
1469 @property
1470 def kind(self):
1471 return self._kind
1472
1473 def replace(self, *, name=_void, kind=_void, annotation=_void,
1474 default=_void, _partial_kwarg=_void):
1475 '''Creates a customized copy of the Parameter.'''
1476
1477 if name is _void:
1478 name = self._name
1479
1480 if kind is _void:
1481 kind = self._kind
1482
1483 if annotation is _void:
1484 annotation = self._annotation
1485
1486 if default is _void:
1487 default = self._default
1488
1489 if _partial_kwarg is _void:
1490 _partial_kwarg = self._partial_kwarg
1491
1492 return type(self)(name, kind, default=default, annotation=annotation,
1493 _partial_kwarg=_partial_kwarg)
1494
1495 def __str__(self):
1496 kind = self.kind
1497
1498 formatted = self._name
1499 if kind == _POSITIONAL_ONLY:
1500 if formatted is None:
1501 formatted = ''
1502 formatted = '<{}>'.format(formatted)
1503
1504 # Add annotation and default value
1505 if self._annotation is not _empty:
1506 formatted = '{}:{}'.format(formatted,
1507 formatannotation(self._annotation))
1508
1509 if self._default is not _empty:
1510 formatted = '{}={}'.format(formatted, repr(self._default))
1511
1512 if kind == _VAR_POSITIONAL:
1513 formatted = '*' + formatted
1514 elif kind == _VAR_KEYWORD:
1515 formatted = '**' + formatted
1516
1517 return formatted
1518
1519 def __repr__(self):
1520 return '<{} at {:#x} {!r}>'.format(self.__class__.__name__,
1521 id(self), self.name)
1522
1523 def __eq__(self, other):
1524 return (issubclass(other.__class__, Parameter) and
1525 self._name == other._name and
1526 self._kind == other._kind and
1527 self._default == other._default and
1528 self._annotation == other._annotation)
1529
1530 def __ne__(self, other):
1531 return not self.__eq__(other)
1532
1533
1534class BoundArguments:
1535 '''Result of `Signature.bind` call. Holds the mapping of arguments
1536 to the function's parameters.
1537
1538 Has the following public attributes:
1539
1540 * arguments : OrderedDict
1541 An ordered mutable mapping of parameters' names to arguments' values.
1542 Does not contain arguments' default values.
1543 * signature : Signature
1544 The Signature object that created this instance.
1545 * args : tuple
1546 Tuple of positional arguments values.
1547 * kwargs : dict
1548 Dict of keyword arguments values.
1549 '''
1550
1551 def __init__(self, signature, arguments):
1552 self.arguments = arguments
1553 self._signature = signature
1554
1555 @property
1556 def signature(self):
1557 return self._signature
1558
1559 @property
1560 def args(self):
1561 args = []
1562 for param_name, param in self._signature.parameters.items():
1563 if (param.kind in (_VAR_KEYWORD, _KEYWORD_ONLY) or
1564 param._partial_kwarg):
1565 # Keyword arguments mapped by 'functools.partial'
1566 # (Parameter._partial_kwarg is True) are mapped
1567 # in 'BoundArguments.kwargs', along with VAR_KEYWORD &
1568 # KEYWORD_ONLY
1569 break
1570
1571 try:
1572 arg = self.arguments[param_name]
1573 except KeyError:
1574 # We're done here. Other arguments
1575 # will be mapped in 'BoundArguments.kwargs'
1576 break
1577 else:
1578 if param.kind == _VAR_POSITIONAL:
1579 # *args
1580 args.extend(arg)
1581 else:
1582 # plain argument
1583 args.append(arg)
1584
1585 return tuple(args)
1586
1587 @property
1588 def kwargs(self):
1589 kwargs = {}
1590 kwargs_started = False
1591 for param_name, param in self._signature.parameters.items():
1592 if not kwargs_started:
1593 if (param.kind in (_VAR_KEYWORD, _KEYWORD_ONLY) or
1594 param._partial_kwarg):
1595 kwargs_started = True
1596 else:
1597 if param_name not in self.arguments:
1598 kwargs_started = True
1599 continue
1600
1601 if not kwargs_started:
1602 continue
1603
1604 try:
1605 arg = self.arguments[param_name]
1606 except KeyError:
1607 pass
1608 else:
1609 if param.kind == _VAR_KEYWORD:
1610 # **kwargs
1611 kwargs.update(arg)
1612 else:
1613 # plain keyword argument
1614 kwargs[param_name] = arg
1615
1616 return kwargs
1617
1618 def __eq__(self, other):
1619 return (issubclass(other.__class__, BoundArguments) and
1620 self.signature == other.signature and
1621 self.arguments == other.arguments)
1622
1623 def __ne__(self, other):
1624 return not self.__eq__(other)
1625
1626
1627class Signature:
1628 '''A Signature object represents the overall signature of a function.
1629 It stores a Parameter object for each parameter accepted by the
1630 function, as well as information specific to the function itself.
1631
1632 A Signature object has the following public attributes and methods:
1633
1634 * parameters : OrderedDict
1635 An ordered mapping of parameters' names to the corresponding
1636 Parameter objects (keyword-only arguments are in the same order
1637 as listed in `code.co_varnames`).
1638 * return_annotation : object
1639 The annotation for the return type of the function if specified.
1640 If the function has no annotation for its return type, this
1641 attribute is not set.
1642 * bind(*args, **kwargs) -> BoundArguments
1643 Creates a mapping from positional and keyword arguments to
1644 parameters.
1645 * bind_partial(*args, **kwargs) -> BoundArguments
1646 Creates a partial mapping from positional and keyword arguments
1647 to parameters (simulating 'functools.partial' behavior.)
1648 '''
1649
1650 __slots__ = ('_return_annotation', '_parameters')
1651
1652 _parameter_cls = Parameter
1653 _bound_arguments_cls = BoundArguments
1654
1655 empty = _empty
1656
1657 def __init__(self, parameters=None, *, return_annotation=_empty,
1658 __validate_parameters__=True):
1659 '''Constructs Signature from the given list of Parameter
1660 objects and 'return_annotation'. All arguments are optional.
1661 '''
1662
1663 if parameters is None:
1664 params = OrderedDict()
1665 else:
1666 if __validate_parameters__:
1667 params = OrderedDict()
1668 top_kind = _POSITIONAL_ONLY
1669
1670 for idx, param in enumerate(parameters):
1671 kind = param.kind
1672 if kind < top_kind:
1673 msg = 'wrong parameter order: {} before {}'
1674 msg = msg.format(top_kind, param.kind)
1675 raise ValueError(msg)
1676 else:
1677 top_kind = kind
1678
1679 name = param.name
1680 if name is None:
1681 name = str(idx)
1682 param = param.replace(name=name)
1683
1684 if name in params:
1685 msg = 'duplicate parameter name: {!r}'.format(name)
1686 raise ValueError(msg)
1687 params[name] = param
1688 else:
1689 params = OrderedDict(((param.name, param)
1690 for param in parameters))
1691
1692 self._parameters = types.MappingProxyType(params)
1693 self._return_annotation = return_annotation
1694
1695 @classmethod
1696 def from_function(cls, func):
1697 '''Constructs Signature for the given python function'''
1698
1699 if not isinstance(func, types.FunctionType):
1700 raise TypeError('{!r} is not a Python function'.format(func))
1701
1702 Parameter = cls._parameter_cls
1703
1704 # Parameter information.
1705 func_code = func.__code__
1706 pos_count = func_code.co_argcount
1707 arg_names = func_code.co_varnames
1708 positional = tuple(arg_names[:pos_count])
1709 keyword_only_count = func_code.co_kwonlyargcount
1710 keyword_only = arg_names[pos_count:(pos_count + keyword_only_count)]
1711 annotations = func.__annotations__
1712 defaults = func.__defaults__
1713 kwdefaults = func.__kwdefaults__
1714
1715 if defaults:
1716 pos_default_count = len(defaults)
1717 else:
1718 pos_default_count = 0
1719
1720 parameters = []
1721
1722 # Non-keyword-only parameters w/o defaults.
1723 non_default_count = pos_count - pos_default_count
1724 for name in positional[:non_default_count]:
1725 annotation = annotations.get(name, _empty)
1726 parameters.append(Parameter(name, annotation=annotation,
1727 kind=_POSITIONAL_OR_KEYWORD))
1728
1729 # ... w/ defaults.
1730 for offset, name in enumerate(positional[non_default_count:]):
1731 annotation = annotations.get(name, _empty)
1732 parameters.append(Parameter(name, annotation=annotation,
1733 kind=_POSITIONAL_OR_KEYWORD,
1734 default=defaults[offset]))
1735
1736 # *args
1737 if func_code.co_flags & 0x04:
1738 name = arg_names[pos_count + keyword_only_count]
1739 annotation = annotations.get(name, _empty)
1740 parameters.append(Parameter(name, annotation=annotation,
1741 kind=_VAR_POSITIONAL))
1742
1743 # Keyword-only parameters.
1744 for name in keyword_only:
1745 default = _empty
1746 if kwdefaults is not None:
1747 default = kwdefaults.get(name, _empty)
1748
1749 annotation = annotations.get(name, _empty)
1750 parameters.append(Parameter(name, annotation=annotation,
1751 kind=_KEYWORD_ONLY,
1752 default=default))
1753 # **kwargs
1754 if func_code.co_flags & 0x08:
1755 index = pos_count + keyword_only_count
1756 if func_code.co_flags & 0x04:
1757 index += 1
1758
1759 name = arg_names[index]
1760 annotation = annotations.get(name, _empty)
1761 parameters.append(Parameter(name, annotation=annotation,
1762 kind=_VAR_KEYWORD))
1763
1764 return cls(parameters,
1765 return_annotation=annotations.get('return', _empty),
1766 __validate_parameters__=False)
1767
1768 @property
1769 def parameters(self):
1770 return self._parameters
1771
1772 @property
1773 def return_annotation(self):
1774 return self._return_annotation
1775
1776 def replace(self, *, parameters=_void, return_annotation=_void):
1777 '''Creates a customized copy of the Signature.
1778 Pass 'parameters' and/or 'return_annotation' arguments
1779 to override them in the new copy.
1780 '''
1781
1782 if parameters is _void:
1783 parameters = self.parameters.values()
1784
1785 if return_annotation is _void:
1786 return_annotation = self._return_annotation
1787
1788 return type(self)(parameters,
1789 return_annotation=return_annotation)
1790
1791 def __eq__(self, other):
1792 if (not issubclass(type(other), Signature) or
1793 self.return_annotation != other.return_annotation or
1794 len(self.parameters) != len(other.parameters)):
1795 return False
1796
1797 other_positions = {param: idx
1798 for idx, param in enumerate(other.parameters.keys())}
1799
1800 for idx, (param_name, param) in enumerate(self.parameters.items()):
1801 if param.kind == _KEYWORD_ONLY:
1802 try:
1803 other_param = other.parameters[param_name]
1804 except KeyError:
1805 return False
1806 else:
1807 if param != other_param:
1808 return False
1809 else:
1810 try:
1811 other_idx = other_positions[param_name]
1812 except KeyError:
1813 return False
1814 else:
1815 if (idx != other_idx or
1816 param != other.parameters[param_name]):
1817 return False
1818
1819 return True
1820
1821 def __ne__(self, other):
1822 return not self.__eq__(other)
1823
1824 def _bind(self, args, kwargs, *, partial=False):
1825 '''Private method. Don't use directly.'''
1826
1827 arguments = OrderedDict()
1828
1829 parameters = iter(self.parameters.values())
1830 parameters_ex = ()
1831 arg_vals = iter(args)
1832
1833 if partial:
1834 # Support for binding arguments to 'functools.partial' objects.
1835 # See 'functools.partial' case in 'signature()' implementation
1836 # for details.
1837 for param_name, param in self.parameters.items():
1838 if (param._partial_kwarg and param_name not in kwargs):
1839 # Simulating 'functools.partial' behavior
1840 kwargs[param_name] = param.default
1841
1842 while True:
1843 # Let's iterate through the positional arguments and corresponding
1844 # parameters
1845 try:
1846 arg_val = next(arg_vals)
1847 except StopIteration:
1848 # No more positional arguments
1849 try:
1850 param = next(parameters)
1851 except StopIteration:
1852 # No more parameters. That's it. Just need to check that
1853 # we have no `kwargs` after this while loop
1854 break
1855 else:
1856 if param.kind == _VAR_POSITIONAL:
1857 # That's OK, just empty *args. Let's start parsing
1858 # kwargs
1859 break
1860 elif param.name in kwargs:
1861 if param.kind == _POSITIONAL_ONLY:
1862 msg = '{arg!r} parameter is positional only, ' \
1863 'but was passed as a keyword'
1864 msg = msg.format(arg=param.name)
1865 raise TypeError(msg) from None
1866 parameters_ex = (param,)
1867 break
1868 elif (param.kind == _VAR_KEYWORD or
1869 param.default is not _empty):
1870 # That's fine too - we have a default value for this
1871 # parameter. So, lets start parsing `kwargs`, starting
1872 # with the current parameter
1873 parameters_ex = (param,)
1874 break
1875 else:
1876 if partial:
1877 parameters_ex = (param,)
1878 break
1879 else:
1880 msg = '{arg!r} parameter lacking default value'
1881 msg = msg.format(arg=param.name)
1882 raise TypeError(msg) from None
1883 else:
1884 # We have a positional argument to process
1885 try:
1886 param = next(parameters)
1887 except StopIteration:
1888 raise TypeError('too many positional arguments') from None
1889 else:
1890 if param.kind in (_VAR_KEYWORD, _KEYWORD_ONLY):
1891 # Looks like we have no parameter for this positional
1892 # argument
1893 raise TypeError('too many positional arguments')
1894
1895 if param.kind == _VAR_POSITIONAL:
1896 # We have an '*args'-like argument, let's fill it with
1897 # all positional arguments we have left and move on to
1898 # the next phase
1899 values = [arg_val]
1900 values.extend(arg_vals)
1901 arguments[param.name] = tuple(values)
1902 break
1903
1904 if param.name in kwargs:
1905 raise TypeError('multiple values for argument '
1906 '{arg!r}'.format(arg=param.name))
1907
1908 arguments[param.name] = arg_val
1909
1910 # Now, we iterate through the remaining parameters to process
1911 # keyword arguments
1912 kwargs_param = None
1913 for param in itertools.chain(parameters_ex, parameters):
1914 if param.kind == _POSITIONAL_ONLY:
1915 # This should never happen in case of a properly built
1916 # Signature object (but let's have this check here
1917 # to ensure correct behaviour just in case)
1918 raise TypeError('{arg!r} parameter is positional only, '
1919 'but was passed as a keyword'. \
1920 format(arg=param.name))
1921
1922 if param.kind == _VAR_KEYWORD:
1923 # Memorize that we have a '**kwargs'-like parameter
1924 kwargs_param = param
1925 continue
1926
1927 param_name = param.name
1928 try:
1929 arg_val = kwargs.pop(param_name)
1930 except KeyError:
1931 # We have no value for this parameter. It's fine though,
1932 # if it has a default value, or it is an '*args'-like
1933 # parameter, left alone by the processing of positional
1934 # arguments.
1935 if (not partial and param.kind != _VAR_POSITIONAL and
1936 param.default is _empty):
1937 raise TypeError('{arg!r} parameter lacking default value'. \
1938 format(arg=param_name)) from None
1939
1940 else:
1941 arguments[param_name] = arg_val
1942
1943 if kwargs:
1944 if kwargs_param is not None:
1945 # Process our '**kwargs'-like parameter
1946 arguments[kwargs_param.name] = kwargs
1947 else:
1948 raise TypeError('too many keyword arguments')
1949
1950 return self._bound_arguments_cls(self, arguments)
1951
1952 def bind(self, *args, **kwargs):
1953 '''Get a BoundArguments object, that maps the passed `args`
1954 and `kwargs` to the function's signature. Raises `TypeError`
1955 if the passed arguments can not be bound.
1956 '''
1957 return self._bind(args, kwargs)
1958
1959 def bind_partial(self, *args, **kwargs):
1960 '''Get a BoundArguments object, that partially maps the
1961 passed `args` and `kwargs` to the function's signature.
1962 Raises `TypeError` if the passed arguments can not be bound.
1963 '''
1964 return self._bind(args, kwargs, partial=True)
1965
1966 def __str__(self):
1967 result = []
1968 render_kw_only_separator = True
1969 for idx, param in enumerate(self.parameters.values()):
1970 formatted = str(param)
1971
1972 kind = param.kind
1973 if kind == _VAR_POSITIONAL:
1974 # OK, we have an '*args'-like parameter, so we won't need
1975 # a '*' to separate keyword-only arguments
1976 render_kw_only_separator = False
1977 elif kind == _KEYWORD_ONLY and render_kw_only_separator:
1978 # We have a keyword-only parameter to render and we haven't
1979 # rendered an '*args'-like parameter before, so add a '*'
1980 # separator to the parameters list ("foo(arg1, *, arg2)" case)
1981 result.append('*')
1982 # This condition should be only triggered once, so
1983 # reset the flag
1984 render_kw_only_separator = False
1985
1986 result.append(formatted)
1987
1988 rendered = '({})'.format(', '.join(result))
1989
1990 if self.return_annotation is not _empty:
1991 anno = formatannotation(self.return_annotation)
1992 rendered += ' -> {}'.format(anno)
1993
1994 return rendered