blob: 22b9e845431ac23fdf54aea7fd02a156540802cf [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
51# back to hardcording so the dependency is optional
52try:
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:
188 __iter__ defined to support interation over container
189 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
Brett Cannon4c14b5d2013-05-04 13:56:58 -0400479 if getattr(getmodule(object, filename), '__loader__', None) is not None:
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
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200548 in the file and the line number indexes a line in that list. An OSError
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000549 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:] != '<>':
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200554 raise OSError('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:
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200563 raise OSError('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:
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200589 raise OSError('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'):
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200601 raise OSError('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
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200608 raise OSError('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)
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200617 except (OSError, TypeError):
Jeremy Hyltonb4c17c82002-03-28 23:01:56 +0000618 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
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200713 original source file the first line of code was found. An OSError is
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000714 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
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200725 OSError is raised if the source code cannot be retrieved."""
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000726 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] = []
756 children[parent].append(c)
757 if unique and parent in classes: break
758 elif c not in roots:
759 roots.append(c)
Raymond Hettingere0d49722002-06-02 18:55:56 +0000760 for parent in children:
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000761 if parent not in classes:
762 roots.append(parent)
763 return walktree(roots, children, None)
764
765# ------------------------------------------------ argument list extraction
Christian Heimes25bb7832008-01-11 16:17:00 +0000766Arguments = namedtuple('Arguments', 'args, varargs, varkw')
767
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000768def getargs(co):
769 """Get information about the arguments accepted by a code object.
770
Guido van Rossum2e65f892007-02-28 22:03:49 +0000771 Three things are returned: (args, varargs, varkw), where
Georg Brandlc1c4bf82010-10-15 16:07:41 +0000772 'args' is the list of argument names. Keyword-only arguments are
773 appended. 'varargs' and 'varkw' are the names of the * and **
774 arguments or None."""
Guido van Rossum2e65f892007-02-28 22:03:49 +0000775 args, varargs, kwonlyargs, varkw = _getfullargs(co)
Christian Heimes25bb7832008-01-11 16:17:00 +0000776 return Arguments(args + kwonlyargs, varargs, varkw)
Guido van Rossum2e65f892007-02-28 22:03:49 +0000777
778def _getfullargs(co):
779 """Get information about the arguments accepted by a code object.
780
781 Four things are returned: (args, varargs, kwonlyargs, varkw), where
Georg Brandlc1c4bf82010-10-15 16:07:41 +0000782 'args' and 'kwonlyargs' are lists of argument names, and 'varargs'
783 and 'varkw' are the names of the * and ** arguments or None."""
Jeremy Hylton64967882003-06-27 18:14:39 +0000784
785 if not iscode(co):
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +0000786 raise TypeError('{!r} is not a code object'.format(co))
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000787
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000788 nargs = co.co_argcount
789 names = co.co_varnames
Guido van Rossum2e65f892007-02-28 22:03:49 +0000790 nkwargs = co.co_kwonlyargcount
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000791 args = list(names[:nargs])
Guido van Rossum2e65f892007-02-28 22:03:49 +0000792 kwonlyargs = list(names[nargs:nargs+nkwargs])
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000793 step = 0
794
Guido van Rossum2e65f892007-02-28 22:03:49 +0000795 nargs += nkwargs
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000796 varargs = None
797 if co.co_flags & CO_VARARGS:
798 varargs = co.co_varnames[nargs]
799 nargs = nargs + 1
800 varkw = None
801 if co.co_flags & CO_VARKEYWORDS:
802 varkw = co.co_varnames[nargs]
Guido van Rossum2e65f892007-02-28 22:03:49 +0000803 return args, varargs, kwonlyargs, varkw
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000804
Christian Heimes25bb7832008-01-11 16:17:00 +0000805
806ArgSpec = namedtuple('ArgSpec', 'args varargs keywords defaults')
807
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000808def getargspec(func):
809 """Get the names and default values of a function's arguments.
810
811 A tuple of four things is returned: (args, varargs, varkw, defaults).
Georg Brandlc1c4bf82010-10-15 16:07:41 +0000812 'args' is a list of the argument names.
Guido van Rossum2e65f892007-02-28 22:03:49 +0000813 'args' will include keyword-only argument names.
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000814 'varargs' and 'varkw' are the names of the * and ** arguments or None.
Jeremy Hylton64967882003-06-27 18:14:39 +0000815 'defaults' is an n-tuple of the default values of the last n arguments.
Guido van Rossuma8add0e2007-05-14 22:03:55 +0000816
Guido van Rossum2e65f892007-02-28 22:03:49 +0000817 Use the getfullargspec() API for Python-3000 code, as annotations
818 and keyword arguments are supported. getargspec() will raise ValueError
819 if the func has either annotations or keyword arguments.
820 """
821
822 args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults, ann = \
823 getfullargspec(func)
824 if kwonlyargs or ann:
Collin Winterce36ad82007-08-30 01:19:48 +0000825 raise ValueError("Function has keyword-only arguments or annotations"
826 ", use getfullargspec() API which can support them")
Christian Heimes25bb7832008-01-11 16:17:00 +0000827 return ArgSpec(args, varargs, varkw, defaults)
828
829FullArgSpec = namedtuple('FullArgSpec',
Benjamin Peterson3d4ca742008-11-12 21:39:01 +0000830 'args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults, annotations')
Guido van Rossum2e65f892007-02-28 22:03:49 +0000831
832def getfullargspec(func):
833 """Get the names and default values of a function's arguments.
834
Brett Cannon504d8852007-09-07 02:12:14 +0000835 A tuple of seven things is returned:
836 (args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults annotations).
Georg Brandlc1c4bf82010-10-15 16:07:41 +0000837 'args' is a list of the argument names.
Guido van Rossum2e65f892007-02-28 22:03:49 +0000838 'varargs' and 'varkw' are the names of the * and ** arguments or None.
839 'defaults' is an n-tuple of the default values of the last n arguments.
840 'kwonlyargs' is a list of keyword-only argument names.
841 'kwonlydefaults' is a dictionary mapping names from kwonlyargs to defaults.
842 'annotations' is a dictionary mapping argument names to annotations.
Guido van Rossuma8add0e2007-05-14 22:03:55 +0000843
Guido van Rossum2e65f892007-02-28 22:03:49 +0000844 The first four items in the tuple correspond to getargspec().
Jeremy Hylton64967882003-06-27 18:14:39 +0000845 """
846
847 if ismethod(func):
Christian Heimesff737952007-11-27 10:40:20 +0000848 func = func.__func__
Jeremy Hylton64967882003-06-27 18:14:39 +0000849 if not isfunction(func):
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +0000850 raise TypeError('{!r} is not a Python function'.format(func))
Guido van Rossum2e65f892007-02-28 22:03:49 +0000851 args, varargs, kwonlyargs, varkw = _getfullargs(func.__code__)
Christian Heimes25bb7832008-01-11 16:17:00 +0000852 return FullArgSpec(args, varargs, varkw, func.__defaults__,
Guido van Rossum2e65f892007-02-28 22:03:49 +0000853 kwonlyargs, func.__kwdefaults__, func.__annotations__)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000854
Christian Heimes25bb7832008-01-11 16:17:00 +0000855ArgInfo = namedtuple('ArgInfo', 'args varargs keywords locals')
856
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000857def getargvalues(frame):
858 """Get information about arguments passed into a particular frame.
859
860 A tuple of four things is returned: (args, varargs, varkw, locals).
Georg Brandlc1c4bf82010-10-15 16:07:41 +0000861 'args' is a list of the argument names.
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000862 'varargs' and 'varkw' are the names of the * and ** arguments or None.
863 'locals' is the locals dictionary of the given frame."""
864 args, varargs, varkw = getargs(frame.f_code)
Benjamin Peterson1a6e0d02008-10-25 15:49:17 +0000865 return ArgInfo(args, varargs, varkw, frame.f_locals)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000866
Guido van Rossum2e65f892007-02-28 22:03:49 +0000867def formatannotation(annotation, base_module=None):
868 if isinstance(annotation, type):
Georg Brandl1a3284e2007-12-02 09:40:06 +0000869 if annotation.__module__ in ('builtins', base_module):
Guido van Rossum2e65f892007-02-28 22:03:49 +0000870 return annotation.__name__
871 return annotation.__module__+'.'+annotation.__name__
872 return repr(annotation)
Guido van Rossuma8add0e2007-05-14 22:03:55 +0000873
Guido van Rossum2e65f892007-02-28 22:03:49 +0000874def formatannotationrelativeto(object):
Guido van Rossuma8add0e2007-05-14 22:03:55 +0000875 module = getattr(object, '__module__', None)
876 def _formatannotation(annotation):
877 return formatannotation(annotation, module)
878 return _formatannotation
Guido van Rossum2e65f892007-02-28 22:03:49 +0000879
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000880def formatargspec(args, varargs=None, varkw=None, defaults=None,
Guido van Rossum2e65f892007-02-28 22:03:49 +0000881 kwonlyargs=(), kwonlydefaults={}, annotations={},
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000882 formatarg=str,
883 formatvarargs=lambda name: '*' + name,
884 formatvarkw=lambda name: '**' + name,
885 formatvalue=lambda value: '=' + repr(value),
Guido van Rossum2e65f892007-02-28 22:03:49 +0000886 formatreturns=lambda text: ' -> ' + text,
Georg Brandlc1c4bf82010-10-15 16:07:41 +0000887 formatannotation=formatannotation):
Guido van Rossuma8add0e2007-05-14 22:03:55 +0000888 """Format an argument spec from the values returned by getargspec
Guido van Rossum2e65f892007-02-28 22:03:49 +0000889 or getfullargspec.
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000890
Guido van Rossum2e65f892007-02-28 22:03:49 +0000891 The first seven arguments are (args, varargs, varkw, defaults,
892 kwonlyargs, kwonlydefaults, annotations). The other five arguments
893 are the corresponding optional formatting functions that are called to
894 turn names and values into strings. The last argument is an optional
895 function to format the sequence of arguments."""
896 def formatargandannotation(arg):
897 result = formatarg(arg)
898 if arg in annotations:
899 result += ': ' + formatannotation(annotations[arg])
900 return result
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000901 specs = []
902 if defaults:
903 firstdefault = len(args) - len(defaults)
Benjamin Petersonb58dda72009-01-18 22:27:04 +0000904 for i, arg in enumerate(args):
Georg Brandlc1c4bf82010-10-15 16:07:41 +0000905 spec = formatargandannotation(arg)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000906 if defaults and i >= firstdefault:
907 spec = spec + formatvalue(defaults[i - firstdefault])
908 specs.append(spec)
Raymond Hettinger936654b2002-06-01 03:06:31 +0000909 if varargs is not None:
Guido van Rossum2e65f892007-02-28 22:03:49 +0000910 specs.append(formatvarargs(formatargandannotation(varargs)))
911 else:
912 if kwonlyargs:
913 specs.append('*')
914 if kwonlyargs:
915 for kwonlyarg in kwonlyargs:
916 spec = formatargandannotation(kwonlyarg)
Benjamin Peterson9953a8d2009-01-17 04:15:01 +0000917 if kwonlydefaults and kwonlyarg in kwonlydefaults:
Guido van Rossum2e65f892007-02-28 22:03:49 +0000918 spec += formatvalue(kwonlydefaults[kwonlyarg])
919 specs.append(spec)
Raymond Hettinger936654b2002-06-01 03:06:31 +0000920 if varkw is not None:
Guido van Rossum2e65f892007-02-28 22:03:49 +0000921 specs.append(formatvarkw(formatargandannotation(varkw)))
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000922 result = '(' + ', '.join(specs) + ')'
Guido van Rossum2e65f892007-02-28 22:03:49 +0000923 if 'return' in annotations:
924 result += formatreturns(formatannotation(annotations['return']))
925 return result
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000926
927def formatargvalues(args, varargs, varkw, locals,
928 formatarg=str,
929 formatvarargs=lambda name: '*' + name,
930 formatvarkw=lambda name: '**' + name,
Georg Brandlc1c4bf82010-10-15 16:07:41 +0000931 formatvalue=lambda value: '=' + repr(value)):
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000932 """Format an argument spec from the 4 values returned by getargvalues.
933
934 The first four arguments are (args, varargs, varkw, locals). The
935 next four arguments are the corresponding optional formatting functions
936 that are called to turn names and values into strings. The ninth
937 argument is an optional function to format the sequence of arguments."""
938 def convert(name, locals=locals,
939 formatarg=formatarg, formatvalue=formatvalue):
940 return formatarg(name) + formatvalue(locals[name])
941 specs = []
942 for i in range(len(args)):
Georg Brandlc1c4bf82010-10-15 16:07:41 +0000943 specs.append(convert(args[i]))
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000944 if varargs:
945 specs.append(formatvarargs(varargs) + formatvalue(locals[varargs]))
946 if varkw:
947 specs.append(formatvarkw(varkw) + formatvalue(locals[varkw]))
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000948 return '(' + ', '.join(specs) + ')'
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000949
Benjamin Petersone109c702011-06-24 09:37:26 -0500950def _missing_arguments(f_name, argnames, pos, values):
951 names = [repr(name) for name in argnames if name not in values]
952 missing = len(names)
953 if missing == 1:
954 s = names[0]
955 elif missing == 2:
956 s = "{} and {}".format(*names)
957 else:
958 tail = ", {} and {}".format(names[-2:])
959 del names[-2:]
960 s = ", ".join(names) + tail
961 raise TypeError("%s() missing %i required %s argument%s: %s" %
962 (f_name, missing,
963 "positional" if pos else "keyword-only",
964 "" if missing == 1 else "s", s))
965
966def _too_many(f_name, args, kwonly, varargs, defcount, given, values):
Benjamin Petersonb204a422011-06-05 22:04:07 -0500967 atleast = len(args) - defcount
Benjamin Petersonb204a422011-06-05 22:04:07 -0500968 kwonly_given = len([arg for arg in kwonly if arg in values])
969 if varargs:
970 plural = atleast != 1
971 sig = "at least %d" % (atleast,)
972 elif defcount:
973 plural = True
974 sig = "from %d to %d" % (atleast, len(args))
975 else:
976 plural = len(args) != 1
977 sig = str(len(args))
978 kwonly_sig = ""
979 if kwonly_given:
980 msg = " positional argument%s (and %d keyword-only argument%s)"
981 kwonly_sig = (msg % ("s" if given != 1 else "", kwonly_given,
982 "s" if kwonly_given != 1 else ""))
983 raise TypeError("%s() takes %s positional argument%s but %d%s %s given" %
984 (f_name, sig, "s" if plural else "", given, kwonly_sig,
985 "was" if given == 1 and not kwonly_given else "were"))
986
Benjamin Peterson25cd7eb2010-03-30 18:42:32 +0000987def getcallargs(func, *positional, **named):
988 """Get the mapping of arguments to values.
989
990 A dict is returned, with keys the function argument names (including the
991 names of the * and ** arguments, if any), and values the respective bound
992 values from 'positional' and 'named'."""
993 spec = getfullargspec(func)
994 args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults, ann = spec
995 f_name = func.__name__
996 arg2value = {}
997
Benjamin Petersonb204a422011-06-05 22:04:07 -0500998
Benjamin Peterson25cd7eb2010-03-30 18:42:32 +0000999 if ismethod(func) and func.__self__ is not None:
1000 # implicit 'self' (or 'cls' for classmethods) argument
1001 positional = (func.__self__,) + positional
1002 num_pos = len(positional)
Benjamin Peterson25cd7eb2010-03-30 18:42:32 +00001003 num_args = len(args)
1004 num_defaults = len(defaults) if defaults else 0
Benjamin Peterson25cd7eb2010-03-30 18:42:32 +00001005
Benjamin Petersonb204a422011-06-05 22:04:07 -05001006 n = min(num_pos, num_args)
1007 for i in range(n):
1008 arg2value[args[i]] = positional[i]
1009 if varargs:
1010 arg2value[varargs] = tuple(positional[n:])
1011 possible_kwargs = set(args + kwonlyargs)
Benjamin Peterson25cd7eb2010-03-30 18:42:32 +00001012 if varkw:
Benjamin Petersonb204a422011-06-05 22:04:07 -05001013 arg2value[varkw] = {}
1014 for kw, value in named.items():
1015 if kw not in possible_kwargs:
1016 if not varkw:
1017 raise TypeError("%s() got an unexpected keyword argument %r" %
1018 (f_name, kw))
1019 arg2value[varkw][kw] = value
1020 continue
1021 if kw in arg2value:
1022 raise TypeError("%s() got multiple values for argument %r" %
1023 (f_name, kw))
1024 arg2value[kw] = value
1025 if num_pos > num_args and not varargs:
Benjamin Petersone109c702011-06-24 09:37:26 -05001026 _too_many(f_name, args, kwonlyargs, varargs, num_defaults,
1027 num_pos, arg2value)
Benjamin Petersonb204a422011-06-05 22:04:07 -05001028 if num_pos < num_args:
Benjamin Petersone109c702011-06-24 09:37:26 -05001029 req = args[:num_args - num_defaults]
1030 for arg in req:
Benjamin Petersonb204a422011-06-05 22:04:07 -05001031 if arg not in arg2value:
Benjamin Petersone109c702011-06-24 09:37:26 -05001032 _missing_arguments(f_name, req, True, arg2value)
Benjamin Petersonb204a422011-06-05 22:04:07 -05001033 for i, arg in enumerate(args[num_args - num_defaults:]):
1034 if arg not in arg2value:
1035 arg2value[arg] = defaults[i]
Benjamin Petersone109c702011-06-24 09:37:26 -05001036 missing = 0
Benjamin Petersonb204a422011-06-05 22:04:07 -05001037 for kwarg in kwonlyargs:
1038 if kwarg not in arg2value:
Benjamin Petersone109c702011-06-24 09:37:26 -05001039 if kwarg in kwonlydefaults:
1040 arg2value[kwarg] = kwonlydefaults[kwarg]
1041 else:
1042 missing += 1
1043 if missing:
1044 _missing_arguments(f_name, kwonlyargs, False, arg2value)
Benjamin Peterson25cd7eb2010-03-30 18:42:32 +00001045 return arg2value
1046
Nick Coghlan2f92e542012-06-23 19:39:55 +10001047ClosureVars = namedtuple('ClosureVars', 'nonlocals globals builtins unbound')
1048
1049def getclosurevars(func):
1050 """
1051 Get the mapping of free variables to their current values.
1052
Meador Inge8fda3592012-07-19 21:33:21 -05001053 Returns a named tuple of dicts mapping the current nonlocal, global
Nick Coghlan2f92e542012-06-23 19:39:55 +10001054 and builtin references as seen by the body of the function. A final
1055 set of unbound names that could not be resolved is also provided.
1056 """
1057
1058 if ismethod(func):
1059 func = func.__func__
1060
1061 if not isfunction(func):
1062 raise TypeError("'{!r}' is not a Python function".format(func))
1063
1064 code = func.__code__
1065 # Nonlocal references are named in co_freevars and resolved
1066 # by looking them up in __closure__ by positional index
1067 if func.__closure__ is None:
1068 nonlocal_vars = {}
1069 else:
1070 nonlocal_vars = {
1071 var : cell.cell_contents
1072 for var, cell in zip(code.co_freevars, func.__closure__)
1073 }
1074
1075 # Global and builtin references are named in co_names and resolved
1076 # by looking them up in __globals__ or __builtins__
1077 global_ns = func.__globals__
1078 builtin_ns = global_ns.get("__builtins__", builtins.__dict__)
1079 if ismodule(builtin_ns):
1080 builtin_ns = builtin_ns.__dict__
1081 global_vars = {}
1082 builtin_vars = {}
1083 unbound_names = set()
1084 for name in code.co_names:
1085 if name in ("None", "True", "False"):
1086 # Because these used to be builtins instead of keywords, they
1087 # may still show up as name references. We ignore them.
1088 continue
1089 try:
1090 global_vars[name] = global_ns[name]
1091 except KeyError:
1092 try:
1093 builtin_vars[name] = builtin_ns[name]
1094 except KeyError:
1095 unbound_names.add(name)
1096
1097 return ClosureVars(nonlocal_vars, global_vars,
1098 builtin_vars, unbound_names)
1099
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001100# -------------------------------------------------- stack frame extraction
Christian Heimes25bb7832008-01-11 16:17:00 +00001101
1102Traceback = namedtuple('Traceback', 'filename lineno function code_context index')
1103
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001104def getframeinfo(frame, context=1):
1105 """Get information about a frame or traceback object.
1106
1107 A tuple of five things is returned: the filename, the line number of
1108 the current line, the function name, a list of lines of context from
1109 the source code, and the index of the current line within that list.
1110 The optional second argument specifies the number of lines of context
1111 to return, which are centered around the current line."""
1112 if istraceback(frame):
Andrew M. Kuchlingba8b6bc2004-06-05 14:11:59 +00001113 lineno = frame.tb_lineno
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001114 frame = frame.tb_frame
Andrew M. Kuchlingba8b6bc2004-06-05 14:11:59 +00001115 else:
1116 lineno = frame.f_lineno
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001117 if not isframe(frame):
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00001118 raise TypeError('{!r} is not a frame or traceback object'.format(frame))
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001119
Neil Schemenauerf06f8532002-03-23 23:51:04 +00001120 filename = getsourcefile(frame) or getfile(frame)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001121 if context > 0:
Guido van Rossum54e54c62001-09-04 19:14:14 +00001122 start = lineno - 1 - context//2
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001123 try:
1124 lines, lnum = findsource(frame)
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02001125 except OSError:
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +00001126 lines = index = None
1127 else:
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001128 start = max(start, 1)
Raymond Hettingera0501712004-06-15 11:22:53 +00001129 start = max(0, min(start, len(lines) - context))
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001130 lines = lines[start:start+context]
Ka-Ping Yee59ade082001-03-01 03:55:35 +00001131 index = lineno - 1 - start
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001132 else:
1133 lines = index = None
1134
Christian Heimes25bb7832008-01-11 16:17:00 +00001135 return Traceback(filename, lineno, frame.f_code.co_name, lines, index)
Ka-Ping Yee59ade082001-03-01 03:55:35 +00001136
1137def getlineno(frame):
1138 """Get the line number from a frame object, allowing for optimization."""
Michael W. Hudsondd32a912002-08-15 14:59:02 +00001139 # FrameType.f_lineno is now a descriptor that grovels co_lnotab
1140 return frame.f_lineno
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001141
1142def getouterframes(frame, context=1):
1143 """Get a list of records for a frame and all higher (calling) frames.
1144
1145 Each record contains a frame object, filename, line number, function
1146 name, a list of lines of context, and index within the context."""
1147 framelist = []
1148 while frame:
1149 framelist.append((frame,) + getframeinfo(frame, context))
1150 frame = frame.f_back
1151 return framelist
1152
1153def getinnerframes(tb, context=1):
1154 """Get a list of records for a traceback's frame and all lower frames.
1155
1156 Each record contains a frame object, filename, line number, function
1157 name, a list of lines of context, and index within the context."""
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001158 framelist = []
1159 while tb:
1160 framelist.append((tb.tb_frame,) + getframeinfo(tb, context))
1161 tb = tb.tb_next
1162 return framelist
1163
Benjamin Peterson42ac4752010-08-09 13:05:35 +00001164def currentframe():
Benjamin Petersona3a3fc62010-08-09 15:49:56 +00001165 """Return the frame of the caller or None if this is not possible."""
Benjamin Peterson42ac4752010-08-09 13:05:35 +00001166 return sys._getframe(1) if hasattr(sys, "_getframe") else None
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001167
1168def stack(context=1):
1169 """Return a list of records for the stack above the caller's frame."""
Jeremy Hyltonab919022003-06-27 18:41:20 +00001170 return getouterframes(sys._getframe(1), context)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001171
1172def trace(context=1):
Tim Peters85ba6732001-02-28 08:26:44 +00001173 """Return a list of records for the stack below the current exception."""
Fred Draked451ec12002-04-26 02:29:55 +00001174 return getinnerframes(sys.exc_info()[2], context)
Michael Foord95fc51d2010-11-20 15:07:30 +00001175
1176
1177# ------------------------------------------------ static version of getattr
1178
1179_sentinel = object()
1180
Michael Foorde5162652010-11-20 16:40:44 +00001181def _static_getmro(klass):
1182 return type.__dict__['__mro__'].__get__(klass)
1183
Michael Foord95fc51d2010-11-20 15:07:30 +00001184def _check_instance(obj, attr):
1185 instance_dict = {}
1186 try:
1187 instance_dict = object.__getattribute__(obj, "__dict__")
1188 except AttributeError:
1189 pass
Michael Foorddcebe0f2011-03-15 19:20:44 -04001190 return dict.get(instance_dict, attr, _sentinel)
Michael Foord95fc51d2010-11-20 15:07:30 +00001191
1192
1193def _check_class(klass, attr):
Michael Foorde5162652010-11-20 16:40:44 +00001194 for entry in _static_getmro(klass):
Michael Foorda51623b2011-12-18 22:01:40 +00001195 if _shadowed_dict(type(entry)) is _sentinel:
Michael Foorddcebe0f2011-03-15 19:20:44 -04001196 try:
1197 return entry.__dict__[attr]
1198 except KeyError:
1199 pass
Michael Foord95fc51d2010-11-20 15:07:30 +00001200 return _sentinel
1201
Michael Foord35184ed2010-11-20 16:58:30 +00001202def _is_type(obj):
1203 try:
1204 _static_getmro(obj)
1205 except TypeError:
1206 return False
1207 return True
1208
Michael Foorddcebe0f2011-03-15 19:20:44 -04001209def _shadowed_dict(klass):
1210 dict_attr = type.__dict__["__dict__"]
1211 for entry in _static_getmro(klass):
1212 try:
1213 class_dict = dict_attr.__get__(entry)["__dict__"]
1214 except KeyError:
1215 pass
1216 else:
1217 if not (type(class_dict) is types.GetSetDescriptorType and
1218 class_dict.__name__ == "__dict__" and
1219 class_dict.__objclass__ is entry):
Michael Foorda51623b2011-12-18 22:01:40 +00001220 return class_dict
1221 return _sentinel
Michael Foord95fc51d2010-11-20 15:07:30 +00001222
1223def getattr_static(obj, attr, default=_sentinel):
1224 """Retrieve attributes without triggering dynamic lookup via the
1225 descriptor protocol, __getattr__ or __getattribute__.
1226
1227 Note: this function may not be able to retrieve all attributes
1228 that getattr can fetch (like dynamically created attributes)
1229 and may find attributes that getattr can't (like descriptors
1230 that raise AttributeError). It can also return descriptor objects
1231 instead of instance members in some cases. See the
1232 documentation for details.
1233 """
1234 instance_result = _sentinel
Michael Foord35184ed2010-11-20 16:58:30 +00001235 if not _is_type(obj):
Michael Foordcc7ebb82010-11-20 16:20:16 +00001236 klass = type(obj)
Michael Foorda51623b2011-12-18 22:01:40 +00001237 dict_attr = _shadowed_dict(klass)
1238 if (dict_attr is _sentinel or
1239 type(dict_attr) is types.MemberDescriptorType):
Michael Foorddcebe0f2011-03-15 19:20:44 -04001240 instance_result = _check_instance(obj, attr)
Michael Foord95fc51d2010-11-20 15:07:30 +00001241 else:
1242 klass = obj
1243
1244 klass_result = _check_class(klass, attr)
1245
1246 if instance_result is not _sentinel and klass_result is not _sentinel:
1247 if (_check_class(type(klass_result), '__get__') is not _sentinel and
1248 _check_class(type(klass_result), '__set__') is not _sentinel):
1249 return klass_result
1250
1251 if instance_result is not _sentinel:
1252 return instance_result
1253 if klass_result is not _sentinel:
1254 return klass_result
1255
1256 if obj is klass:
1257 # for types we check the metaclass too
Michael Foorde5162652010-11-20 16:40:44 +00001258 for entry in _static_getmro(type(klass)):
Michael Foord3ba95f82011-12-22 01:13:37 +00001259 if _shadowed_dict(type(entry)) is _sentinel:
1260 try:
1261 return entry.__dict__[attr]
1262 except KeyError:
1263 pass
Michael Foord95fc51d2010-11-20 15:07:30 +00001264 if default is not _sentinel:
1265 return default
1266 raise AttributeError(attr)
Nick Coghlane0f04652010-11-21 03:44:04 +00001267
1268
Nick Coghlan04e2e3f2012-06-23 19:52:05 +10001269# ------------------------------------------------ generator introspection
1270
Nick Coghlan7921b9f2010-11-30 06:36:04 +00001271GEN_CREATED = 'GEN_CREATED'
1272GEN_RUNNING = 'GEN_RUNNING'
1273GEN_SUSPENDED = 'GEN_SUSPENDED'
1274GEN_CLOSED = 'GEN_CLOSED'
Nick Coghlane0f04652010-11-21 03:44:04 +00001275
1276def getgeneratorstate(generator):
1277 """Get current state of a generator-iterator.
1278
1279 Possible states are:
1280 GEN_CREATED: Waiting to start execution.
1281 GEN_RUNNING: Currently being executed by the interpreter.
1282 GEN_SUSPENDED: Currently suspended at a yield expression.
1283 GEN_CLOSED: Execution has completed.
1284 """
1285 if generator.gi_running:
1286 return GEN_RUNNING
1287 if generator.gi_frame is None:
1288 return GEN_CLOSED
1289 if generator.gi_frame.f_lasti == -1:
1290 return GEN_CREATED
1291 return GEN_SUSPENDED
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07001292
1293
Nick Coghlan04e2e3f2012-06-23 19:52:05 +10001294def getgeneratorlocals(generator):
1295 """
1296 Get the mapping of generator local variables to their current values.
1297
1298 A dict is returned, with the keys the local variable names and values the
1299 bound values."""
1300
1301 if not isgenerator(generator):
1302 raise TypeError("'{!r}' is not a Python generator".format(generator))
1303
1304 frame = getattr(generator, "gi_frame", None)
1305 if frame is not None:
1306 return generator.gi_frame.f_locals
1307 else:
1308 return {}
1309
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07001310###############################################################################
1311### Function Signature Object (PEP 362)
1312###############################################################################
1313
1314
1315_WrapperDescriptor = type(type.__call__)
1316_MethodWrapper = type(all.__call__)
1317
1318_NonUserDefinedCallables = (_WrapperDescriptor,
1319 _MethodWrapper,
1320 types.BuiltinFunctionType)
1321
1322
1323def _get_user_defined_method(cls, method_name):
1324 try:
1325 meth = getattr(cls, method_name)
1326 except AttributeError:
1327 return
1328 else:
1329 if not isinstance(meth, _NonUserDefinedCallables):
1330 # Once '__signature__' will be added to 'C'-level
1331 # callables, this check won't be necessary
1332 return meth
1333
1334
1335def signature(obj):
1336 '''Get a signature object for the passed callable.'''
1337
1338 if not callable(obj):
1339 raise TypeError('{!r} is not a callable object'.format(obj))
1340
1341 if isinstance(obj, types.MethodType):
1342 # In this case we skip the first parameter of the underlying
1343 # function (usually `self` or `cls`).
1344 sig = signature(obj.__func__)
1345 return sig.replace(parameters=tuple(sig.parameters.values())[1:])
1346
1347 try:
1348 sig = obj.__signature__
1349 except AttributeError:
1350 pass
1351 else:
1352 if sig is not None:
1353 return sig
1354
1355 try:
1356 # Was this function wrapped by a decorator?
1357 wrapped = obj.__wrapped__
1358 except AttributeError:
1359 pass
1360 else:
1361 return signature(wrapped)
1362
1363 if isinstance(obj, types.FunctionType):
1364 return Signature.from_function(obj)
1365
1366 if isinstance(obj, functools.partial):
1367 sig = signature(obj.func)
1368
1369 new_params = OrderedDict(sig.parameters.items())
1370
1371 partial_args = obj.args or ()
1372 partial_keywords = obj.keywords or {}
1373 try:
1374 ba = sig.bind_partial(*partial_args, **partial_keywords)
1375 except TypeError as ex:
1376 msg = 'partial object {!r} has incorrect arguments'.format(obj)
1377 raise ValueError(msg) from ex
1378
1379 for arg_name, arg_value in ba.arguments.items():
1380 param = new_params[arg_name]
1381 if arg_name in partial_keywords:
1382 # We set a new default value, because the following code
1383 # is correct:
1384 #
1385 # >>> def foo(a): print(a)
1386 # >>> print(partial(partial(foo, a=10), a=20)())
1387 # 20
1388 # >>> print(partial(partial(foo, a=10), a=20)(a=30))
1389 # 30
1390 #
1391 # So, with 'partial' objects, passing a keyword argument is
1392 # like setting a new default value for the corresponding
1393 # parameter
1394 #
1395 # We also mark this parameter with '_partial_kwarg'
1396 # flag. Later, in '_bind', the 'default' value of this
1397 # parameter will be added to 'kwargs', to simulate
1398 # the 'functools.partial' real call.
1399 new_params[arg_name] = param.replace(default=arg_value,
1400 _partial_kwarg=True)
1401
1402 elif (param.kind not in (_VAR_KEYWORD, _VAR_POSITIONAL) and
1403 not param._partial_kwarg):
1404 new_params.pop(arg_name)
1405
1406 return sig.replace(parameters=new_params.values())
1407
1408 sig = None
1409 if isinstance(obj, type):
1410 # obj is a class or a metaclass
1411
1412 # First, let's see if it has an overloaded __call__ defined
1413 # in its metaclass
1414 call = _get_user_defined_method(type(obj), '__call__')
1415 if call is not None:
1416 sig = signature(call)
1417 else:
1418 # Now we check if the 'obj' class has a '__new__' method
1419 new = _get_user_defined_method(obj, '__new__')
1420 if new is not None:
1421 sig = signature(new)
1422 else:
1423 # Finally, we should have at least __init__ implemented
1424 init = _get_user_defined_method(obj, '__init__')
1425 if init is not None:
1426 sig = signature(init)
1427 elif not isinstance(obj, _NonUserDefinedCallables):
1428 # An object with __call__
1429 # We also check that the 'obj' is not an instance of
1430 # _WrapperDescriptor or _MethodWrapper to avoid
1431 # infinite recursion (and even potential segfault)
1432 call = _get_user_defined_method(type(obj), '__call__')
1433 if call is not None:
1434 sig = signature(call)
1435
1436 if sig is not None:
1437 # For classes and objects we skip the first parameter of their
1438 # __call__, __new__, or __init__ methods
1439 return sig.replace(parameters=tuple(sig.parameters.values())[1:])
1440
1441 if isinstance(obj, types.BuiltinFunctionType):
1442 # Raise a nicer error message for builtins
1443 msg = 'no signature found for builtin function {!r}'.format(obj)
1444 raise ValueError(msg)
1445
1446 raise ValueError('callable {!r} is not supported by signature'.format(obj))
1447
1448
1449class _void:
1450 '''A private marker - used in Parameter & Signature'''
1451
1452
1453class _empty:
1454 pass
1455
1456
1457class _ParameterKind(int):
1458 def __new__(self, *args, name):
1459 obj = int.__new__(self, *args)
1460 obj._name = name
1461 return obj
1462
1463 def __str__(self):
1464 return self._name
1465
1466 def __repr__(self):
1467 return '<_ParameterKind: {!r}>'.format(self._name)
1468
1469
1470_POSITIONAL_ONLY = _ParameterKind(0, name='POSITIONAL_ONLY')
1471_POSITIONAL_OR_KEYWORD = _ParameterKind(1, name='POSITIONAL_OR_KEYWORD')
1472_VAR_POSITIONAL = _ParameterKind(2, name='VAR_POSITIONAL')
1473_KEYWORD_ONLY = _ParameterKind(3, name='KEYWORD_ONLY')
1474_VAR_KEYWORD = _ParameterKind(4, name='VAR_KEYWORD')
1475
1476
1477class Parameter:
1478 '''Represents a parameter in a function signature.
1479
1480 Has the following public attributes:
1481
1482 * name : str
1483 The name of the parameter as a string.
1484 * default : object
1485 The default value for the parameter if specified. If the
1486 parameter has no default value, this attribute is not set.
1487 * annotation
1488 The annotation for the parameter if specified. If the
1489 parameter has no annotation, this attribute is not set.
1490 * kind : str
1491 Describes how argument values are bound to the parameter.
1492 Possible values: `Parameter.POSITIONAL_ONLY`,
1493 `Parameter.POSITIONAL_OR_KEYWORD`, `Parameter.VAR_POSITIONAL`,
1494 `Parameter.KEYWORD_ONLY`, `Parameter.VAR_KEYWORD`.
1495 '''
1496
1497 __slots__ = ('_name', '_kind', '_default', '_annotation', '_partial_kwarg')
1498
1499 POSITIONAL_ONLY = _POSITIONAL_ONLY
1500 POSITIONAL_OR_KEYWORD = _POSITIONAL_OR_KEYWORD
1501 VAR_POSITIONAL = _VAR_POSITIONAL
1502 KEYWORD_ONLY = _KEYWORD_ONLY
1503 VAR_KEYWORD = _VAR_KEYWORD
1504
1505 empty = _empty
1506
1507 def __init__(self, name, kind, *, default=_empty, annotation=_empty,
1508 _partial_kwarg=False):
1509
1510 if kind not in (_POSITIONAL_ONLY, _POSITIONAL_OR_KEYWORD,
1511 _VAR_POSITIONAL, _KEYWORD_ONLY, _VAR_KEYWORD):
1512 raise ValueError("invalid value for 'Parameter.kind' attribute")
1513 self._kind = kind
1514
1515 if default is not _empty:
1516 if kind in (_VAR_POSITIONAL, _VAR_KEYWORD):
1517 msg = '{} parameters cannot have default values'.format(kind)
1518 raise ValueError(msg)
1519 self._default = default
1520 self._annotation = annotation
1521
1522 if name is None:
1523 if kind != _POSITIONAL_ONLY:
1524 raise ValueError("None is not a valid name for a "
1525 "non-positional-only parameter")
1526 self._name = name
1527 else:
1528 name = str(name)
1529 if kind != _POSITIONAL_ONLY and not name.isidentifier():
1530 msg = '{!r} is not a valid parameter name'.format(name)
1531 raise ValueError(msg)
1532 self._name = name
1533
1534 self._partial_kwarg = _partial_kwarg
1535
1536 @property
1537 def name(self):
1538 return self._name
1539
1540 @property
1541 def default(self):
1542 return self._default
1543
1544 @property
1545 def annotation(self):
1546 return self._annotation
1547
1548 @property
1549 def kind(self):
1550 return self._kind
1551
1552 def replace(self, *, name=_void, kind=_void, annotation=_void,
1553 default=_void, _partial_kwarg=_void):
1554 '''Creates a customized copy of the Parameter.'''
1555
1556 if name is _void:
1557 name = self._name
1558
1559 if kind is _void:
1560 kind = self._kind
1561
1562 if annotation is _void:
1563 annotation = self._annotation
1564
1565 if default is _void:
1566 default = self._default
1567
1568 if _partial_kwarg is _void:
1569 _partial_kwarg = self._partial_kwarg
1570
1571 return type(self)(name, kind, default=default, annotation=annotation,
1572 _partial_kwarg=_partial_kwarg)
1573
1574 def __str__(self):
1575 kind = self.kind
1576
1577 formatted = self._name
1578 if kind == _POSITIONAL_ONLY:
1579 if formatted is None:
1580 formatted = ''
1581 formatted = '<{}>'.format(formatted)
1582
1583 # Add annotation and default value
1584 if self._annotation is not _empty:
1585 formatted = '{}:{}'.format(formatted,
1586 formatannotation(self._annotation))
1587
1588 if self._default is not _empty:
1589 formatted = '{}={}'.format(formatted, repr(self._default))
1590
1591 if kind == _VAR_POSITIONAL:
1592 formatted = '*' + formatted
1593 elif kind == _VAR_KEYWORD:
1594 formatted = '**' + formatted
1595
1596 return formatted
1597
1598 def __repr__(self):
1599 return '<{} at {:#x} {!r}>'.format(self.__class__.__name__,
1600 id(self), self.name)
1601
1602 def __eq__(self, other):
1603 return (issubclass(other.__class__, Parameter) and
1604 self._name == other._name and
1605 self._kind == other._kind and
1606 self._default == other._default and
1607 self._annotation == other._annotation)
1608
1609 def __ne__(self, other):
1610 return not self.__eq__(other)
1611
1612
1613class BoundArguments:
1614 '''Result of `Signature.bind` call. Holds the mapping of arguments
1615 to the function's parameters.
1616
1617 Has the following public attributes:
1618
1619 * arguments : OrderedDict
1620 An ordered mutable mapping of parameters' names to arguments' values.
1621 Does not contain arguments' default values.
1622 * signature : Signature
1623 The Signature object that created this instance.
1624 * args : tuple
1625 Tuple of positional arguments values.
1626 * kwargs : dict
1627 Dict of keyword arguments values.
1628 '''
1629
1630 def __init__(self, signature, arguments):
1631 self.arguments = arguments
1632 self._signature = signature
1633
1634 @property
1635 def signature(self):
1636 return self._signature
1637
1638 @property
1639 def args(self):
1640 args = []
1641 for param_name, param in self._signature.parameters.items():
1642 if (param.kind in (_VAR_KEYWORD, _KEYWORD_ONLY) or
1643 param._partial_kwarg):
1644 # Keyword arguments mapped by 'functools.partial'
1645 # (Parameter._partial_kwarg is True) are mapped
1646 # in 'BoundArguments.kwargs', along with VAR_KEYWORD &
1647 # KEYWORD_ONLY
1648 break
1649
1650 try:
1651 arg = self.arguments[param_name]
1652 except KeyError:
1653 # We're done here. Other arguments
1654 # will be mapped in 'BoundArguments.kwargs'
1655 break
1656 else:
1657 if param.kind == _VAR_POSITIONAL:
1658 # *args
1659 args.extend(arg)
1660 else:
1661 # plain argument
1662 args.append(arg)
1663
1664 return tuple(args)
1665
1666 @property
1667 def kwargs(self):
1668 kwargs = {}
1669 kwargs_started = False
1670 for param_name, param in self._signature.parameters.items():
1671 if not kwargs_started:
1672 if (param.kind in (_VAR_KEYWORD, _KEYWORD_ONLY) or
1673 param._partial_kwarg):
1674 kwargs_started = True
1675 else:
1676 if param_name not in self.arguments:
1677 kwargs_started = True
1678 continue
1679
1680 if not kwargs_started:
1681 continue
1682
1683 try:
1684 arg = self.arguments[param_name]
1685 except KeyError:
1686 pass
1687 else:
1688 if param.kind == _VAR_KEYWORD:
1689 # **kwargs
1690 kwargs.update(arg)
1691 else:
1692 # plain keyword argument
1693 kwargs[param_name] = arg
1694
1695 return kwargs
1696
1697 def __eq__(self, other):
1698 return (issubclass(other.__class__, BoundArguments) and
1699 self.signature == other.signature and
1700 self.arguments == other.arguments)
1701
1702 def __ne__(self, other):
1703 return not self.__eq__(other)
1704
1705
1706class Signature:
1707 '''A Signature object represents the overall signature of a function.
1708 It stores a Parameter object for each parameter accepted by the
1709 function, as well as information specific to the function itself.
1710
1711 A Signature object has the following public attributes and methods:
1712
1713 * parameters : OrderedDict
1714 An ordered mapping of parameters' names to the corresponding
1715 Parameter objects (keyword-only arguments are in the same order
1716 as listed in `code.co_varnames`).
1717 * return_annotation : object
1718 The annotation for the return type of the function if specified.
1719 If the function has no annotation for its return type, this
1720 attribute is not set.
1721 * bind(*args, **kwargs) -> BoundArguments
1722 Creates a mapping from positional and keyword arguments to
1723 parameters.
1724 * bind_partial(*args, **kwargs) -> BoundArguments
1725 Creates a partial mapping from positional and keyword arguments
1726 to parameters (simulating 'functools.partial' behavior.)
1727 '''
1728
1729 __slots__ = ('_return_annotation', '_parameters')
1730
1731 _parameter_cls = Parameter
1732 _bound_arguments_cls = BoundArguments
1733
1734 empty = _empty
1735
1736 def __init__(self, parameters=None, *, return_annotation=_empty,
1737 __validate_parameters__=True):
1738 '''Constructs Signature from the given list of Parameter
1739 objects and 'return_annotation'. All arguments are optional.
1740 '''
1741
1742 if parameters is None:
1743 params = OrderedDict()
1744 else:
1745 if __validate_parameters__:
1746 params = OrderedDict()
1747 top_kind = _POSITIONAL_ONLY
1748
1749 for idx, param in enumerate(parameters):
1750 kind = param.kind
1751 if kind < top_kind:
1752 msg = 'wrong parameter order: {} before {}'
1753 msg = msg.format(top_kind, param.kind)
1754 raise ValueError(msg)
1755 else:
1756 top_kind = kind
1757
1758 name = param.name
1759 if name is None:
1760 name = str(idx)
1761 param = param.replace(name=name)
1762
1763 if name in params:
1764 msg = 'duplicate parameter name: {!r}'.format(name)
1765 raise ValueError(msg)
1766 params[name] = param
1767 else:
1768 params = OrderedDict(((param.name, param)
1769 for param in parameters))
1770
1771 self._parameters = types.MappingProxyType(params)
1772 self._return_annotation = return_annotation
1773
1774 @classmethod
1775 def from_function(cls, func):
1776 '''Constructs Signature for the given python function'''
1777
1778 if not isinstance(func, types.FunctionType):
1779 raise TypeError('{!r} is not a Python function'.format(func))
1780
1781 Parameter = cls._parameter_cls
1782
1783 # Parameter information.
1784 func_code = func.__code__
1785 pos_count = func_code.co_argcount
1786 arg_names = func_code.co_varnames
1787 positional = tuple(arg_names[:pos_count])
1788 keyword_only_count = func_code.co_kwonlyargcount
1789 keyword_only = arg_names[pos_count:(pos_count + keyword_only_count)]
1790 annotations = func.__annotations__
1791 defaults = func.__defaults__
1792 kwdefaults = func.__kwdefaults__
1793
1794 if defaults:
1795 pos_default_count = len(defaults)
1796 else:
1797 pos_default_count = 0
1798
1799 parameters = []
1800
1801 # Non-keyword-only parameters w/o defaults.
1802 non_default_count = pos_count - pos_default_count
1803 for name in positional[:non_default_count]:
1804 annotation = annotations.get(name, _empty)
1805 parameters.append(Parameter(name, annotation=annotation,
1806 kind=_POSITIONAL_OR_KEYWORD))
1807
1808 # ... w/ defaults.
1809 for offset, name in enumerate(positional[non_default_count:]):
1810 annotation = annotations.get(name, _empty)
1811 parameters.append(Parameter(name, annotation=annotation,
1812 kind=_POSITIONAL_OR_KEYWORD,
1813 default=defaults[offset]))
1814
1815 # *args
1816 if func_code.co_flags & 0x04:
1817 name = arg_names[pos_count + keyword_only_count]
1818 annotation = annotations.get(name, _empty)
1819 parameters.append(Parameter(name, annotation=annotation,
1820 kind=_VAR_POSITIONAL))
1821
1822 # Keyword-only parameters.
1823 for name in keyword_only:
1824 default = _empty
1825 if kwdefaults is not None:
1826 default = kwdefaults.get(name, _empty)
1827
1828 annotation = annotations.get(name, _empty)
1829 parameters.append(Parameter(name, annotation=annotation,
1830 kind=_KEYWORD_ONLY,
1831 default=default))
1832 # **kwargs
1833 if func_code.co_flags & 0x08:
1834 index = pos_count + keyword_only_count
1835 if func_code.co_flags & 0x04:
1836 index += 1
1837
1838 name = arg_names[index]
1839 annotation = annotations.get(name, _empty)
1840 parameters.append(Parameter(name, annotation=annotation,
1841 kind=_VAR_KEYWORD))
1842
1843 return cls(parameters,
1844 return_annotation=annotations.get('return', _empty),
1845 __validate_parameters__=False)
1846
1847 @property
1848 def parameters(self):
1849 return self._parameters
1850
1851 @property
1852 def return_annotation(self):
1853 return self._return_annotation
1854
1855 def replace(self, *, parameters=_void, return_annotation=_void):
1856 '''Creates a customized copy of the Signature.
1857 Pass 'parameters' and/or 'return_annotation' arguments
1858 to override them in the new copy.
1859 '''
1860
1861 if parameters is _void:
1862 parameters = self.parameters.values()
1863
1864 if return_annotation is _void:
1865 return_annotation = self._return_annotation
1866
1867 return type(self)(parameters,
1868 return_annotation=return_annotation)
1869
1870 def __eq__(self, other):
1871 if (not issubclass(type(other), Signature) or
1872 self.return_annotation != other.return_annotation or
1873 len(self.parameters) != len(other.parameters)):
1874 return False
1875
1876 other_positions = {param: idx
1877 for idx, param in enumerate(other.parameters.keys())}
1878
1879 for idx, (param_name, param) in enumerate(self.parameters.items()):
1880 if param.kind == _KEYWORD_ONLY:
1881 try:
1882 other_param = other.parameters[param_name]
1883 except KeyError:
1884 return False
1885 else:
1886 if param != other_param:
1887 return False
1888 else:
1889 try:
1890 other_idx = other_positions[param_name]
1891 except KeyError:
1892 return False
1893 else:
1894 if (idx != other_idx or
1895 param != other.parameters[param_name]):
1896 return False
1897
1898 return True
1899
1900 def __ne__(self, other):
1901 return not self.__eq__(other)
1902
1903 def _bind(self, args, kwargs, *, partial=False):
1904 '''Private method. Don't use directly.'''
1905
1906 arguments = OrderedDict()
1907
1908 parameters = iter(self.parameters.values())
1909 parameters_ex = ()
1910 arg_vals = iter(args)
1911
1912 if partial:
1913 # Support for binding arguments to 'functools.partial' objects.
1914 # See 'functools.partial' case in 'signature()' implementation
1915 # for details.
1916 for param_name, param in self.parameters.items():
1917 if (param._partial_kwarg and param_name not in kwargs):
1918 # Simulating 'functools.partial' behavior
1919 kwargs[param_name] = param.default
1920
1921 while True:
1922 # Let's iterate through the positional arguments and corresponding
1923 # parameters
1924 try:
1925 arg_val = next(arg_vals)
1926 except StopIteration:
1927 # No more positional arguments
1928 try:
1929 param = next(parameters)
1930 except StopIteration:
1931 # No more parameters. That's it. Just need to check that
1932 # we have no `kwargs` after this while loop
1933 break
1934 else:
1935 if param.kind == _VAR_POSITIONAL:
1936 # That's OK, just empty *args. Let's start parsing
1937 # kwargs
1938 break
1939 elif param.name in kwargs:
1940 if param.kind == _POSITIONAL_ONLY:
1941 msg = '{arg!r} parameter is positional only, ' \
1942 'but was passed as a keyword'
1943 msg = msg.format(arg=param.name)
1944 raise TypeError(msg) from None
1945 parameters_ex = (param,)
1946 break
1947 elif (param.kind == _VAR_KEYWORD or
1948 param.default is not _empty):
1949 # That's fine too - we have a default value for this
1950 # parameter. So, lets start parsing `kwargs`, starting
1951 # with the current parameter
1952 parameters_ex = (param,)
1953 break
1954 else:
1955 if partial:
1956 parameters_ex = (param,)
1957 break
1958 else:
1959 msg = '{arg!r} parameter lacking default value'
1960 msg = msg.format(arg=param.name)
1961 raise TypeError(msg) from None
1962 else:
1963 # We have a positional argument to process
1964 try:
1965 param = next(parameters)
1966 except StopIteration:
1967 raise TypeError('too many positional arguments') from None
1968 else:
1969 if param.kind in (_VAR_KEYWORD, _KEYWORD_ONLY):
1970 # Looks like we have no parameter for this positional
1971 # argument
1972 raise TypeError('too many positional arguments')
1973
1974 if param.kind == _VAR_POSITIONAL:
1975 # We have an '*args'-like argument, let's fill it with
1976 # all positional arguments we have left and move on to
1977 # the next phase
1978 values = [arg_val]
1979 values.extend(arg_vals)
1980 arguments[param.name] = tuple(values)
1981 break
1982
1983 if param.name in kwargs:
1984 raise TypeError('multiple values for argument '
1985 '{arg!r}'.format(arg=param.name))
1986
1987 arguments[param.name] = arg_val
1988
1989 # Now, we iterate through the remaining parameters to process
1990 # keyword arguments
1991 kwargs_param = None
1992 for param in itertools.chain(parameters_ex, parameters):
1993 if param.kind == _POSITIONAL_ONLY:
1994 # This should never happen in case of a properly built
1995 # Signature object (but let's have this check here
1996 # to ensure correct behaviour just in case)
1997 raise TypeError('{arg!r} parameter is positional only, '
1998 'but was passed as a keyword'. \
1999 format(arg=param.name))
2000
2001 if param.kind == _VAR_KEYWORD:
2002 # Memorize that we have a '**kwargs'-like parameter
2003 kwargs_param = param
2004 continue
2005
2006 param_name = param.name
2007 try:
2008 arg_val = kwargs.pop(param_name)
2009 except KeyError:
2010 # We have no value for this parameter. It's fine though,
2011 # if it has a default value, or it is an '*args'-like
2012 # parameter, left alone by the processing of positional
2013 # arguments.
2014 if (not partial and param.kind != _VAR_POSITIONAL and
2015 param.default is _empty):
2016 raise TypeError('{arg!r} parameter lacking default value'. \
2017 format(arg=param_name)) from None
2018
2019 else:
2020 arguments[param_name] = arg_val
2021
2022 if kwargs:
2023 if kwargs_param is not None:
2024 # Process our '**kwargs'-like parameter
2025 arguments[kwargs_param.name] = kwargs
2026 else:
2027 raise TypeError('too many keyword arguments')
2028
2029 return self._bound_arguments_cls(self, arguments)
2030
Antoine Pitroubd41d1b2013-01-29 21:20:57 +01002031 def bind(__bind_self, *args, **kwargs):
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002032 '''Get a BoundArguments object, that maps the passed `args`
2033 and `kwargs` to the function's signature. Raises `TypeError`
2034 if the passed arguments can not be bound.
2035 '''
Antoine Pitroubd41d1b2013-01-29 21:20:57 +01002036 return __bind_self._bind(args, kwargs)
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002037
Antoine Pitroubd41d1b2013-01-29 21:20:57 +01002038 def bind_partial(__bind_self, *args, **kwargs):
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002039 '''Get a BoundArguments object, that partially maps the
2040 passed `args` and `kwargs` to the function's signature.
2041 Raises `TypeError` if the passed arguments can not be bound.
2042 '''
Antoine Pitroubd41d1b2013-01-29 21:20:57 +01002043 return __bind_self._bind(args, kwargs, partial=True)
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002044
2045 def __str__(self):
2046 result = []
2047 render_kw_only_separator = True
2048 for idx, param in enumerate(self.parameters.values()):
2049 formatted = str(param)
2050
2051 kind = param.kind
2052 if kind == _VAR_POSITIONAL:
2053 # OK, we have an '*args'-like parameter, so we won't need
2054 # a '*' to separate keyword-only arguments
2055 render_kw_only_separator = False
2056 elif kind == _KEYWORD_ONLY and render_kw_only_separator:
2057 # We have a keyword-only parameter to render and we haven't
2058 # rendered an '*args'-like parameter before, so add a '*'
2059 # separator to the parameters list ("foo(arg1, *, arg2)" case)
2060 result.append('*')
2061 # This condition should be only triggered once, so
2062 # reset the flag
2063 render_kw_only_separator = False
2064
2065 result.append(formatted)
2066
2067 rendered = '({})'.format(', '.join(result))
2068
2069 if self.return_annotation is not _empty:
2070 anno = formatannotation(self.return_annotation)
2071 rendered += ' -> {}'.format(anno)
2072
2073 return rendered