blob: 9337bd590b90a194e84aab36b423ce2cb090b705 [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
Nick Coghlan2f92e542012-06-23 19:39:55 +100045import builtins
Raymond Hettingera1a992c2005-03-11 06:46:45 +000046from operator import attrgetter
Larry Hastings7c7cbfc2012-06-22 15:19:35 -070047from collections import namedtuple, OrderedDict
Nick Coghlan09c81232010-08-17 10:18:16 +000048
49# Create constants for the compiler flags in Include/code.h
50# We try to get them from dis to avoid duplication, but fall
Ezio Melotti30b9d5d2013-08-17 15:50:46 +030051# back to hardcoding so the dependency is optional
Nick Coghlan09c81232010-08-17 10:18:16 +000052try:
53 from dis import COMPILER_FLAG_NAMES as _flag_names
54except ImportError:
55 CO_OPTIMIZED, CO_NEWLOCALS = 0x1, 0x2
56 CO_VARARGS, CO_VARKEYWORDS = 0x4, 0x8
57 CO_NESTED, CO_GENERATOR, CO_NOFREE = 0x10, 0x20, 0x40
58else:
59 mod_dict = globals()
60 for k, v in _flag_names.items():
61 mod_dict["CO_" + v] = k
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +000062
Christian Heimesbe5b30b2008-03-03 19:18:51 +000063# See Include/object.h
64TPFLAGS_IS_ABSTRACT = 1 << 20
65
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +000066# ----------------------------------------------------------- type-checking
67def ismodule(object):
68 """Return true if the object is a module.
69
70 Module objects provide these attributes:
Barry Warsaw28a691b2010-04-17 00:19:56 +000071 __cached__ pathname to byte compiled file
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +000072 __doc__ documentation string
73 __file__ filename (missing for built-in modules)"""
Tim Peters28bc59f2001-09-16 08:40:16 +000074 return isinstance(object, types.ModuleType)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +000075
76def isclass(object):
77 """Return true if the object is a class.
78
79 Class objects provide these attributes:
80 __doc__ documentation string
81 __module__ name of module in which this class was defined"""
Benjamin Petersonc4656002009-01-17 22:41:18 +000082 return isinstance(object, type)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +000083
84def ismethod(object):
85 """Return true if the object is an instance method.
86
87 Instance method objects provide these attributes:
88 __doc__ documentation string
89 __name__ name with which this method was defined
Christian Heimesff737952007-11-27 10:40:20 +000090 __func__ function object containing implementation of method
91 __self__ instance to which this method is bound"""
Tim Peters28bc59f2001-09-16 08:40:16 +000092 return isinstance(object, types.MethodType)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +000093
Tim Peters536d2262001-09-20 05:13:38 +000094def ismethoddescriptor(object):
Tim Petersf1d90b92001-09-20 05:47:55 +000095 """Return true if the object is a method descriptor.
96
97 But not if ismethod() or isclass() or isfunction() are true.
Tim Peters536d2262001-09-20 05:13:38 +000098
99 This is new in Python 2.2, and, for example, is true of int.__add__.
100 An object passing this test has a __get__ attribute but not a __set__
101 attribute, but beyond that the set of attributes varies. __name__ is
102 usually sensible, and __doc__ often is.
103
Tim Petersf1d90b92001-09-20 05:47:55 +0000104 Methods implemented via descriptors that also pass one of the other
105 tests return false from the ismethoddescriptor() test, simply because
106 the other tests promise more -- you can, e.g., count on having the
Christian Heimesff737952007-11-27 10:40:20 +0000107 __func__ attribute (etc) when an object passes ismethod()."""
Antoine Pitrou86a8a9a2011-12-21 09:57:40 +0100108 if isclass(object) or ismethod(object) or isfunction(object):
109 # mutual exclusion
110 return False
111 tp = type(object)
112 return hasattr(tp, "__get__") and not hasattr(tp, "__set__")
Tim Peters536d2262001-09-20 05:13:38 +0000113
Martin v. Löwise59e2ba2003-05-03 09:09:02 +0000114def isdatadescriptor(object):
115 """Return true if the object is a data descriptor.
116
117 Data descriptors have both a __get__ and a __set__ attribute. Examples are
118 properties (defined in Python) and getsets and members (defined in C).
119 Typically, data descriptors will also have __name__ and __doc__ attributes
120 (properties, getsets, and members have both of these attributes), but this
121 is not guaranteed."""
Antoine Pitrou86a8a9a2011-12-21 09:57:40 +0100122 if isclass(object) or ismethod(object) or isfunction(object):
123 # mutual exclusion
124 return False
125 tp = type(object)
126 return hasattr(tp, "__set__") and hasattr(tp, "__get__")
Martin v. Löwise59e2ba2003-05-03 09:09:02 +0000127
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000128if hasattr(types, 'MemberDescriptorType'):
129 # CPython and equivalent
130 def ismemberdescriptor(object):
131 """Return true if the object is a member descriptor.
132
133 Member descriptors are specialized descriptors defined in extension
134 modules."""
135 return isinstance(object, types.MemberDescriptorType)
136else:
137 # Other implementations
138 def ismemberdescriptor(object):
139 """Return true if the object is a member descriptor.
140
141 Member descriptors are specialized descriptors defined in extension
142 modules."""
143 return False
144
145if hasattr(types, 'GetSetDescriptorType'):
146 # CPython and equivalent
147 def isgetsetdescriptor(object):
148 """Return true if the object is a getset descriptor.
149
150 getset descriptors are specialized descriptors defined in extension
151 modules."""
152 return isinstance(object, types.GetSetDescriptorType)
153else:
154 # Other implementations
155 def isgetsetdescriptor(object):
156 """Return true if the object is a getset descriptor.
157
158 getset descriptors are specialized descriptors defined in extension
159 modules."""
160 return False
161
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000162def isfunction(object):
163 """Return true if the object is a user-defined function.
164
165 Function objects provide these attributes:
166 __doc__ documentation string
167 __name__ name with which this function was defined
Neal Norwitz221085d2007-02-25 20:55:47 +0000168 __code__ code object containing compiled function bytecode
169 __defaults__ tuple of any default values for arguments
170 __globals__ global namespace in which this function was defined
171 __annotations__ dict of parameter annotations
172 __kwdefaults__ dict of keyword only parameters with defaults"""
Tim Peters28bc59f2001-09-16 08:40:16 +0000173 return isinstance(object, types.FunctionType)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000174
Christian Heimes7131fd92008-02-19 14:21:46 +0000175def isgeneratorfunction(object):
176 """Return true if the object is a user-defined generator function.
177
178 Generator function objects provides same attributes as functions.
179
Alexander Belopolsky977a6842010-08-16 20:17:07 +0000180 See help(isfunction) for attributes listing."""
Georg Brandlb1441c72009-01-03 22:33:39 +0000181 return bool((isfunction(object) or ismethod(object)) and
182 object.__code__.co_flags & CO_GENERATOR)
Christian Heimes7131fd92008-02-19 14:21:46 +0000183
184def isgenerator(object):
185 """Return true if the object is a generator.
186
187 Generator objects provide these attributes:
Ezio Melotti30b9d5d2013-08-17 15:50:46 +0300188 __iter__ defined to support iteration over container
Christian Heimes7131fd92008-02-19 14:21:46 +0000189 close raises a new GeneratorExit exception inside the
190 generator to terminate the iteration
191 gi_code code object
192 gi_frame frame object or possibly None once the generator has
193 been exhausted
194 gi_running set to 1 when generator is executing, 0 otherwise
195 next return the next item from the container
196 send resumes the generator and "sends" a value that becomes
197 the result of the current yield-expression
198 throw used to raise an exception inside the generator"""
199 return isinstance(object, types.GeneratorType)
200
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000201def istraceback(object):
202 """Return true if the object is a traceback.
203
204 Traceback objects provide these attributes:
205 tb_frame frame object at this level
206 tb_lasti index of last attempted instruction in bytecode
207 tb_lineno current line number in Python source code
208 tb_next next inner traceback object (called by this level)"""
Tim Peters28bc59f2001-09-16 08:40:16 +0000209 return isinstance(object, types.TracebackType)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000210
211def isframe(object):
212 """Return true if the object is a frame object.
213
214 Frame objects provide these attributes:
215 f_back next outer frame object (this frame's caller)
216 f_builtins built-in namespace seen by this frame
217 f_code code object being executed in this frame
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000218 f_globals global namespace seen by this frame
219 f_lasti index of last attempted instruction in bytecode
220 f_lineno current line number in Python source code
221 f_locals local namespace seen by this frame
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000222 f_trace tracing function for this frame, or None"""
Tim Peters28bc59f2001-09-16 08:40:16 +0000223 return isinstance(object, types.FrameType)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000224
225def iscode(object):
226 """Return true if the object is a code object.
227
228 Code objects provide these attributes:
229 co_argcount number of arguments (not including * or ** args)
230 co_code string of raw compiled bytecode
231 co_consts tuple of constants used in the bytecode
232 co_filename name of file in which this code object was created
233 co_firstlineno number of first line in Python source code
234 co_flags bitmap: 1=optimized | 2=newlocals | 4=*arg | 8=**arg
235 co_lnotab encoded mapping of line numbers to bytecode indices
236 co_name name with which this code object was defined
237 co_names tuple of names of local variables
238 co_nlocals number of local variables
239 co_stacksize virtual machine stack space required
240 co_varnames tuple of names of arguments and local variables"""
Tim Peters28bc59f2001-09-16 08:40:16 +0000241 return isinstance(object, types.CodeType)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000242
243def isbuiltin(object):
244 """Return true if the object is a built-in function or method.
245
246 Built-in functions and methods provide these attributes:
247 __doc__ documentation string
248 __name__ original name of this function or method
249 __self__ instance to which a method is bound, or None"""
Tim Peters28bc59f2001-09-16 08:40:16 +0000250 return isinstance(object, types.BuiltinFunctionType)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000251
252def isroutine(object):
253 """Return true if the object is any kind of function or method."""
Tim Peters536d2262001-09-20 05:13:38 +0000254 return (isbuiltin(object)
255 or isfunction(object)
256 or ismethod(object)
257 or ismethoddescriptor(object))
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000258
Christian Heimesbe5b30b2008-03-03 19:18:51 +0000259def isabstract(object):
260 """Return true if the object is an abstract base class (ABC)."""
Benjamin Petersona0dfa822009-11-13 02:25:08 +0000261 return bool(isinstance(object, type) and object.__flags__ & TPFLAGS_IS_ABSTRACT)
Christian Heimesbe5b30b2008-03-03 19:18:51 +0000262
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000263def getmembers(object, predicate=None):
264 """Return all members of an object as (name, value) pairs sorted by name.
265 Optionally, only return members that satisfy a given predicate."""
Antoine Pitrou86a8a9a2011-12-21 09:57:40 +0100266 if isclass(object):
267 mro = (object,) + getmro(object)
268 else:
269 mro = ()
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000270 results = []
271 for key in dir(object):
Antoine Pitrou86a8a9a2011-12-21 09:57:40 +0100272 # First try to get the value via __dict__. Some descriptors don't
273 # like calling their __get__ (see bug #1785).
274 for base in mro:
275 if key in base.__dict__:
276 value = base.__dict__[key]
277 break
278 else:
279 try:
280 value = getattr(object, key)
281 except AttributeError:
282 continue
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000283 if not predicate or predicate(value):
284 results.append((key, value))
285 results.sort()
286 return results
287
Christian Heimes25bb7832008-01-11 16:17:00 +0000288Attribute = namedtuple('Attribute', 'name kind defining_class object')
289
Tim Peters13b49d32001-09-23 02:00:29 +0000290def classify_class_attrs(cls):
291 """Return list of attribute-descriptor tuples.
292
293 For each name in dir(cls), the return list contains a 4-tuple
294 with these elements:
295
296 0. The name (a string).
297
298 1. The kind of attribute this is, one of these strings:
299 'class method' created via classmethod()
300 'static method' created via staticmethod()
301 'property' created via property()
302 'method' any other flavor of method
303 'data' not a method
304
305 2. The class which defined this attribute (a class).
306
307 3. The object as obtained directly from the defining class's
308 __dict__, not via getattr. This is especially important for
309 data attributes: C.data is just a data object, but
310 C.__dict__['data'] may be a data descriptor with additional
311 info, like a __doc__ string.
312 """
313
314 mro = getmro(cls)
315 names = dir(cls)
316 result = []
317 for name in names:
Antoine Pitrou86a8a9a2011-12-21 09:57:40 +0100318 # Get the object associated with the name, and where it was defined.
Tim Peters13b49d32001-09-23 02:00:29 +0000319 # Getting an obj from the __dict__ sometimes reveals more than
320 # using getattr. Static and class methods are dramatic examples.
Antoine Pitrou86a8a9a2011-12-21 09:57:40 +0100321 # Furthermore, some objects may raise an Exception when fetched with
322 # getattr(). This is the case with some descriptors (bug #1785).
323 # Thus, we only use getattr() as a last resort.
324 homecls = None
325 for base in (cls,) + mro:
326 if name in base.__dict__:
327 obj = base.__dict__[name]
328 homecls = base
329 break
Tim Peters13b49d32001-09-23 02:00:29 +0000330 else:
331 obj = getattr(cls, name)
Antoine Pitrou86a8a9a2011-12-21 09:57:40 +0100332 homecls = getattr(obj, "__objclass__", homecls)
Tim Peters13b49d32001-09-23 02:00:29 +0000333
334 # Classify the object.
335 if isinstance(obj, staticmethod):
336 kind = "static method"
337 elif isinstance(obj, classmethod):
338 kind = "class method"
339 elif isinstance(obj, property):
340 kind = "property"
Antoine Pitrou86a8a9a2011-12-21 09:57:40 +0100341 elif ismethoddescriptor(obj):
Tim Peters13b49d32001-09-23 02:00:29 +0000342 kind = "method"
Antoine Pitrou86a8a9a2011-12-21 09:57:40 +0100343 elif isdatadescriptor(obj):
Tim Peters13b49d32001-09-23 02:00:29 +0000344 kind = "data"
Antoine Pitrou86a8a9a2011-12-21 09:57:40 +0100345 else:
346 obj_via_getattr = getattr(cls, name)
347 if (isfunction(obj_via_getattr) or
348 ismethoddescriptor(obj_via_getattr)):
349 kind = "method"
350 else:
351 kind = "data"
352 obj = obj_via_getattr
Tim Peters13b49d32001-09-23 02:00:29 +0000353
Christian Heimes25bb7832008-01-11 16:17:00 +0000354 result.append(Attribute(name, kind, homecls, obj))
Tim Peters13b49d32001-09-23 02:00:29 +0000355
356 return result
357
Tim Peterse0b2d7a2001-09-22 06:10:55 +0000358# ----------------------------------------------------------- class helpers
Tim Peterse0b2d7a2001-09-22 06:10:55 +0000359
360def getmro(cls):
361 "Return tuple of base classes (including cls) in method resolution order."
Benjamin Petersonb82c8e52010-11-04 00:38:49 +0000362 return cls.__mro__
Tim Peterse0b2d7a2001-09-22 06:10:55 +0000363
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000364# -------------------------------------------------- source code extraction
365def indentsize(line):
366 """Return the indent size, in spaces, at the start of a line of text."""
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000367 expline = line.expandtabs()
368 return len(expline) - len(expline.lstrip())
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000369
370def getdoc(object):
371 """Get the documentation string for an object.
372
373 All tabs are expanded to spaces. To clean up docstrings that are
374 indented to line up with blocks of code, any whitespace than can be
375 uniformly removed from the second line onwards is removed."""
Tim Peters24008312002-03-17 18:56:20 +0000376 try:
377 doc = object.__doc__
378 except AttributeError:
379 return None
Guido van Rossum3172c5d2007-10-16 18:12:55 +0000380 if not isinstance(doc, str):
Tim Peters24008312002-03-17 18:56:20 +0000381 return None
Georg Brandl0c77a822008-06-10 16:37:50 +0000382 return cleandoc(doc)
383
384def cleandoc(doc):
385 """Clean up indentation from docstrings.
386
387 Any whitespace that can be uniformly removed from the second line
388 onwards is removed."""
Tim Peters24008312002-03-17 18:56:20 +0000389 try:
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000390 lines = doc.expandtabs().split('\n')
Tim Peters24008312002-03-17 18:56:20 +0000391 except UnicodeError:
392 return None
393 else:
Ka-Ping Yeea59ef7b2002-11-30 03:53:15 +0000394 # Find minimum indentation of any non-blank lines after first line.
Christian Heimesa37d4c62007-12-04 23:02:19 +0000395 margin = sys.maxsize
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000396 for line in lines[1:]:
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000397 content = len(line.lstrip())
Ka-Ping Yeea59ef7b2002-11-30 03:53:15 +0000398 if content:
399 indent = len(line) - content
400 margin = min(margin, indent)
401 # Remove indentation.
402 if lines:
403 lines[0] = lines[0].lstrip()
Christian Heimesa37d4c62007-12-04 23:02:19 +0000404 if margin < sys.maxsize:
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000405 for i in range(1, len(lines)): lines[i] = lines[i][margin:]
Ka-Ping Yeea59ef7b2002-11-30 03:53:15 +0000406 # Remove any trailing or leading blank lines.
407 while lines and not lines[-1]:
408 lines.pop()
409 while lines and not lines[0]:
410 lines.pop(0)
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000411 return '\n'.join(lines)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000412
413def getfile(object):
Ka-Ping Yeec113c242001-03-02 02:08:53 +0000414 """Work out which source or compiled file an object was defined in."""
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000415 if ismodule(object):
416 if hasattr(object, '__file__'):
417 return object.__file__
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +0000418 raise TypeError('{!r} is a built-in module'.format(object))
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000419 if isclass(object):
Ka-Ping Yeec99e0f12001-04-13 12:10:40 +0000420 object = sys.modules.get(object.__module__)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000421 if hasattr(object, '__file__'):
422 return object.__file__
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +0000423 raise TypeError('{!r} is a built-in class'.format(object))
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000424 if ismethod(object):
Christian Heimesff737952007-11-27 10:40:20 +0000425 object = object.__func__
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000426 if isfunction(object):
Neal Norwitz221085d2007-02-25 20:55:47 +0000427 object = object.__code__
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000428 if istraceback(object):
429 object = object.tb_frame
430 if isframe(object):
431 object = object.f_code
432 if iscode(object):
433 return object.co_filename
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +0000434 raise TypeError('{!r} is not a module, class, method, '
435 'function, traceback, frame, or code object'.format(object))
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000436
Christian Heimes25bb7832008-01-11 16:17:00 +0000437ModuleInfo = namedtuple('ModuleInfo', 'name suffix mode module_type')
438
Ka-Ping Yee4d6fc7f2001-04-10 11:43:00 +0000439def getmoduleinfo(path):
440 """Get the module name, suffix, mode, and module type for a given file."""
Brett Cannoncb66eb02012-05-11 12:58:42 -0400441 warnings.warn('inspect.getmoduleinfo() is deprecated', DeprecationWarning,
442 2)
Ka-Ping Yee4d6fc7f2001-04-10 11:43:00 +0000443 filename = os.path.basename(path)
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000444 suffixes = [(-len(suffix), suffix, mode, mtype)
445 for suffix, mode, mtype in imp.get_suffixes()]
Ka-Ping Yee4d6fc7f2001-04-10 11:43:00 +0000446 suffixes.sort() # try longest suffixes first, in case they overlap
447 for neglen, suffix, mode, mtype in suffixes:
448 if filename[neglen:] == suffix:
Christian Heimes25bb7832008-01-11 16:17:00 +0000449 return ModuleInfo(filename[:neglen], suffix, mode, mtype)
Ka-Ping Yee4d6fc7f2001-04-10 11:43:00 +0000450
451def getmodulename(path):
452 """Return the module name for a given file, or None."""
Nick Coghlan76e07702012-07-18 23:14:57 +1000453 fname = os.path.basename(path)
454 # Check for paths that look like an actual module file
455 suffixes = [(-len(suffix), suffix)
456 for suffix in importlib.machinery.all_suffixes()]
457 suffixes.sort() # try longest suffixes first, in case they overlap
458 for neglen, suffix in suffixes:
459 if fname.endswith(suffix):
460 return fname[:neglen]
461 return None
Ka-Ping Yee4d6fc7f2001-04-10 11:43:00 +0000462
Ka-Ping Yeec113c242001-03-02 02:08:53 +0000463def getsourcefile(object):
R. David Murraya1b37402010-06-17 02:04:29 +0000464 """Return the filename that can be used to locate an object's source.
465 Return None if no way can be identified to get the source.
466 """
Ka-Ping Yeec113c242001-03-02 02:08:53 +0000467 filename = getfile(object)
Brett Cannoncb66eb02012-05-11 12:58:42 -0400468 all_bytecode_suffixes = importlib.machinery.DEBUG_BYTECODE_SUFFIXES[:]
469 all_bytecode_suffixes += importlib.machinery.OPTIMIZED_BYTECODE_SUFFIXES[:]
470 if any(filename.endswith(s) for s in all_bytecode_suffixes):
471 filename = (os.path.splitext(filename)[0] +
472 importlib.machinery.SOURCE_SUFFIXES[0])
473 elif any(filename.endswith(s) for s in
474 importlib.machinery.EXTENSION_SUFFIXES):
475 return None
Thomas Wouters477c8d52006-05-27 19:21:47 +0000476 if os.path.exists(filename):
477 return filename
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000478 # only return a non-existent filename if the module has a PEP 302 loader
479 if hasattr(getmodule(object, filename), '__loader__'):
Ka-Ping Yeec113c242001-03-02 02:08:53 +0000480 return filename
R. David Murraya1b37402010-06-17 02:04:29 +0000481 # or it is in the linecache
482 if filename in linecache.cache:
483 return filename
Ka-Ping Yeec113c242001-03-02 02:08:53 +0000484
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000485def getabsfile(object, _filename=None):
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000486 """Return an absolute path to the source or compiled file for an object.
Ka-Ping Yeec113c242001-03-02 02:08:53 +0000487
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000488 The idea is for each object to have a unique origin, so this routine
489 normalizes the result as much as possible."""
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000490 if _filename is None:
491 _filename = getsourcefile(object) or getfile(object)
492 return os.path.normcase(os.path.abspath(_filename))
Ka-Ping Yeec113c242001-03-02 02:08:53 +0000493
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000494modulesbyfile = {}
Thomas Wouters89f507f2006-12-13 04:49:30 +0000495_filesbymodname = {}
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000496
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000497def getmodule(object, _filename=None):
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000498 """Return the module an object was defined in, or None if not found."""
Ka-Ping Yee202c99b2001-04-13 09:15:08 +0000499 if ismodule(object):
500 return object
Johannes Gijsbers93245262004-09-11 15:53:22 +0000501 if hasattr(object, '__module__'):
Ka-Ping Yee8b58b842001-03-01 13:56:16 +0000502 return sys.modules.get(object.__module__)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000503 # Try the filename to modulename cache
504 if _filename is not None and _filename in modulesbyfile:
505 return sys.modules.get(modulesbyfile[_filename])
506 # Try the cache again with the absolute file name
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000507 try:
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000508 file = getabsfile(object, _filename)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000509 except TypeError:
510 return None
Raymond Hettinger54f02222002-06-01 14:18:47 +0000511 if file in modulesbyfile:
Ka-Ping Yeeb38bbbd2003-03-28 16:29:50 +0000512 return sys.modules.get(modulesbyfile[file])
Thomas Wouters89f507f2006-12-13 04:49:30 +0000513 # Update the filename to module name cache and check yet again
514 # Copy sys.modules in order to cope with changes while iterating
Éric Araujoa74f8ef2011-11-29 16:58:53 +0100515 for modname, module in list(sys.modules.items()):
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000516 if ismodule(module) and hasattr(module, '__file__'):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000517 f = module.__file__
518 if f == _filesbymodname.get(modname, None):
519 # Have already mapped this module, so skip it
520 continue
521 _filesbymodname[modname] = f
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000522 f = getabsfile(module)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000523 # Always map to the name the module knows itself by
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000524 modulesbyfile[f] = modulesbyfile[
525 os.path.realpath(f)] = module.__name__
Raymond Hettinger54f02222002-06-01 14:18:47 +0000526 if file in modulesbyfile:
Ka-Ping Yeeb38bbbd2003-03-28 16:29:50 +0000527 return sys.modules.get(modulesbyfile[file])
Thomas Wouters89f507f2006-12-13 04:49:30 +0000528 # Check the main module
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000529 main = sys.modules['__main__']
Brett Cannon4a671fe2003-06-15 22:33:28 +0000530 if not hasattr(object, '__name__'):
531 return None
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000532 if hasattr(main, object.__name__):
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000533 mainobject = getattr(main, object.__name__)
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000534 if mainobject is object:
535 return main
Thomas Wouters89f507f2006-12-13 04:49:30 +0000536 # Check builtins
Georg Brandl1a3284e2007-12-02 09:40:06 +0000537 builtin = sys.modules['builtins']
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000538 if hasattr(builtin, object.__name__):
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000539 builtinobject = getattr(builtin, object.__name__)
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000540 if builtinobject is object:
541 return builtin
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000542
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000543def findsource(object):
544 """Return the entire source file and starting line number for an object.
545
546 The argument may be a module, class, method, function, traceback, frame,
547 or code object. The source code is returned as a list of all the lines
548 in the file and the line number indexes a line in that list. An IOError
549 is raised if the source code cannot be retrieved."""
Benjamin Peterson9620cc02011-06-11 15:53:11 -0500550
551 file = getfile(object)
552 sourcefile = getsourcefile(object)
Ezio Melotti1b145922013-03-30 05:17:24 +0200553 if not sourcefile and file[:1] + file[-1:] != '<>':
R. David Murray74b89242009-05-13 17:33:03 +0000554 raise IOError('source code not available')
Benjamin Peterson9620cc02011-06-11 15:53:11 -0500555 file = sourcefile if sourcefile else file
556
Thomas Wouters89f507f2006-12-13 04:49:30 +0000557 module = getmodule(object, file)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000558 if module:
559 lines = linecache.getlines(file, module.__dict__)
560 else:
561 lines = linecache.getlines(file)
Neil Schemenauerf06f8532002-03-23 23:51:04 +0000562 if not lines:
Jeremy Hyltonab919022003-06-27 18:41:20 +0000563 raise IOError('could not get source code')
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000564
565 if ismodule(object):
566 return lines, 0
567
568 if isclass(object):
569 name = object.__name__
Thomas Wouters89f507f2006-12-13 04:49:30 +0000570 pat = re.compile(r'^(\s*)class\s*' + name + r'\b')
571 # make some effort to find the best matching class definition:
572 # use the one with the least indentation, which is the one
573 # that's most probably not inside a function definition.
574 candidates = []
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000575 for i in range(len(lines)):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000576 match = pat.match(lines[i])
577 if match:
578 # if it's at toplevel, it's already the best one
579 if lines[i][0] == 'c':
580 return lines, i
581 # else add whitespace to candidate list
582 candidates.append((match.group(1), i))
583 if candidates:
584 # this will sort by whitespace, and by line number,
585 # less whitespace first
586 candidates.sort()
587 return lines, candidates[0][1]
Jeremy Hyltonab919022003-06-27 18:41:20 +0000588 else:
589 raise IOError('could not find class definition')
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000590
591 if ismethod(object):
Christian Heimesff737952007-11-27 10:40:20 +0000592 object = object.__func__
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000593 if isfunction(object):
Neal Norwitz221085d2007-02-25 20:55:47 +0000594 object = object.__code__
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000595 if istraceback(object):
596 object = object.tb_frame
597 if isframe(object):
598 object = object.f_code
599 if iscode(object):
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000600 if not hasattr(object, 'co_firstlineno'):
Jeremy Hyltonab919022003-06-27 18:41:20 +0000601 raise IOError('could not find function definition')
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000602 lnum = object.co_firstlineno - 1
Johannes Gijsbers1542f342004-12-12 16:46:28 +0000603 pat = re.compile(r'^(\s*def\s)|(.*(?<!\w)lambda(:|\s))|^(\s*@)')
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000604 while lnum > 0:
Ka-Ping Yeea6e59712001-03-10 09:31:55 +0000605 if pat.match(lines[lnum]): break
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000606 lnum = lnum - 1
607 return lines, lnum
Jeremy Hyltonab919022003-06-27 18:41:20 +0000608 raise IOError('could not find code object')
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000609
610def getcomments(object):
Jeremy Hyltonb4c17c82002-03-28 23:01:56 +0000611 """Get lines of comments immediately preceding an object's source code.
612
613 Returns None when source can't be found.
614 """
615 try:
616 lines, lnum = findsource(object)
617 except (IOError, TypeError):
618 return None
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000619
620 if ismodule(object):
621 # Look for a comment block at the top of the file.
622 start = 0
Ka-Ping Yeeb910efe2001-04-12 13:17:17 +0000623 if lines and lines[0][:2] == '#!': start = 1
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000624 while start < len(lines) and lines[start].strip() in ('', '#'):
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000625 start = start + 1
Ka-Ping Yeeb910efe2001-04-12 13:17:17 +0000626 if start < len(lines) and lines[start][:1] == '#':
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000627 comments = []
628 end = start
629 while end < len(lines) and lines[end][:1] == '#':
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000630 comments.append(lines[end].expandtabs())
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000631 end = end + 1
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000632 return ''.join(comments)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000633
634 # Look for a preceding block of comments at the same indentation.
635 elif lnum > 0:
636 indent = indentsize(lines[lnum])
637 end = lnum - 1
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000638 if end >= 0 and lines[end].lstrip()[:1] == '#' and \
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000639 indentsize(lines[end]) == indent:
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000640 comments = [lines[end].expandtabs().lstrip()]
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000641 if end > 0:
642 end = end - 1
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000643 comment = lines[end].expandtabs().lstrip()
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000644 while comment[:1] == '#' and indentsize(lines[end]) == indent:
645 comments[:0] = [comment]
646 end = end - 1
647 if end < 0: break
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000648 comment = lines[end].expandtabs().lstrip()
649 while comments and comments[0].strip() == '#':
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000650 comments[:1] = []
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000651 while comments and comments[-1].strip() == '#':
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000652 comments[-1:] = []
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000653 return ''.join(comments)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000654
Tim Peters4efb6e92001-06-29 23:51:08 +0000655class EndOfBlock(Exception): pass
656
657class BlockFinder:
658 """Provide a tokeneater() method to detect the end of a code block."""
659 def __init__(self):
660 self.indent = 0
Johannes Gijsbersa5855d52005-03-12 16:37:11 +0000661 self.islambda = False
Johannes Gijsbers1542f342004-12-12 16:46:28 +0000662 self.started = False
663 self.passline = False
Armin Rigodd5c0232005-09-25 11:45:45 +0000664 self.last = 1
Tim Peters4efb6e92001-06-29 23:51:08 +0000665
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000666 def tokeneater(self, type, token, srowcol, erowcol, line):
Tim Peters4efb6e92001-06-29 23:51:08 +0000667 if not self.started:
Armin Rigodd5c0232005-09-25 11:45:45 +0000668 # look for the first "def", "class" or "lambda"
Johannes Gijsbers1542f342004-12-12 16:46:28 +0000669 if token in ("def", "class", "lambda"):
Johannes Gijsbersa5855d52005-03-12 16:37:11 +0000670 if token == "lambda":
671 self.islambda = True
Johannes Gijsbers1542f342004-12-12 16:46:28 +0000672 self.started = True
Armin Rigodd5c0232005-09-25 11:45:45 +0000673 self.passline = True # skip to the end of the line
Tim Peters4efb6e92001-06-29 23:51:08 +0000674 elif type == tokenize.NEWLINE:
Armin Rigodd5c0232005-09-25 11:45:45 +0000675 self.passline = False # stop skipping when a NEWLINE is seen
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000676 self.last = srowcol[0]
Armin Rigodd5c0232005-09-25 11:45:45 +0000677 if self.islambda: # lambdas always end at the first NEWLINE
678 raise EndOfBlock
Johannes Gijsbers1542f342004-12-12 16:46:28 +0000679 elif self.passline:
680 pass
Tim Peters4efb6e92001-06-29 23:51:08 +0000681 elif type == tokenize.INDENT:
682 self.indent = self.indent + 1
Johannes Gijsbers1542f342004-12-12 16:46:28 +0000683 self.passline = True
Tim Peters4efb6e92001-06-29 23:51:08 +0000684 elif type == tokenize.DEDENT:
685 self.indent = self.indent - 1
Armin Rigodd5c0232005-09-25 11:45:45 +0000686 # the end of matching indent/dedent pairs end a block
687 # (note that this only works for "def"/"class" blocks,
688 # not e.g. for "if: else:" or "try: finally:" blocks)
689 if self.indent <= 0:
690 raise EndOfBlock
691 elif self.indent == 0 and type not in (tokenize.COMMENT, tokenize.NL):
692 # any other token on the same indentation level end the previous
693 # block as well, except the pseudo-tokens COMMENT and NL.
694 raise EndOfBlock
Tim Peters4efb6e92001-06-29 23:51:08 +0000695
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000696def getblock(lines):
697 """Extract the block of code at the top of the given list of lines."""
Armin Rigodd5c0232005-09-25 11:45:45 +0000698 blockfinder = BlockFinder()
Tim Peters4efb6e92001-06-29 23:51:08 +0000699 try:
Trent Nelson428de652008-03-18 22:41:35 +0000700 tokens = tokenize.generate_tokens(iter(lines).__next__)
701 for _token in tokens:
702 blockfinder.tokeneater(*_token)
Armin Rigodd5c0232005-09-25 11:45:45 +0000703 except (EndOfBlock, IndentationError):
704 pass
705 return lines[:blockfinder.last]
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000706
707def getsourcelines(object):
708 """Return a list of source lines and starting line number for an object.
709
710 The argument may be a module, class, method, function, traceback, frame,
711 or code object. The source code is returned as a list of the lines
712 corresponding to the object and the line number indicates where in the
713 original source file the first line of code was found. An IOError is
714 raised if the source code cannot be retrieved."""
715 lines, lnum = findsource(object)
716
717 if ismodule(object): return lines, 0
718 else: return getblock(lines[lnum:]), lnum + 1
719
720def getsource(object):
721 """Return the text of the source code for an object.
722
723 The argument may be a module, class, method, function, traceback, frame,
724 or code object. The source code is returned as a single string. An
725 IOError is raised if the source code cannot be retrieved."""
726 lines, lnum = getsourcelines(object)
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000727 return ''.join(lines)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000728
729# --------------------------------------------------- class tree extraction
730def walktree(classes, children, parent):
731 """Recursive helper function for getclasstree()."""
732 results = []
Raymond Hettingera1a992c2005-03-11 06:46:45 +0000733 classes.sort(key=attrgetter('__module__', '__name__'))
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000734 for c in classes:
735 results.append((c, c.__bases__))
Raymond Hettinger54f02222002-06-01 14:18:47 +0000736 if c in children:
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000737 results.append(walktree(children[c], children, c))
738 return results
739
Georg Brandl5ce83a02009-06-01 17:23:51 +0000740def getclasstree(classes, unique=False):
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000741 """Arrange the given list of classes into a hierarchy of nested lists.
742
743 Where a nested list appears, it contains classes derived from the class
744 whose entry immediately precedes the list. Each entry is a 2-tuple
745 containing a class and a tuple of its base classes. If the 'unique'
746 argument is true, exactly one entry appears in the returned structure
747 for each class in the given list. Otherwise, classes using multiple
748 inheritance and their descendants will appear multiple times."""
749 children = {}
750 roots = []
751 for c in classes:
752 if c.__bases__:
753 for parent in c.__bases__:
Raymond Hettinger54f02222002-06-01 14:18:47 +0000754 if not parent in children:
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000755 children[parent] = []
Serhiy Storchaka362c1b52013-09-05 17:14:32 +0300756 if c not in children[parent]:
757 children[parent].append(c)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000758 if unique and parent in classes: break
759 elif c not in roots:
760 roots.append(c)
Raymond Hettingere0d49722002-06-02 18:55:56 +0000761 for parent in children:
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000762 if parent not in classes:
763 roots.append(parent)
764 return walktree(roots, children, None)
765
766# ------------------------------------------------ argument list extraction
Christian Heimes25bb7832008-01-11 16:17:00 +0000767Arguments = namedtuple('Arguments', 'args, varargs, varkw')
768
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000769def getargs(co):
770 """Get information about the arguments accepted by a code object.
771
Guido van Rossum2e65f892007-02-28 22:03:49 +0000772 Three things are returned: (args, varargs, varkw), where
Georg Brandlc1c4bf82010-10-15 16:07:41 +0000773 'args' is the list of argument names. Keyword-only arguments are
774 appended. 'varargs' and 'varkw' are the names of the * and **
775 arguments or None."""
Guido van Rossum2e65f892007-02-28 22:03:49 +0000776 args, varargs, kwonlyargs, varkw = _getfullargs(co)
Christian Heimes25bb7832008-01-11 16:17:00 +0000777 return Arguments(args + kwonlyargs, varargs, varkw)
Guido van Rossum2e65f892007-02-28 22:03:49 +0000778
779def _getfullargs(co):
780 """Get information about the arguments accepted by a code object.
781
782 Four things are returned: (args, varargs, kwonlyargs, varkw), where
Georg Brandlc1c4bf82010-10-15 16:07:41 +0000783 'args' and 'kwonlyargs' are lists of argument names, and 'varargs'
784 and 'varkw' are the names of the * and ** arguments or None."""
Jeremy Hylton64967882003-06-27 18:14:39 +0000785
786 if not iscode(co):
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +0000787 raise TypeError('{!r} is not a code object'.format(co))
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000788
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000789 nargs = co.co_argcount
790 names = co.co_varnames
Guido van Rossum2e65f892007-02-28 22:03:49 +0000791 nkwargs = co.co_kwonlyargcount
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000792 args = list(names[:nargs])
Guido van Rossum2e65f892007-02-28 22:03:49 +0000793 kwonlyargs = list(names[nargs:nargs+nkwargs])
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000794 step = 0
795
Guido van Rossum2e65f892007-02-28 22:03:49 +0000796 nargs += nkwargs
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000797 varargs = None
798 if co.co_flags & CO_VARARGS:
799 varargs = co.co_varnames[nargs]
800 nargs = nargs + 1
801 varkw = None
802 if co.co_flags & CO_VARKEYWORDS:
803 varkw = co.co_varnames[nargs]
Guido van Rossum2e65f892007-02-28 22:03:49 +0000804 return args, varargs, kwonlyargs, varkw
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000805
Christian Heimes25bb7832008-01-11 16:17:00 +0000806
807ArgSpec = namedtuple('ArgSpec', 'args varargs keywords defaults')
808
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000809def getargspec(func):
810 """Get the names and default values of a function's arguments.
811
812 A tuple of four things is returned: (args, varargs, varkw, defaults).
Georg Brandlc1c4bf82010-10-15 16:07:41 +0000813 'args' is a list of the argument names.
Guido van Rossum2e65f892007-02-28 22:03:49 +0000814 'args' will include keyword-only argument names.
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000815 'varargs' and 'varkw' are the names of the * and ** arguments or None.
Jeremy Hylton64967882003-06-27 18:14:39 +0000816 'defaults' is an n-tuple of the default values of the last n arguments.
Guido van Rossuma8add0e2007-05-14 22:03:55 +0000817
Guido van Rossum2e65f892007-02-28 22:03:49 +0000818 Use the getfullargspec() API for Python-3000 code, as annotations
819 and keyword arguments are supported. getargspec() will raise ValueError
820 if the func has either annotations or keyword arguments.
821 """
822
823 args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults, ann = \
824 getfullargspec(func)
825 if kwonlyargs or ann:
Collin Winterce36ad82007-08-30 01:19:48 +0000826 raise ValueError("Function has keyword-only arguments or annotations"
827 ", use getfullargspec() API which can support them")
Christian Heimes25bb7832008-01-11 16:17:00 +0000828 return ArgSpec(args, varargs, varkw, defaults)
829
830FullArgSpec = namedtuple('FullArgSpec',
Benjamin Peterson3d4ca742008-11-12 21:39:01 +0000831 'args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults, annotations')
Guido van Rossum2e65f892007-02-28 22:03:49 +0000832
833def getfullargspec(func):
834 """Get the names and default values of a function's arguments.
835
Brett Cannon504d8852007-09-07 02:12:14 +0000836 A tuple of seven things is returned:
837 (args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults annotations).
Georg Brandlc1c4bf82010-10-15 16:07:41 +0000838 'args' is a list of the argument names.
Guido van Rossum2e65f892007-02-28 22:03:49 +0000839 'varargs' and 'varkw' are the names of the * and ** arguments or None.
840 'defaults' is an n-tuple of the default values of the last n arguments.
841 'kwonlyargs' is a list of keyword-only argument names.
842 'kwonlydefaults' is a dictionary mapping names from kwonlyargs to defaults.
843 'annotations' is a dictionary mapping argument names to annotations.
Guido van Rossuma8add0e2007-05-14 22:03:55 +0000844
Guido van Rossum2e65f892007-02-28 22:03:49 +0000845 The first four items in the tuple correspond to getargspec().
Jeremy Hylton64967882003-06-27 18:14:39 +0000846 """
847
848 if ismethod(func):
Christian Heimesff737952007-11-27 10:40:20 +0000849 func = func.__func__
Jeremy Hylton64967882003-06-27 18:14:39 +0000850 if not isfunction(func):
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +0000851 raise TypeError('{!r} is not a Python function'.format(func))
Guido van Rossum2e65f892007-02-28 22:03:49 +0000852 args, varargs, kwonlyargs, varkw = _getfullargs(func.__code__)
Christian Heimes25bb7832008-01-11 16:17:00 +0000853 return FullArgSpec(args, varargs, varkw, func.__defaults__,
Guido van Rossum2e65f892007-02-28 22:03:49 +0000854 kwonlyargs, func.__kwdefaults__, func.__annotations__)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000855
Christian Heimes25bb7832008-01-11 16:17:00 +0000856ArgInfo = namedtuple('ArgInfo', 'args varargs keywords locals')
857
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000858def getargvalues(frame):
859 """Get information about arguments passed into a particular frame.
860
861 A tuple of four things is returned: (args, varargs, varkw, locals).
Georg Brandlc1c4bf82010-10-15 16:07:41 +0000862 'args' is a list of the argument names.
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000863 'varargs' and 'varkw' are the names of the * and ** arguments or None.
864 'locals' is the locals dictionary of the given frame."""
865 args, varargs, varkw = getargs(frame.f_code)
Benjamin Peterson1a6e0d02008-10-25 15:49:17 +0000866 return ArgInfo(args, varargs, varkw, frame.f_locals)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000867
Guido van Rossum2e65f892007-02-28 22:03:49 +0000868def formatannotation(annotation, base_module=None):
869 if isinstance(annotation, type):
Georg Brandl1a3284e2007-12-02 09:40:06 +0000870 if annotation.__module__ in ('builtins', base_module):
Guido van Rossum2e65f892007-02-28 22:03:49 +0000871 return annotation.__name__
872 return annotation.__module__+'.'+annotation.__name__
873 return repr(annotation)
Guido van Rossuma8add0e2007-05-14 22:03:55 +0000874
Guido van Rossum2e65f892007-02-28 22:03:49 +0000875def formatannotationrelativeto(object):
Guido van Rossuma8add0e2007-05-14 22:03:55 +0000876 module = getattr(object, '__module__', None)
877 def _formatannotation(annotation):
878 return formatannotation(annotation, module)
879 return _formatannotation
Guido van Rossum2e65f892007-02-28 22:03:49 +0000880
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000881def formatargspec(args, varargs=None, varkw=None, defaults=None,
Guido van Rossum2e65f892007-02-28 22:03:49 +0000882 kwonlyargs=(), kwonlydefaults={}, annotations={},
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000883 formatarg=str,
884 formatvarargs=lambda name: '*' + name,
885 formatvarkw=lambda name: '**' + name,
886 formatvalue=lambda value: '=' + repr(value),
Guido van Rossum2e65f892007-02-28 22:03:49 +0000887 formatreturns=lambda text: ' -> ' + text,
Georg Brandlc1c4bf82010-10-15 16:07:41 +0000888 formatannotation=formatannotation):
Guido van Rossuma8add0e2007-05-14 22:03:55 +0000889 """Format an argument spec from the values returned by getargspec
Guido van Rossum2e65f892007-02-28 22:03:49 +0000890 or getfullargspec.
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000891
Guido van Rossum2e65f892007-02-28 22:03:49 +0000892 The first seven arguments are (args, varargs, varkw, defaults,
893 kwonlyargs, kwonlydefaults, annotations). The other five arguments
894 are the corresponding optional formatting functions that are called to
895 turn names and values into strings. The last argument is an optional
896 function to format the sequence of arguments."""
897 def formatargandannotation(arg):
898 result = formatarg(arg)
899 if arg in annotations:
900 result += ': ' + formatannotation(annotations[arg])
901 return result
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000902 specs = []
903 if defaults:
904 firstdefault = len(args) - len(defaults)
Benjamin Petersonb58dda72009-01-18 22:27:04 +0000905 for i, arg in enumerate(args):
Georg Brandlc1c4bf82010-10-15 16:07:41 +0000906 spec = formatargandannotation(arg)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000907 if defaults and i >= firstdefault:
908 spec = spec + formatvalue(defaults[i - firstdefault])
909 specs.append(spec)
Raymond Hettinger936654b2002-06-01 03:06:31 +0000910 if varargs is not None:
Guido van Rossum2e65f892007-02-28 22:03:49 +0000911 specs.append(formatvarargs(formatargandannotation(varargs)))
912 else:
913 if kwonlyargs:
914 specs.append('*')
915 if kwonlyargs:
916 for kwonlyarg in kwonlyargs:
917 spec = formatargandannotation(kwonlyarg)
Benjamin Peterson9953a8d2009-01-17 04:15:01 +0000918 if kwonlydefaults and kwonlyarg in kwonlydefaults:
Guido van Rossum2e65f892007-02-28 22:03:49 +0000919 spec += formatvalue(kwonlydefaults[kwonlyarg])
920 specs.append(spec)
Raymond Hettinger936654b2002-06-01 03:06:31 +0000921 if varkw is not None:
Guido van Rossum2e65f892007-02-28 22:03:49 +0000922 specs.append(formatvarkw(formatargandannotation(varkw)))
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000923 result = '(' + ', '.join(specs) + ')'
Guido van Rossum2e65f892007-02-28 22:03:49 +0000924 if 'return' in annotations:
925 result += formatreturns(formatannotation(annotations['return']))
926 return result
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000927
928def formatargvalues(args, varargs, varkw, locals,
929 formatarg=str,
930 formatvarargs=lambda name: '*' + name,
931 formatvarkw=lambda name: '**' + name,
Georg Brandlc1c4bf82010-10-15 16:07:41 +0000932 formatvalue=lambda value: '=' + repr(value)):
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000933 """Format an argument spec from the 4 values returned by getargvalues.
934
935 The first four arguments are (args, varargs, varkw, locals). The
936 next four arguments are the corresponding optional formatting functions
937 that are called to turn names and values into strings. The ninth
938 argument is an optional function to format the sequence of arguments."""
939 def convert(name, locals=locals,
940 formatarg=formatarg, formatvalue=formatvalue):
941 return formatarg(name) + formatvalue(locals[name])
942 specs = []
943 for i in range(len(args)):
Georg Brandlc1c4bf82010-10-15 16:07:41 +0000944 specs.append(convert(args[i]))
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000945 if varargs:
946 specs.append(formatvarargs(varargs) + formatvalue(locals[varargs]))
947 if varkw:
948 specs.append(formatvarkw(varkw) + formatvalue(locals[varkw]))
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000949 return '(' + ', '.join(specs) + ')'
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000950
Benjamin Petersone109c702011-06-24 09:37:26 -0500951def _missing_arguments(f_name, argnames, pos, values):
952 names = [repr(name) for name in argnames if name not in values]
953 missing = len(names)
954 if missing == 1:
955 s = names[0]
956 elif missing == 2:
957 s = "{} and {}".format(*names)
958 else:
959 tail = ", {} and {}".format(names[-2:])
960 del names[-2:]
961 s = ", ".join(names) + tail
962 raise TypeError("%s() missing %i required %s argument%s: %s" %
963 (f_name, missing,
964 "positional" if pos else "keyword-only",
965 "" if missing == 1 else "s", s))
966
967def _too_many(f_name, args, kwonly, varargs, defcount, given, values):
Benjamin Petersonb204a422011-06-05 22:04:07 -0500968 atleast = len(args) - defcount
Benjamin Petersonb204a422011-06-05 22:04:07 -0500969 kwonly_given = len([arg for arg in kwonly if arg in values])
970 if varargs:
971 plural = atleast != 1
972 sig = "at least %d" % (atleast,)
973 elif defcount:
974 plural = True
975 sig = "from %d to %d" % (atleast, len(args))
976 else:
977 plural = len(args) != 1
978 sig = str(len(args))
979 kwonly_sig = ""
980 if kwonly_given:
981 msg = " positional argument%s (and %d keyword-only argument%s)"
982 kwonly_sig = (msg % ("s" if given != 1 else "", kwonly_given,
983 "s" if kwonly_given != 1 else ""))
984 raise TypeError("%s() takes %s positional argument%s but %d%s %s given" %
985 (f_name, sig, "s" if plural else "", given, kwonly_sig,
986 "was" if given == 1 and not kwonly_given else "were"))
987
Benjamin Peterson25cd7eb2010-03-30 18:42:32 +0000988def getcallargs(func, *positional, **named):
989 """Get the mapping of arguments to values.
990
991 A dict is returned, with keys the function argument names (including the
992 names of the * and ** arguments, if any), and values the respective bound
993 values from 'positional' and 'named'."""
994 spec = getfullargspec(func)
995 args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults, ann = spec
996 f_name = func.__name__
997 arg2value = {}
998
Benjamin Petersonb204a422011-06-05 22:04:07 -0500999
Benjamin Peterson25cd7eb2010-03-30 18:42:32 +00001000 if ismethod(func) and func.__self__ is not None:
1001 # implicit 'self' (or 'cls' for classmethods) argument
1002 positional = (func.__self__,) + positional
1003 num_pos = len(positional)
Benjamin Peterson25cd7eb2010-03-30 18:42:32 +00001004 num_args = len(args)
1005 num_defaults = len(defaults) if defaults else 0
Benjamin Peterson25cd7eb2010-03-30 18:42:32 +00001006
Benjamin Petersonb204a422011-06-05 22:04:07 -05001007 n = min(num_pos, num_args)
1008 for i in range(n):
1009 arg2value[args[i]] = positional[i]
1010 if varargs:
1011 arg2value[varargs] = tuple(positional[n:])
1012 possible_kwargs = set(args + kwonlyargs)
Benjamin Peterson25cd7eb2010-03-30 18:42:32 +00001013 if varkw:
Benjamin Petersonb204a422011-06-05 22:04:07 -05001014 arg2value[varkw] = {}
1015 for kw, value in named.items():
1016 if kw not in possible_kwargs:
1017 if not varkw:
1018 raise TypeError("%s() got an unexpected keyword argument %r" %
1019 (f_name, kw))
1020 arg2value[varkw][kw] = value
1021 continue
1022 if kw in arg2value:
1023 raise TypeError("%s() got multiple values for argument %r" %
1024 (f_name, kw))
1025 arg2value[kw] = value
1026 if num_pos > num_args and not varargs:
Benjamin Petersone109c702011-06-24 09:37:26 -05001027 _too_many(f_name, args, kwonlyargs, varargs, num_defaults,
1028 num_pos, arg2value)
Benjamin Petersonb204a422011-06-05 22:04:07 -05001029 if num_pos < num_args:
Benjamin Petersone109c702011-06-24 09:37:26 -05001030 req = args[:num_args - num_defaults]
1031 for arg in req:
Benjamin Petersonb204a422011-06-05 22:04:07 -05001032 if arg not in arg2value:
Benjamin Petersone109c702011-06-24 09:37:26 -05001033 _missing_arguments(f_name, req, True, arg2value)
Benjamin Petersonb204a422011-06-05 22:04:07 -05001034 for i, arg in enumerate(args[num_args - num_defaults:]):
1035 if arg not in arg2value:
1036 arg2value[arg] = defaults[i]
Benjamin Petersone109c702011-06-24 09:37:26 -05001037 missing = 0
Benjamin Petersonb204a422011-06-05 22:04:07 -05001038 for kwarg in kwonlyargs:
1039 if kwarg not in arg2value:
Benjamin Petersone109c702011-06-24 09:37:26 -05001040 if kwarg in kwonlydefaults:
1041 arg2value[kwarg] = kwonlydefaults[kwarg]
1042 else:
1043 missing += 1
1044 if missing:
1045 _missing_arguments(f_name, kwonlyargs, False, arg2value)
Benjamin Peterson25cd7eb2010-03-30 18:42:32 +00001046 return arg2value
1047
Nick Coghlan2f92e542012-06-23 19:39:55 +10001048ClosureVars = namedtuple('ClosureVars', 'nonlocals globals builtins unbound')
1049
1050def getclosurevars(func):
1051 """
1052 Get the mapping of free variables to their current values.
1053
Meador Inge8fda3592012-07-19 21:33:21 -05001054 Returns a named tuple of dicts mapping the current nonlocal, global
Nick Coghlan2f92e542012-06-23 19:39:55 +10001055 and builtin references as seen by the body of the function. A final
1056 set of unbound names that could not be resolved is also provided.
1057 """
1058
1059 if ismethod(func):
1060 func = func.__func__
1061
1062 if not isfunction(func):
1063 raise TypeError("'{!r}' is not a Python function".format(func))
1064
1065 code = func.__code__
1066 # Nonlocal references are named in co_freevars and resolved
1067 # by looking them up in __closure__ by positional index
1068 if func.__closure__ is None:
1069 nonlocal_vars = {}
1070 else:
1071 nonlocal_vars = {
1072 var : cell.cell_contents
1073 for var, cell in zip(code.co_freevars, func.__closure__)
1074 }
1075
1076 # Global and builtin references are named in co_names and resolved
1077 # by looking them up in __globals__ or __builtins__
1078 global_ns = func.__globals__
1079 builtin_ns = global_ns.get("__builtins__", builtins.__dict__)
1080 if ismodule(builtin_ns):
1081 builtin_ns = builtin_ns.__dict__
1082 global_vars = {}
1083 builtin_vars = {}
1084 unbound_names = set()
1085 for name in code.co_names:
1086 if name in ("None", "True", "False"):
1087 # Because these used to be builtins instead of keywords, they
1088 # may still show up as name references. We ignore them.
1089 continue
1090 try:
1091 global_vars[name] = global_ns[name]
1092 except KeyError:
1093 try:
1094 builtin_vars[name] = builtin_ns[name]
1095 except KeyError:
1096 unbound_names.add(name)
1097
1098 return ClosureVars(nonlocal_vars, global_vars,
1099 builtin_vars, unbound_names)
1100
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001101# -------------------------------------------------- stack frame extraction
Christian Heimes25bb7832008-01-11 16:17:00 +00001102
1103Traceback = namedtuple('Traceback', 'filename lineno function code_context index')
1104
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001105def getframeinfo(frame, context=1):
1106 """Get information about a frame or traceback object.
1107
1108 A tuple of five things is returned: the filename, the line number of
1109 the current line, the function name, a list of lines of context from
1110 the source code, and the index of the current line within that list.
1111 The optional second argument specifies the number of lines of context
1112 to return, which are centered around the current line."""
1113 if istraceback(frame):
Andrew M. Kuchlingba8b6bc2004-06-05 14:11:59 +00001114 lineno = frame.tb_lineno
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001115 frame = frame.tb_frame
Andrew M. Kuchlingba8b6bc2004-06-05 14:11:59 +00001116 else:
1117 lineno = frame.f_lineno
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001118 if not isframe(frame):
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00001119 raise TypeError('{!r} is not a frame or traceback object'.format(frame))
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001120
Neil Schemenauerf06f8532002-03-23 23:51:04 +00001121 filename = getsourcefile(frame) or getfile(frame)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001122 if context > 0:
Guido van Rossum54e54c62001-09-04 19:14:14 +00001123 start = lineno - 1 - context//2
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001124 try:
1125 lines, lnum = findsource(frame)
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +00001126 except IOError:
1127 lines = index = None
1128 else:
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001129 start = max(start, 1)
Raymond Hettingera0501712004-06-15 11:22:53 +00001130 start = max(0, min(start, len(lines) - context))
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001131 lines = lines[start:start+context]
Ka-Ping Yee59ade082001-03-01 03:55:35 +00001132 index = lineno - 1 - start
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001133 else:
1134 lines = index = None
1135
Christian Heimes25bb7832008-01-11 16:17:00 +00001136 return Traceback(filename, lineno, frame.f_code.co_name, lines, index)
Ka-Ping Yee59ade082001-03-01 03:55:35 +00001137
1138def getlineno(frame):
1139 """Get the line number from a frame object, allowing for optimization."""
Michael W. Hudsondd32a912002-08-15 14:59:02 +00001140 # FrameType.f_lineno is now a descriptor that grovels co_lnotab
1141 return frame.f_lineno
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001142
1143def getouterframes(frame, context=1):
1144 """Get a list of records for a frame and all higher (calling) frames.
1145
1146 Each record contains a frame object, filename, line number, function
1147 name, a list of lines of context, and index within the context."""
1148 framelist = []
1149 while frame:
1150 framelist.append((frame,) + getframeinfo(frame, context))
1151 frame = frame.f_back
1152 return framelist
1153
1154def getinnerframes(tb, context=1):
1155 """Get a list of records for a traceback's frame and all lower frames.
1156
1157 Each record contains a frame object, filename, line number, function
1158 name, a list of lines of context, and index within the context."""
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001159 framelist = []
1160 while tb:
1161 framelist.append((tb.tb_frame,) + getframeinfo(tb, context))
1162 tb = tb.tb_next
1163 return framelist
1164
Benjamin Peterson42ac4752010-08-09 13:05:35 +00001165def currentframe():
Benjamin Petersona3a3fc62010-08-09 15:49:56 +00001166 """Return the frame of the caller or None if this is not possible."""
Benjamin Peterson42ac4752010-08-09 13:05:35 +00001167 return sys._getframe(1) if hasattr(sys, "_getframe") else None
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001168
1169def stack(context=1):
1170 """Return a list of records for the stack above the caller's frame."""
Jeremy Hyltonab919022003-06-27 18:41:20 +00001171 return getouterframes(sys._getframe(1), context)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001172
1173def trace(context=1):
Tim Peters85ba6732001-02-28 08:26:44 +00001174 """Return a list of records for the stack below the current exception."""
Fred Draked451ec12002-04-26 02:29:55 +00001175 return getinnerframes(sys.exc_info()[2], context)
Michael Foord95fc51d2010-11-20 15:07:30 +00001176
1177
1178# ------------------------------------------------ static version of getattr
1179
1180_sentinel = object()
1181
Michael Foorde5162652010-11-20 16:40:44 +00001182def _static_getmro(klass):
1183 return type.__dict__['__mro__'].__get__(klass)
1184
Michael Foord95fc51d2010-11-20 15:07:30 +00001185def _check_instance(obj, attr):
1186 instance_dict = {}
1187 try:
1188 instance_dict = object.__getattribute__(obj, "__dict__")
1189 except AttributeError:
1190 pass
Michael Foorddcebe0f2011-03-15 19:20:44 -04001191 return dict.get(instance_dict, attr, _sentinel)
Michael Foord95fc51d2010-11-20 15:07:30 +00001192
1193
1194def _check_class(klass, attr):
Michael Foorde5162652010-11-20 16:40:44 +00001195 for entry in _static_getmro(klass):
Michael Foorda51623b2011-12-18 22:01:40 +00001196 if _shadowed_dict(type(entry)) is _sentinel:
Michael Foorddcebe0f2011-03-15 19:20:44 -04001197 try:
1198 return entry.__dict__[attr]
1199 except KeyError:
1200 pass
Michael Foord95fc51d2010-11-20 15:07:30 +00001201 return _sentinel
1202
Michael Foord35184ed2010-11-20 16:58:30 +00001203def _is_type(obj):
1204 try:
1205 _static_getmro(obj)
1206 except TypeError:
1207 return False
1208 return True
1209
Michael Foorddcebe0f2011-03-15 19:20:44 -04001210def _shadowed_dict(klass):
1211 dict_attr = type.__dict__["__dict__"]
1212 for entry in _static_getmro(klass):
1213 try:
1214 class_dict = dict_attr.__get__(entry)["__dict__"]
1215 except KeyError:
1216 pass
1217 else:
1218 if not (type(class_dict) is types.GetSetDescriptorType and
1219 class_dict.__name__ == "__dict__" and
1220 class_dict.__objclass__ is entry):
Michael Foorda51623b2011-12-18 22:01:40 +00001221 return class_dict
1222 return _sentinel
Michael Foord95fc51d2010-11-20 15:07:30 +00001223
1224def getattr_static(obj, attr, default=_sentinel):
1225 """Retrieve attributes without triggering dynamic lookup via the
1226 descriptor protocol, __getattr__ or __getattribute__.
1227
1228 Note: this function may not be able to retrieve all attributes
1229 that getattr can fetch (like dynamically created attributes)
1230 and may find attributes that getattr can't (like descriptors
1231 that raise AttributeError). It can also return descriptor objects
1232 instead of instance members in some cases. See the
1233 documentation for details.
1234 """
1235 instance_result = _sentinel
Michael Foord35184ed2010-11-20 16:58:30 +00001236 if not _is_type(obj):
Michael Foordcc7ebb82010-11-20 16:20:16 +00001237 klass = type(obj)
Michael Foorda51623b2011-12-18 22:01:40 +00001238 dict_attr = _shadowed_dict(klass)
1239 if (dict_attr is _sentinel or
1240 type(dict_attr) is types.MemberDescriptorType):
Michael Foorddcebe0f2011-03-15 19:20:44 -04001241 instance_result = _check_instance(obj, attr)
Michael Foord95fc51d2010-11-20 15:07:30 +00001242 else:
1243 klass = obj
1244
1245 klass_result = _check_class(klass, attr)
1246
1247 if instance_result is not _sentinel and klass_result is not _sentinel:
1248 if (_check_class(type(klass_result), '__get__') is not _sentinel and
1249 _check_class(type(klass_result), '__set__') is not _sentinel):
1250 return klass_result
1251
1252 if instance_result is not _sentinel:
1253 return instance_result
1254 if klass_result is not _sentinel:
1255 return klass_result
1256
1257 if obj is klass:
1258 # for types we check the metaclass too
Michael Foorde5162652010-11-20 16:40:44 +00001259 for entry in _static_getmro(type(klass)):
Michael Foord3ba95f82011-12-22 01:13:37 +00001260 if _shadowed_dict(type(entry)) is _sentinel:
1261 try:
1262 return entry.__dict__[attr]
1263 except KeyError:
1264 pass
Michael Foord95fc51d2010-11-20 15:07:30 +00001265 if default is not _sentinel:
1266 return default
1267 raise AttributeError(attr)
Nick Coghlane0f04652010-11-21 03:44:04 +00001268
1269
Nick Coghlan04e2e3f2012-06-23 19:52:05 +10001270# ------------------------------------------------ generator introspection
1271
Nick Coghlan7921b9f2010-11-30 06:36:04 +00001272GEN_CREATED = 'GEN_CREATED'
1273GEN_RUNNING = 'GEN_RUNNING'
1274GEN_SUSPENDED = 'GEN_SUSPENDED'
1275GEN_CLOSED = 'GEN_CLOSED'
Nick Coghlane0f04652010-11-21 03:44:04 +00001276
1277def getgeneratorstate(generator):
1278 """Get current state of a generator-iterator.
1279
1280 Possible states are:
1281 GEN_CREATED: Waiting to start execution.
1282 GEN_RUNNING: Currently being executed by the interpreter.
1283 GEN_SUSPENDED: Currently suspended at a yield expression.
1284 GEN_CLOSED: Execution has completed.
1285 """
1286 if generator.gi_running:
1287 return GEN_RUNNING
1288 if generator.gi_frame is None:
1289 return GEN_CLOSED
1290 if generator.gi_frame.f_lasti == -1:
1291 return GEN_CREATED
1292 return GEN_SUSPENDED
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07001293
1294
Nick Coghlan04e2e3f2012-06-23 19:52:05 +10001295def getgeneratorlocals(generator):
1296 """
1297 Get the mapping of generator local variables to their current values.
1298
1299 A dict is returned, with the keys the local variable names and values the
1300 bound values."""
1301
1302 if not isgenerator(generator):
1303 raise TypeError("'{!r}' is not a Python generator".format(generator))
1304
1305 frame = getattr(generator, "gi_frame", None)
1306 if frame is not None:
1307 return generator.gi_frame.f_locals
1308 else:
1309 return {}
1310
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07001311###############################################################################
1312### Function Signature Object (PEP 362)
1313###############################################################################
1314
1315
1316_WrapperDescriptor = type(type.__call__)
1317_MethodWrapper = type(all.__call__)
1318
1319_NonUserDefinedCallables = (_WrapperDescriptor,
1320 _MethodWrapper,
1321 types.BuiltinFunctionType)
1322
1323
1324def _get_user_defined_method(cls, method_name):
1325 try:
1326 meth = getattr(cls, method_name)
1327 except AttributeError:
1328 return
1329 else:
1330 if not isinstance(meth, _NonUserDefinedCallables):
1331 # Once '__signature__' will be added to 'C'-level
1332 # callables, this check won't be necessary
1333 return meth
1334
1335
1336def signature(obj):
1337 '''Get a signature object for the passed callable.'''
1338
1339 if not callable(obj):
1340 raise TypeError('{!r} is not a callable object'.format(obj))
1341
1342 if isinstance(obj, types.MethodType):
1343 # In this case we skip the first parameter of the underlying
1344 # function (usually `self` or `cls`).
1345 sig = signature(obj.__func__)
1346 return sig.replace(parameters=tuple(sig.parameters.values())[1:])
1347
1348 try:
1349 sig = obj.__signature__
1350 except AttributeError:
1351 pass
1352 else:
1353 if sig is not None:
1354 return sig
1355
1356 try:
1357 # Was this function wrapped by a decorator?
1358 wrapped = obj.__wrapped__
1359 except AttributeError:
1360 pass
1361 else:
1362 return signature(wrapped)
1363
1364 if isinstance(obj, types.FunctionType):
1365 return Signature.from_function(obj)
1366
1367 if isinstance(obj, functools.partial):
1368 sig = signature(obj.func)
1369
1370 new_params = OrderedDict(sig.parameters.items())
1371
1372 partial_args = obj.args or ()
1373 partial_keywords = obj.keywords or {}
1374 try:
1375 ba = sig.bind_partial(*partial_args, **partial_keywords)
1376 except TypeError as ex:
1377 msg = 'partial object {!r} has incorrect arguments'.format(obj)
1378 raise ValueError(msg) from ex
1379
1380 for arg_name, arg_value in ba.arguments.items():
1381 param = new_params[arg_name]
1382 if arg_name in partial_keywords:
1383 # We set a new default value, because the following code
1384 # is correct:
1385 #
1386 # >>> def foo(a): print(a)
1387 # >>> print(partial(partial(foo, a=10), a=20)())
1388 # 20
1389 # >>> print(partial(partial(foo, a=10), a=20)(a=30))
1390 # 30
1391 #
1392 # So, with 'partial' objects, passing a keyword argument is
1393 # like setting a new default value for the corresponding
1394 # parameter
1395 #
1396 # We also mark this parameter with '_partial_kwarg'
1397 # flag. Later, in '_bind', the 'default' value of this
1398 # parameter will be added to 'kwargs', to simulate
1399 # the 'functools.partial' real call.
1400 new_params[arg_name] = param.replace(default=arg_value,
1401 _partial_kwarg=True)
1402
1403 elif (param.kind not in (_VAR_KEYWORD, _VAR_POSITIONAL) and
1404 not param._partial_kwarg):
1405 new_params.pop(arg_name)
1406
1407 return sig.replace(parameters=new_params.values())
1408
1409 sig = None
1410 if isinstance(obj, type):
1411 # obj is a class or a metaclass
1412
1413 # First, let's see if it has an overloaded __call__ defined
1414 # in its metaclass
1415 call = _get_user_defined_method(type(obj), '__call__')
1416 if call is not None:
1417 sig = signature(call)
1418 else:
1419 # Now we check if the 'obj' class has a '__new__' method
1420 new = _get_user_defined_method(obj, '__new__')
1421 if new is not None:
1422 sig = signature(new)
1423 else:
1424 # Finally, we should have at least __init__ implemented
1425 init = _get_user_defined_method(obj, '__init__')
1426 if init is not None:
1427 sig = signature(init)
1428 elif not isinstance(obj, _NonUserDefinedCallables):
1429 # An object with __call__
1430 # We also check that the 'obj' is not an instance of
1431 # _WrapperDescriptor or _MethodWrapper to avoid
1432 # infinite recursion (and even potential segfault)
1433 call = _get_user_defined_method(type(obj), '__call__')
1434 if call is not None:
1435 sig = signature(call)
1436
1437 if sig is not None:
1438 # For classes and objects we skip the first parameter of their
1439 # __call__, __new__, or __init__ methods
1440 return sig.replace(parameters=tuple(sig.parameters.values())[1:])
1441
1442 if isinstance(obj, types.BuiltinFunctionType):
1443 # Raise a nicer error message for builtins
1444 msg = 'no signature found for builtin function {!r}'.format(obj)
1445 raise ValueError(msg)
1446
1447 raise ValueError('callable {!r} is not supported by signature'.format(obj))
1448
1449
1450class _void:
1451 '''A private marker - used in Parameter & Signature'''
1452
1453
1454class _empty:
1455 pass
1456
1457
1458class _ParameterKind(int):
1459 def __new__(self, *args, name):
1460 obj = int.__new__(self, *args)
1461 obj._name = name
1462 return obj
1463
1464 def __str__(self):
1465 return self._name
1466
1467 def __repr__(self):
1468 return '<_ParameterKind: {!r}>'.format(self._name)
1469
1470
1471_POSITIONAL_ONLY = _ParameterKind(0, name='POSITIONAL_ONLY')
1472_POSITIONAL_OR_KEYWORD = _ParameterKind(1, name='POSITIONAL_OR_KEYWORD')
1473_VAR_POSITIONAL = _ParameterKind(2, name='VAR_POSITIONAL')
1474_KEYWORD_ONLY = _ParameterKind(3, name='KEYWORD_ONLY')
1475_VAR_KEYWORD = _ParameterKind(4, name='VAR_KEYWORD')
1476
1477
1478class Parameter:
1479 '''Represents a parameter in a function signature.
1480
1481 Has the following public attributes:
1482
1483 * name : str
1484 The name of the parameter as a string.
1485 * default : object
1486 The default value for the parameter if specified. If the
1487 parameter has no default value, this attribute is not set.
1488 * annotation
1489 The annotation for the parameter if specified. If the
1490 parameter has no annotation, this attribute is not set.
1491 * kind : str
1492 Describes how argument values are bound to the parameter.
1493 Possible values: `Parameter.POSITIONAL_ONLY`,
1494 `Parameter.POSITIONAL_OR_KEYWORD`, `Parameter.VAR_POSITIONAL`,
1495 `Parameter.KEYWORD_ONLY`, `Parameter.VAR_KEYWORD`.
1496 '''
1497
1498 __slots__ = ('_name', '_kind', '_default', '_annotation', '_partial_kwarg')
1499
1500 POSITIONAL_ONLY = _POSITIONAL_ONLY
1501 POSITIONAL_OR_KEYWORD = _POSITIONAL_OR_KEYWORD
1502 VAR_POSITIONAL = _VAR_POSITIONAL
1503 KEYWORD_ONLY = _KEYWORD_ONLY
1504 VAR_KEYWORD = _VAR_KEYWORD
1505
1506 empty = _empty
1507
1508 def __init__(self, name, kind, *, default=_empty, annotation=_empty,
1509 _partial_kwarg=False):
1510
1511 if kind not in (_POSITIONAL_ONLY, _POSITIONAL_OR_KEYWORD,
1512 _VAR_POSITIONAL, _KEYWORD_ONLY, _VAR_KEYWORD):
1513 raise ValueError("invalid value for 'Parameter.kind' attribute")
1514 self._kind = kind
1515
1516 if default is not _empty:
1517 if kind in (_VAR_POSITIONAL, _VAR_KEYWORD):
1518 msg = '{} parameters cannot have default values'.format(kind)
1519 raise ValueError(msg)
1520 self._default = default
1521 self._annotation = annotation
1522
1523 if name is None:
1524 if kind != _POSITIONAL_ONLY:
1525 raise ValueError("None is not a valid name for a "
1526 "non-positional-only parameter")
1527 self._name = name
1528 else:
1529 name = str(name)
1530 if kind != _POSITIONAL_ONLY and not name.isidentifier():
1531 msg = '{!r} is not a valid parameter name'.format(name)
1532 raise ValueError(msg)
1533 self._name = name
1534
1535 self._partial_kwarg = _partial_kwarg
1536
1537 @property
1538 def name(self):
1539 return self._name
1540
1541 @property
1542 def default(self):
1543 return self._default
1544
1545 @property
1546 def annotation(self):
1547 return self._annotation
1548
1549 @property
1550 def kind(self):
1551 return self._kind
1552
1553 def replace(self, *, name=_void, kind=_void, annotation=_void,
1554 default=_void, _partial_kwarg=_void):
1555 '''Creates a customized copy of the Parameter.'''
1556
1557 if name is _void:
1558 name = self._name
1559
1560 if kind is _void:
1561 kind = self._kind
1562
1563 if annotation is _void:
1564 annotation = self._annotation
1565
1566 if default is _void:
1567 default = self._default
1568
1569 if _partial_kwarg is _void:
1570 _partial_kwarg = self._partial_kwarg
1571
1572 return type(self)(name, kind, default=default, annotation=annotation,
1573 _partial_kwarg=_partial_kwarg)
1574
1575 def __str__(self):
1576 kind = self.kind
1577
1578 formatted = self._name
1579 if kind == _POSITIONAL_ONLY:
1580 if formatted is None:
1581 formatted = ''
1582 formatted = '<{}>'.format(formatted)
1583
1584 # Add annotation and default value
1585 if self._annotation is not _empty:
1586 formatted = '{}:{}'.format(formatted,
1587 formatannotation(self._annotation))
1588
1589 if self._default is not _empty:
1590 formatted = '{}={}'.format(formatted, repr(self._default))
1591
1592 if kind == _VAR_POSITIONAL:
1593 formatted = '*' + formatted
1594 elif kind == _VAR_KEYWORD:
1595 formatted = '**' + formatted
1596
1597 return formatted
1598
1599 def __repr__(self):
1600 return '<{} at {:#x} {!r}>'.format(self.__class__.__name__,
1601 id(self), self.name)
1602
1603 def __eq__(self, other):
1604 return (issubclass(other.__class__, Parameter) and
1605 self._name == other._name and
1606 self._kind == other._kind and
1607 self._default == other._default and
1608 self._annotation == other._annotation)
1609
1610 def __ne__(self, other):
1611 return not self.__eq__(other)
1612
1613
1614class BoundArguments:
1615 '''Result of `Signature.bind` call. Holds the mapping of arguments
1616 to the function's parameters.
1617
1618 Has the following public attributes:
1619
1620 * arguments : OrderedDict
1621 An ordered mutable mapping of parameters' names to arguments' values.
1622 Does not contain arguments' default values.
1623 * signature : Signature
1624 The Signature object that created this instance.
1625 * args : tuple
1626 Tuple of positional arguments values.
1627 * kwargs : dict
1628 Dict of keyword arguments values.
1629 '''
1630
1631 def __init__(self, signature, arguments):
1632 self.arguments = arguments
1633 self._signature = signature
1634
1635 @property
1636 def signature(self):
1637 return self._signature
1638
1639 @property
1640 def args(self):
1641 args = []
1642 for param_name, param in self._signature.parameters.items():
1643 if (param.kind in (_VAR_KEYWORD, _KEYWORD_ONLY) or
1644 param._partial_kwarg):
1645 # Keyword arguments mapped by 'functools.partial'
1646 # (Parameter._partial_kwarg is True) are mapped
1647 # in 'BoundArguments.kwargs', along with VAR_KEYWORD &
1648 # KEYWORD_ONLY
1649 break
1650
1651 try:
1652 arg = self.arguments[param_name]
1653 except KeyError:
1654 # We're done here. Other arguments
1655 # will be mapped in 'BoundArguments.kwargs'
1656 break
1657 else:
1658 if param.kind == _VAR_POSITIONAL:
1659 # *args
1660 args.extend(arg)
1661 else:
1662 # plain argument
1663 args.append(arg)
1664
1665 return tuple(args)
1666
1667 @property
1668 def kwargs(self):
1669 kwargs = {}
1670 kwargs_started = False
1671 for param_name, param in self._signature.parameters.items():
1672 if not kwargs_started:
1673 if (param.kind in (_VAR_KEYWORD, _KEYWORD_ONLY) or
1674 param._partial_kwarg):
1675 kwargs_started = True
1676 else:
1677 if param_name not in self.arguments:
1678 kwargs_started = True
1679 continue
1680
1681 if not kwargs_started:
1682 continue
1683
1684 try:
1685 arg = self.arguments[param_name]
1686 except KeyError:
1687 pass
1688 else:
1689 if param.kind == _VAR_KEYWORD:
1690 # **kwargs
1691 kwargs.update(arg)
1692 else:
1693 # plain keyword argument
1694 kwargs[param_name] = arg
1695
1696 return kwargs
1697
1698 def __eq__(self, other):
1699 return (issubclass(other.__class__, BoundArguments) and
1700 self.signature == other.signature and
1701 self.arguments == other.arguments)
1702
1703 def __ne__(self, other):
1704 return not self.__eq__(other)
1705
1706
1707class Signature:
1708 '''A Signature object represents the overall signature of a function.
1709 It stores a Parameter object for each parameter accepted by the
1710 function, as well as information specific to the function itself.
1711
1712 A Signature object has the following public attributes and methods:
1713
1714 * parameters : OrderedDict
1715 An ordered mapping of parameters' names to the corresponding
1716 Parameter objects (keyword-only arguments are in the same order
1717 as listed in `code.co_varnames`).
1718 * return_annotation : object
1719 The annotation for the return type of the function if specified.
1720 If the function has no annotation for its return type, this
1721 attribute is not set.
1722 * bind(*args, **kwargs) -> BoundArguments
1723 Creates a mapping from positional and keyword arguments to
1724 parameters.
1725 * bind_partial(*args, **kwargs) -> BoundArguments
1726 Creates a partial mapping from positional and keyword arguments
1727 to parameters (simulating 'functools.partial' behavior.)
1728 '''
1729
1730 __slots__ = ('_return_annotation', '_parameters')
1731
1732 _parameter_cls = Parameter
1733 _bound_arguments_cls = BoundArguments
1734
1735 empty = _empty
1736
1737 def __init__(self, parameters=None, *, return_annotation=_empty,
1738 __validate_parameters__=True):
1739 '''Constructs Signature from the given list of Parameter
1740 objects and 'return_annotation'. All arguments are optional.
1741 '''
1742
1743 if parameters is None:
1744 params = OrderedDict()
1745 else:
1746 if __validate_parameters__:
1747 params = OrderedDict()
1748 top_kind = _POSITIONAL_ONLY
1749
1750 for idx, param in enumerate(parameters):
1751 kind = param.kind
1752 if kind < top_kind:
1753 msg = 'wrong parameter order: {} before {}'
1754 msg = msg.format(top_kind, param.kind)
1755 raise ValueError(msg)
1756 else:
1757 top_kind = kind
1758
1759 name = param.name
1760 if name is None:
1761 name = str(idx)
1762 param = param.replace(name=name)
1763
1764 if name in params:
1765 msg = 'duplicate parameter name: {!r}'.format(name)
1766 raise ValueError(msg)
1767 params[name] = param
1768 else:
1769 params = OrderedDict(((param.name, param)
1770 for param in parameters))
1771
1772 self._parameters = types.MappingProxyType(params)
1773 self._return_annotation = return_annotation
1774
1775 @classmethod
1776 def from_function(cls, func):
1777 '''Constructs Signature for the given python function'''
1778
1779 if not isinstance(func, types.FunctionType):
1780 raise TypeError('{!r} is not a Python function'.format(func))
1781
1782 Parameter = cls._parameter_cls
1783
1784 # Parameter information.
1785 func_code = func.__code__
1786 pos_count = func_code.co_argcount
1787 arg_names = func_code.co_varnames
1788 positional = tuple(arg_names[:pos_count])
1789 keyword_only_count = func_code.co_kwonlyargcount
1790 keyword_only = arg_names[pos_count:(pos_count + keyword_only_count)]
1791 annotations = func.__annotations__
1792 defaults = func.__defaults__
1793 kwdefaults = func.__kwdefaults__
1794
1795 if defaults:
1796 pos_default_count = len(defaults)
1797 else:
1798 pos_default_count = 0
1799
1800 parameters = []
1801
1802 # Non-keyword-only parameters w/o defaults.
1803 non_default_count = pos_count - pos_default_count
1804 for name in positional[:non_default_count]:
1805 annotation = annotations.get(name, _empty)
1806 parameters.append(Parameter(name, annotation=annotation,
1807 kind=_POSITIONAL_OR_KEYWORD))
1808
1809 # ... w/ defaults.
1810 for offset, name in enumerate(positional[non_default_count:]):
1811 annotation = annotations.get(name, _empty)
1812 parameters.append(Parameter(name, annotation=annotation,
1813 kind=_POSITIONAL_OR_KEYWORD,
1814 default=defaults[offset]))
1815
1816 # *args
1817 if func_code.co_flags & 0x04:
1818 name = arg_names[pos_count + keyword_only_count]
1819 annotation = annotations.get(name, _empty)
1820 parameters.append(Parameter(name, annotation=annotation,
1821 kind=_VAR_POSITIONAL))
1822
1823 # Keyword-only parameters.
1824 for name in keyword_only:
1825 default = _empty
1826 if kwdefaults is not None:
1827 default = kwdefaults.get(name, _empty)
1828
1829 annotation = annotations.get(name, _empty)
1830 parameters.append(Parameter(name, annotation=annotation,
1831 kind=_KEYWORD_ONLY,
1832 default=default))
1833 # **kwargs
1834 if func_code.co_flags & 0x08:
1835 index = pos_count + keyword_only_count
1836 if func_code.co_flags & 0x04:
1837 index += 1
1838
1839 name = arg_names[index]
1840 annotation = annotations.get(name, _empty)
1841 parameters.append(Parameter(name, annotation=annotation,
1842 kind=_VAR_KEYWORD))
1843
1844 return cls(parameters,
1845 return_annotation=annotations.get('return', _empty),
1846 __validate_parameters__=False)
1847
1848 @property
1849 def parameters(self):
1850 return self._parameters
1851
1852 @property
1853 def return_annotation(self):
1854 return self._return_annotation
1855
1856 def replace(self, *, parameters=_void, return_annotation=_void):
1857 '''Creates a customized copy of the Signature.
1858 Pass 'parameters' and/or 'return_annotation' arguments
1859 to override them in the new copy.
1860 '''
1861
1862 if parameters is _void:
1863 parameters = self.parameters.values()
1864
1865 if return_annotation is _void:
1866 return_annotation = self._return_annotation
1867
1868 return type(self)(parameters,
1869 return_annotation=return_annotation)
1870
1871 def __eq__(self, other):
1872 if (not issubclass(type(other), Signature) or
1873 self.return_annotation != other.return_annotation or
1874 len(self.parameters) != len(other.parameters)):
1875 return False
1876
1877 other_positions = {param: idx
1878 for idx, param in enumerate(other.parameters.keys())}
1879
1880 for idx, (param_name, param) in enumerate(self.parameters.items()):
1881 if param.kind == _KEYWORD_ONLY:
1882 try:
1883 other_param = other.parameters[param_name]
1884 except KeyError:
1885 return False
1886 else:
1887 if param != other_param:
1888 return False
1889 else:
1890 try:
1891 other_idx = other_positions[param_name]
1892 except KeyError:
1893 return False
1894 else:
1895 if (idx != other_idx or
1896 param != other.parameters[param_name]):
1897 return False
1898
1899 return True
1900
1901 def __ne__(self, other):
1902 return not self.__eq__(other)
1903
1904 def _bind(self, args, kwargs, *, partial=False):
1905 '''Private method. Don't use directly.'''
1906
1907 arguments = OrderedDict()
1908
1909 parameters = iter(self.parameters.values())
1910 parameters_ex = ()
1911 arg_vals = iter(args)
1912
1913 if partial:
1914 # Support for binding arguments to 'functools.partial' objects.
1915 # See 'functools.partial' case in 'signature()' implementation
1916 # for details.
1917 for param_name, param in self.parameters.items():
1918 if (param._partial_kwarg and param_name not in kwargs):
1919 # Simulating 'functools.partial' behavior
1920 kwargs[param_name] = param.default
1921
1922 while True:
1923 # Let's iterate through the positional arguments and corresponding
1924 # parameters
1925 try:
1926 arg_val = next(arg_vals)
1927 except StopIteration:
1928 # No more positional arguments
1929 try:
1930 param = next(parameters)
1931 except StopIteration:
1932 # No more parameters. That's it. Just need to check that
1933 # we have no `kwargs` after this while loop
1934 break
1935 else:
1936 if param.kind == _VAR_POSITIONAL:
1937 # That's OK, just empty *args. Let's start parsing
1938 # kwargs
1939 break
1940 elif param.name in kwargs:
1941 if param.kind == _POSITIONAL_ONLY:
1942 msg = '{arg!r} parameter is positional only, ' \
1943 'but was passed as a keyword'
1944 msg = msg.format(arg=param.name)
1945 raise TypeError(msg) from None
1946 parameters_ex = (param,)
1947 break
1948 elif (param.kind == _VAR_KEYWORD or
1949 param.default is not _empty):
1950 # That's fine too - we have a default value for this
1951 # parameter. So, lets start parsing `kwargs`, starting
1952 # with the current parameter
1953 parameters_ex = (param,)
1954 break
1955 else:
1956 if partial:
1957 parameters_ex = (param,)
1958 break
1959 else:
1960 msg = '{arg!r} parameter lacking default value'
1961 msg = msg.format(arg=param.name)
1962 raise TypeError(msg) from None
1963 else:
1964 # We have a positional argument to process
1965 try:
1966 param = next(parameters)
1967 except StopIteration:
1968 raise TypeError('too many positional arguments') from None
1969 else:
1970 if param.kind in (_VAR_KEYWORD, _KEYWORD_ONLY):
1971 # Looks like we have no parameter for this positional
1972 # argument
1973 raise TypeError('too many positional arguments')
1974
1975 if param.kind == _VAR_POSITIONAL:
1976 # We have an '*args'-like argument, let's fill it with
1977 # all positional arguments we have left and move on to
1978 # the next phase
1979 values = [arg_val]
1980 values.extend(arg_vals)
1981 arguments[param.name] = tuple(values)
1982 break
1983
1984 if param.name in kwargs:
1985 raise TypeError('multiple values for argument '
1986 '{arg!r}'.format(arg=param.name))
1987
1988 arguments[param.name] = arg_val
1989
1990 # Now, we iterate through the remaining parameters to process
1991 # keyword arguments
1992 kwargs_param = None
1993 for param in itertools.chain(parameters_ex, parameters):
1994 if param.kind == _POSITIONAL_ONLY:
1995 # This should never happen in case of a properly built
1996 # Signature object (but let's have this check here
1997 # to ensure correct behaviour just in case)
1998 raise TypeError('{arg!r} parameter is positional only, '
1999 'but was passed as a keyword'. \
2000 format(arg=param.name))
2001
2002 if param.kind == _VAR_KEYWORD:
2003 # Memorize that we have a '**kwargs'-like parameter
2004 kwargs_param = param
2005 continue
2006
2007 param_name = param.name
2008 try:
2009 arg_val = kwargs.pop(param_name)
2010 except KeyError:
2011 # We have no value for this parameter. It's fine though,
2012 # if it has a default value, or it is an '*args'-like
2013 # parameter, left alone by the processing of positional
2014 # arguments.
2015 if (not partial and param.kind != _VAR_POSITIONAL and
2016 param.default is _empty):
2017 raise TypeError('{arg!r} parameter lacking default value'. \
2018 format(arg=param_name)) from None
2019
2020 else:
2021 arguments[param_name] = arg_val
2022
2023 if kwargs:
2024 if kwargs_param is not None:
2025 # Process our '**kwargs'-like parameter
2026 arguments[kwargs_param.name] = kwargs
2027 else:
2028 raise TypeError('too many keyword arguments')
2029
2030 return self._bound_arguments_cls(self, arguments)
2031
Antoine Pitroubd41d1b2013-01-29 21:20:57 +01002032 def bind(__bind_self, *args, **kwargs):
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002033 '''Get a BoundArguments object, that maps the passed `args`
2034 and `kwargs` to the function's signature. Raises `TypeError`
2035 if the passed arguments can not be bound.
2036 '''
Antoine Pitroubd41d1b2013-01-29 21:20:57 +01002037 return __bind_self._bind(args, kwargs)
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002038
Antoine Pitroubd41d1b2013-01-29 21:20:57 +01002039 def bind_partial(__bind_self, *args, **kwargs):
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002040 '''Get a BoundArguments object, that partially maps the
2041 passed `args` and `kwargs` to the function's signature.
2042 Raises `TypeError` if the passed arguments can not be bound.
2043 '''
Antoine Pitroubd41d1b2013-01-29 21:20:57 +01002044 return __bind_self._bind(args, kwargs, partial=True)
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002045
2046 def __str__(self):
2047 result = []
2048 render_kw_only_separator = True
2049 for idx, param in enumerate(self.parameters.values()):
2050 formatted = str(param)
2051
2052 kind = param.kind
2053 if kind == _VAR_POSITIONAL:
2054 # OK, we have an '*args'-like parameter, so we won't need
2055 # a '*' to separate keyword-only arguments
2056 render_kw_only_separator = False
2057 elif kind == _KEYWORD_ONLY and render_kw_only_separator:
2058 # We have a keyword-only parameter to render and we haven't
2059 # rendered an '*args'-like parameter before, so add a '*'
2060 # separator to the parameters list ("foo(arg1, *, arg2)" case)
2061 result.append('*')
2062 # This condition should be only triggered once, so
2063 # reset the flag
2064 render_kw_only_separator = False
2065
2066 result.append(formatted)
2067
2068 rendered = '({})'.format(', '.join(result))
2069
2070 if self.return_annotation is not _empty:
2071 anno = formatannotation(self.return_annotation)
2072 rendered += ' -> {}'.format(anno)
2073
2074 return rendered