blob: d6bd8cdb62c667090ff714f39388b3732e33d994 [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
Larry Hastings44e2eaa2013-11-23 15:37:55 -080034import ast
Brett Cannoncb66eb02012-05-11 12:58:42 -040035import importlib.machinery
36import itertools
Christian Heimes7131fd92008-02-19 14:21:46 +000037import linecache
Brett Cannoncb66eb02012-05-11 12:58:42 -040038import os
39import re
40import sys
41import tokenize
42import types
Brett Cannon2b88fcf2012-06-02 22:28:42 -040043import warnings
Larry Hastings7c7cbfc2012-06-22 15:19:35 -070044import functools
Nick Coghlan2f92e542012-06-23 19:39:55 +100045import builtins
Raymond Hettingera1a992c2005-03-11 06:46:45 +000046from operator import attrgetter
Larry Hastings7c7cbfc2012-06-22 15:19:35 -070047from collections import namedtuple, OrderedDict
Nick Coghlan09c81232010-08-17 10:18:16 +000048
49# Create constants for the compiler flags in Include/code.h
50# We try to get them from dis to avoid duplication, but fall
Ezio Melotti30b9d5d2013-08-17 15:50:46 +030051# back to hardcoding so the dependency is optional
Nick Coghlan09c81232010-08-17 10:18:16 +000052try:
53 from dis import COMPILER_FLAG_NAMES as _flag_names
Brett Cannoncd171c82013-07-04 17:43:24 -040054except ImportError:
Nick Coghlan09c81232010-08-17 10:18:16 +000055 CO_OPTIMIZED, CO_NEWLOCALS = 0x1, 0x2
56 CO_VARARGS, CO_VARKEYWORDS = 0x4, 0x8
57 CO_NESTED, CO_GENERATOR, CO_NOFREE = 0x10, 0x20, 0x40
58else:
59 mod_dict = globals()
60 for k, v in _flag_names.items():
61 mod_dict["CO_" + v] = k
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +000062
Christian Heimesbe5b30b2008-03-03 19:18:51 +000063# See Include/object.h
64TPFLAGS_IS_ABSTRACT = 1 << 20
65
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +000066# ----------------------------------------------------------- type-checking
67def ismodule(object):
68 """Return true if the object is a module.
69
70 Module objects provide these attributes:
Barry Warsaw28a691b2010-04-17 00:19:56 +000071 __cached__ pathname to byte compiled file
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +000072 __doc__ documentation string
73 __file__ filename (missing for built-in modules)"""
Tim Peters28bc59f2001-09-16 08:40:16 +000074 return isinstance(object, types.ModuleType)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +000075
76def isclass(object):
77 """Return true if the object is a class.
78
79 Class objects provide these attributes:
80 __doc__ documentation string
81 __module__ name of module in which this class was defined"""
Benjamin Petersonc4656002009-01-17 22:41:18 +000082 return isinstance(object, type)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +000083
84def ismethod(object):
85 """Return true if the object is an instance method.
86
87 Instance method objects provide these attributes:
88 __doc__ documentation string
89 __name__ name with which this method was defined
Christian Heimesff737952007-11-27 10:40:20 +000090 __func__ function object containing implementation of method
91 __self__ instance to which this method is bound"""
Tim Peters28bc59f2001-09-16 08:40:16 +000092 return isinstance(object, types.MethodType)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +000093
Tim Peters536d2262001-09-20 05:13:38 +000094def ismethoddescriptor(object):
Tim Petersf1d90b92001-09-20 05:47:55 +000095 """Return true if the object is a method descriptor.
96
97 But not if ismethod() or isclass() or isfunction() are true.
Tim Peters536d2262001-09-20 05:13:38 +000098
99 This is new in Python 2.2, and, for example, is true of int.__add__.
100 An object passing this test has a __get__ attribute but not a __set__
101 attribute, but beyond that the set of attributes varies. __name__ is
102 usually sensible, and __doc__ often is.
103
Tim Petersf1d90b92001-09-20 05:47:55 +0000104 Methods implemented via descriptors that also pass one of the other
105 tests return false from the ismethoddescriptor() test, simply because
106 the other tests promise more -- you can, e.g., count on having the
Christian Heimesff737952007-11-27 10:40:20 +0000107 __func__ attribute (etc) when an object passes ismethod()."""
Antoine Pitrou86a8a9a2011-12-21 09:57:40 +0100108 if isclass(object) or ismethod(object) or isfunction(object):
109 # mutual exclusion
110 return False
111 tp = type(object)
112 return hasattr(tp, "__get__") and not hasattr(tp, "__set__")
Tim Peters536d2262001-09-20 05:13:38 +0000113
Martin v. Löwise59e2ba2003-05-03 09:09:02 +0000114def isdatadescriptor(object):
115 """Return true if the object is a data descriptor.
116
117 Data descriptors have both a __get__ and a __set__ attribute. Examples are
118 properties (defined in Python) and getsets and members (defined in C).
119 Typically, data descriptors will also have __name__ and __doc__ attributes
120 (properties, getsets, and members have both of these attributes), but this
121 is not guaranteed."""
Antoine Pitrou86a8a9a2011-12-21 09:57:40 +0100122 if isclass(object) or ismethod(object) or isfunction(object):
123 # mutual exclusion
124 return False
125 tp = type(object)
126 return hasattr(tp, "__set__") and hasattr(tp, "__get__")
Martin v. Löwise59e2ba2003-05-03 09:09:02 +0000127
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000128if hasattr(types, 'MemberDescriptorType'):
129 # CPython and equivalent
130 def ismemberdescriptor(object):
131 """Return true if the object is a member descriptor.
132
133 Member descriptors are specialized descriptors defined in extension
134 modules."""
135 return isinstance(object, types.MemberDescriptorType)
136else:
137 # Other implementations
138 def ismemberdescriptor(object):
139 """Return true if the object is a member descriptor.
140
141 Member descriptors are specialized descriptors defined in extension
142 modules."""
143 return False
144
145if hasattr(types, 'GetSetDescriptorType'):
146 # CPython and equivalent
147 def isgetsetdescriptor(object):
148 """Return true if the object is a getset descriptor.
149
150 getset descriptors are specialized descriptors defined in extension
151 modules."""
152 return isinstance(object, types.GetSetDescriptorType)
153else:
154 # Other implementations
155 def isgetsetdescriptor(object):
156 """Return true if the object is a getset descriptor.
157
158 getset descriptors are specialized descriptors defined in extension
159 modules."""
160 return False
161
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000162def isfunction(object):
163 """Return true if the object is a user-defined function.
164
165 Function objects provide these attributes:
166 __doc__ documentation string
167 __name__ name with which this function was defined
Neal Norwitz221085d2007-02-25 20:55:47 +0000168 __code__ code object containing compiled function bytecode
169 __defaults__ tuple of any default values for arguments
170 __globals__ global namespace in which this function was defined
171 __annotations__ dict of parameter annotations
172 __kwdefaults__ dict of keyword only parameters with defaults"""
Tim Peters28bc59f2001-09-16 08:40:16 +0000173 return isinstance(object, types.FunctionType)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000174
Christian Heimes7131fd92008-02-19 14:21:46 +0000175def isgeneratorfunction(object):
176 """Return true if the object is a user-defined generator function.
177
178 Generator function objects provides same attributes as functions.
179
Alexander Belopolsky977a6842010-08-16 20:17:07 +0000180 See help(isfunction) for attributes listing."""
Georg Brandlb1441c72009-01-03 22:33:39 +0000181 return bool((isfunction(object) or ismethod(object)) and
182 object.__code__.co_flags & CO_GENERATOR)
Christian Heimes7131fd92008-02-19 14:21:46 +0000183
184def isgenerator(object):
185 """Return true if the object is a generator.
186
187 Generator objects provide these attributes:
Ezio Melotti30b9d5d2013-08-17 15:50:46 +0300188 __iter__ defined to support iteration over container
Christian Heimes7131fd92008-02-19 14:21:46 +0000189 close raises a new GeneratorExit exception inside the
190 generator to terminate the iteration
191 gi_code code object
192 gi_frame frame object or possibly None once the generator has
193 been exhausted
194 gi_running set to 1 when generator is executing, 0 otherwise
195 next return the next item from the container
196 send resumes the generator and "sends" a value that becomes
197 the result of the current yield-expression
198 throw used to raise an exception inside the generator"""
199 return isinstance(object, types.GeneratorType)
200
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000201def istraceback(object):
202 """Return true if the object is a traceback.
203
204 Traceback objects provide these attributes:
205 tb_frame frame object at this level
206 tb_lasti index of last attempted instruction in bytecode
207 tb_lineno current line number in Python source code
208 tb_next next inner traceback object (called by this level)"""
Tim Peters28bc59f2001-09-16 08:40:16 +0000209 return isinstance(object, types.TracebackType)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000210
211def isframe(object):
212 """Return true if the object is a frame object.
213
214 Frame objects provide these attributes:
215 f_back next outer frame object (this frame's caller)
216 f_builtins built-in namespace seen by this frame
217 f_code code object being executed in this frame
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000218 f_globals global namespace seen by this frame
219 f_lasti index of last attempted instruction in bytecode
220 f_lineno current line number in Python source code
221 f_locals local namespace seen by this frame
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000222 f_trace tracing function for this frame, or None"""
Tim Peters28bc59f2001-09-16 08:40:16 +0000223 return isinstance(object, types.FrameType)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000224
225def iscode(object):
226 """Return true if the object is a code object.
227
228 Code objects provide these attributes:
229 co_argcount number of arguments (not including * or ** args)
230 co_code string of raw compiled bytecode
231 co_consts tuple of constants used in the bytecode
232 co_filename name of file in which this code object was created
233 co_firstlineno number of first line in Python source code
234 co_flags bitmap: 1=optimized | 2=newlocals | 4=*arg | 8=**arg
235 co_lnotab encoded mapping of line numbers to bytecode indices
236 co_name name with which this code object was defined
237 co_names tuple of names of local variables
238 co_nlocals number of local variables
239 co_stacksize virtual machine stack space required
240 co_varnames tuple of names of arguments and local variables"""
Tim Peters28bc59f2001-09-16 08:40:16 +0000241 return isinstance(object, types.CodeType)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000242
243def isbuiltin(object):
244 """Return true if the object is a built-in function or method.
245
246 Built-in functions and methods provide these attributes:
247 __doc__ documentation string
248 __name__ original name of this function or method
249 __self__ instance to which a method is bound, or None"""
Tim Peters28bc59f2001-09-16 08:40:16 +0000250 return isinstance(object, types.BuiltinFunctionType)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000251
252def isroutine(object):
253 """Return true if the object is any kind of function or method."""
Tim Peters536d2262001-09-20 05:13:38 +0000254 return (isbuiltin(object)
255 or isfunction(object)
256 or ismethod(object)
257 or ismethoddescriptor(object))
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000258
Christian Heimesbe5b30b2008-03-03 19:18:51 +0000259def isabstract(object):
260 """Return true if the object is an abstract base class (ABC)."""
Benjamin Petersona0dfa822009-11-13 02:25:08 +0000261 return bool(isinstance(object, type) and object.__flags__ & TPFLAGS_IS_ABSTRACT)
Christian Heimesbe5b30b2008-03-03 19:18:51 +0000262
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000263def getmembers(object, predicate=None):
264 """Return all members of an object as (name, value) pairs sorted by name.
265 Optionally, only return members that satisfy a given predicate."""
Antoine Pitrou86a8a9a2011-12-21 09:57:40 +0100266 if isclass(object):
267 mro = (object,) + getmro(object)
268 else:
269 mro = ()
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000270 results = []
Ethan Furmane03ea372013-09-25 07:14:41 -0700271 processed = set()
272 names = dir(object)
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700273 # :dd any DynamicClassAttributes to the list of names if object is a class;
Ethan Furmane03ea372013-09-25 07:14:41 -0700274 # this may result in duplicate entries if, for example, a virtual
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700275 # attribute with the same name as a DynamicClassAttribute exists
Ethan Furmane03ea372013-09-25 07:14:41 -0700276 try:
277 for base in object.__bases__:
278 for k, v in base.__dict__.items():
279 if isinstance(v, types.DynamicClassAttribute):
280 names.append(k)
281 except AttributeError:
282 pass
283 for key in names:
Ethan Furman63c141c2013-10-18 00:27:39 -0700284 # First try to get the value via getattr. Some descriptors don't
285 # like calling their __get__ (see bug #1785), so fall back to
286 # looking in the __dict__.
287 try:
288 value = getattr(object, key)
289 # handle the duplicate key
290 if key in processed:
291 raise AttributeError
292 except AttributeError:
293 for base in mro:
294 if key in base.__dict__:
295 value = base.__dict__[key]
296 break
297 else:
298 # could be a (currently) missing slot member, or a buggy
299 # __dir__; discard and move on
Antoine Pitrou86a8a9a2011-12-21 09:57:40 +0100300 continue
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000301 if not predicate or predicate(value):
302 results.append((key, value))
Ethan Furmane03ea372013-09-25 07:14:41 -0700303 processed.add(key)
304 results.sort(key=lambda pair: pair[0])
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000305 return results
306
Christian Heimes25bb7832008-01-11 16:17:00 +0000307Attribute = namedtuple('Attribute', 'name kind defining_class object')
308
Tim Peters13b49d32001-09-23 02:00:29 +0000309def classify_class_attrs(cls):
310 """Return list of attribute-descriptor tuples.
311
312 For each name in dir(cls), the return list contains a 4-tuple
313 with these elements:
314
315 0. The name (a string).
316
317 1. The kind of attribute this is, one of these strings:
318 'class method' created via classmethod()
319 'static method' created via staticmethod()
320 'property' created via property()
Ethan Furmane03ea372013-09-25 07:14:41 -0700321 'method' any other flavor of method or descriptor
Tim Peters13b49d32001-09-23 02:00:29 +0000322 'data' not a method
323
324 2. The class which defined this attribute (a class).
325
Ethan Furmane03ea372013-09-25 07:14:41 -0700326 3. The object as obtained by calling getattr; if this fails, or if the
327 resulting object does not live anywhere in the class' mro (including
328 metaclasses) then the object is looked up in the defining class's
329 dict (found by walking the mro).
Ethan Furman668dede2013-09-14 18:53:26 -0700330
331 If one of the items in dir(cls) is stored in the metaclass it will now
332 be discovered and not have None be listed as the class in which it was
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700333 defined. Any items whose home class cannot be discovered are skipped.
Tim Peters13b49d32001-09-23 02:00:29 +0000334 """
335
336 mro = getmro(cls)
Ethan Furman668dede2013-09-14 18:53:26 -0700337 metamro = getmro(type(cls)) # for attributes stored in the metaclass
Ethan Furmane03ea372013-09-25 07:14:41 -0700338 metamro = tuple([cls for cls in metamro if cls not in (type, object)])
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700339 class_bases = (cls,) + mro
340 all_bases = class_bases + metamro
Tim Peters13b49d32001-09-23 02:00:29 +0000341 names = dir(cls)
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700342 # :dd any DynamicClassAttributes to the list of names;
Ethan Furmane03ea372013-09-25 07:14:41 -0700343 # this may result in duplicate entries if, for example, a virtual
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700344 # attribute with the same name as a DynamicClassAttribute exists.
Ethan Furman63c141c2013-10-18 00:27:39 -0700345 for base in mro:
Ethan Furmane03ea372013-09-25 07:14:41 -0700346 for k, v in base.__dict__.items():
347 if isinstance(v, types.DynamicClassAttribute):
348 names.append(k)
Tim Peters13b49d32001-09-23 02:00:29 +0000349 result = []
Ethan Furmane03ea372013-09-25 07:14:41 -0700350 processed = set()
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700351
Tim Peters13b49d32001-09-23 02:00:29 +0000352 for name in names:
Antoine Pitrou86a8a9a2011-12-21 09:57:40 +0100353 # Get the object associated with the name, and where it was defined.
Ethan Furmane03ea372013-09-25 07:14:41 -0700354 # Normal objects will be looked up with both getattr and directly in
355 # its class' dict (in case getattr fails [bug #1785], and also to look
356 # for a docstring).
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700357 # For DynamicClassAttributes on the second pass we only look in the
Ethan Furmane03ea372013-09-25 07:14:41 -0700358 # class's dict.
359 #
Tim Peters13b49d32001-09-23 02:00:29 +0000360 # Getting an obj from the __dict__ sometimes reveals more than
361 # using getattr. Static and class methods are dramatic examples.
Antoine Pitrou86a8a9a2011-12-21 09:57:40 +0100362 homecls = None
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700363 get_obj = None
364 dict_obj = None
Ethan Furmane03ea372013-09-25 07:14:41 -0700365 if name not in processed:
366 try:
Ethan Furmana8b07072013-10-18 01:22:08 -0700367 if name == '__dict__':
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700368 raise Exception("__dict__ is special, don't want the proxy")
Ethan Furmane03ea372013-09-25 07:14:41 -0700369 get_obj = getattr(cls, name)
370 except Exception as exc:
371 pass
372 else:
Ethan Furmane03ea372013-09-25 07:14:41 -0700373 homecls = getattr(get_obj, "__objclass__", homecls)
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700374 if homecls not in class_bases:
Ethan Furmane03ea372013-09-25 07:14:41 -0700375 # if the resulting object does not live somewhere in the
Ethan Furman63c141c2013-10-18 00:27:39 -0700376 # mro, drop it and search the mro manually
Ethan Furmane03ea372013-09-25 07:14:41 -0700377 homecls = None
Ethan Furman63c141c2013-10-18 00:27:39 -0700378 last_cls = None
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700379 # first look in the classes
380 for srch_cls in class_bases:
Ethan Furman63c141c2013-10-18 00:27:39 -0700381 srch_obj = getattr(srch_cls, name, None)
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700382 if srch_obj == get_obj:
Ethan Furman63c141c2013-10-18 00:27:39 -0700383 last_cls = srch_cls
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700384 # then check the metaclasses
385 for srch_cls in metamro:
386 try:
387 srch_obj = srch_cls.__getattr__(cls, name)
388 except AttributeError:
389 continue
390 if srch_obj == get_obj:
391 last_cls = srch_cls
Ethan Furman63c141c2013-10-18 00:27:39 -0700392 if last_cls is not None:
393 homecls = last_cls
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700394 for base in all_bases:
Ethan Furmane03ea372013-09-25 07:14:41 -0700395 if name in base.__dict__:
396 dict_obj = base.__dict__[name]
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700397 if homecls not in metamro:
398 homecls = base
Ethan Furmane03ea372013-09-25 07:14:41 -0700399 break
Ethan Furman63c141c2013-10-18 00:27:39 -0700400 if homecls is None:
401 # unable to locate the attribute anywhere, most likely due to
402 # buggy custom __dir__; discard and move on
403 continue
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700404 obj = get_obj or dict_obj
Ethan Furmane03ea372013-09-25 07:14:41 -0700405 # Classify the object or its descriptor.
Ethan Furman63c141c2013-10-18 00:27:39 -0700406 if isinstance(dict_obj, staticmethod):
Tim Peters13b49d32001-09-23 02:00:29 +0000407 kind = "static method"
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700408 obj = dict_obj
Ethan Furman63c141c2013-10-18 00:27:39 -0700409 elif isinstance(dict_obj, classmethod):
Tim Peters13b49d32001-09-23 02:00:29 +0000410 kind = "class method"
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700411 obj = dict_obj
412 elif isinstance(dict_obj, property):
Tim Peters13b49d32001-09-23 02:00:29 +0000413 kind = "property"
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700414 obj = dict_obj
Ethan Furmane03ea372013-09-25 07:14:41 -0700415 elif isfunction(obj) or ismethoddescriptor(obj):
Tim Peters13b49d32001-09-23 02:00:29 +0000416 kind = "method"
Antoine Pitrou86a8a9a2011-12-21 09:57:40 +0100417 else:
Ethan Furmane03ea372013-09-25 07:14:41 -0700418 kind = "data"
Christian Heimes25bb7832008-01-11 16:17:00 +0000419 result.append(Attribute(name, kind, homecls, obj))
Ethan Furmane03ea372013-09-25 07:14:41 -0700420 processed.add(name)
Tim Peters13b49d32001-09-23 02:00:29 +0000421 return result
422
Tim Peterse0b2d7a2001-09-22 06:10:55 +0000423# ----------------------------------------------------------- class helpers
Tim Peterse0b2d7a2001-09-22 06:10:55 +0000424
425def getmro(cls):
426 "Return tuple of base classes (including cls) in method resolution order."
Benjamin Petersonb82c8e52010-11-04 00:38:49 +0000427 return cls.__mro__
Tim Peterse0b2d7a2001-09-22 06:10:55 +0000428
Nick Coghlane8c45d62013-07-28 20:00:01 +1000429# -------------------------------------------------------- function helpers
430
431def unwrap(func, *, stop=None):
432 """Get the object wrapped by *func*.
433
434 Follows the chain of :attr:`__wrapped__` attributes returning the last
435 object in the chain.
436
437 *stop* is an optional callback accepting an object in the wrapper chain
438 as its sole argument that allows the unwrapping to be terminated early if
439 the callback returns a true value. If the callback never returns a true
440 value, the last object in the chain is returned as usual. For example,
441 :func:`signature` uses this to stop unwrapping if any object in the
442 chain has a ``__signature__`` attribute defined.
443
444 :exc:`ValueError` is raised if a cycle is encountered.
445
446 """
447 if stop is None:
448 def _is_wrapper(f):
449 return hasattr(f, '__wrapped__')
450 else:
451 def _is_wrapper(f):
452 return hasattr(f, '__wrapped__') and not stop(f)
453 f = func # remember the original func for error reporting
454 memo = {id(f)} # Memoise by id to tolerate non-hashable objects
455 while _is_wrapper(func):
456 func = func.__wrapped__
457 id_func = id(func)
458 if id_func in memo:
459 raise ValueError('wrapper loop when unwrapping {!r}'.format(f))
460 memo.add(id_func)
461 return func
462
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000463# -------------------------------------------------- source code extraction
464def indentsize(line):
465 """Return the indent size, in spaces, at the start of a line of text."""
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000466 expline = line.expandtabs()
467 return len(expline) - len(expline.lstrip())
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000468
469def getdoc(object):
470 """Get the documentation string for an object.
471
472 All tabs are expanded to spaces. To clean up docstrings that are
473 indented to line up with blocks of code, any whitespace than can be
474 uniformly removed from the second line onwards is removed."""
Tim Peters24008312002-03-17 18:56:20 +0000475 try:
476 doc = object.__doc__
477 except AttributeError:
478 return None
Guido van Rossum3172c5d2007-10-16 18:12:55 +0000479 if not isinstance(doc, str):
Tim Peters24008312002-03-17 18:56:20 +0000480 return None
Georg Brandl0c77a822008-06-10 16:37:50 +0000481 return cleandoc(doc)
482
483def cleandoc(doc):
484 """Clean up indentation from docstrings.
485
486 Any whitespace that can be uniformly removed from the second line
487 onwards is removed."""
Tim Peters24008312002-03-17 18:56:20 +0000488 try:
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000489 lines = doc.expandtabs().split('\n')
Tim Peters24008312002-03-17 18:56:20 +0000490 except UnicodeError:
491 return None
492 else:
Ka-Ping Yeea59ef7b2002-11-30 03:53:15 +0000493 # Find minimum indentation of any non-blank lines after first line.
Christian Heimesa37d4c62007-12-04 23:02:19 +0000494 margin = sys.maxsize
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000495 for line in lines[1:]:
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000496 content = len(line.lstrip())
Ka-Ping Yeea59ef7b2002-11-30 03:53:15 +0000497 if content:
498 indent = len(line) - content
499 margin = min(margin, indent)
500 # Remove indentation.
501 if lines:
502 lines[0] = lines[0].lstrip()
Christian Heimesa37d4c62007-12-04 23:02:19 +0000503 if margin < sys.maxsize:
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000504 for i in range(1, len(lines)): lines[i] = lines[i][margin:]
Ka-Ping Yeea59ef7b2002-11-30 03:53:15 +0000505 # Remove any trailing or leading blank lines.
506 while lines and not lines[-1]:
507 lines.pop()
508 while lines and not lines[0]:
509 lines.pop(0)
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000510 return '\n'.join(lines)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000511
512def getfile(object):
Ka-Ping Yeec113c242001-03-02 02:08:53 +0000513 """Work out which source or compiled file an object was defined in."""
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000514 if ismodule(object):
515 if hasattr(object, '__file__'):
516 return object.__file__
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +0000517 raise TypeError('{!r} is a built-in module'.format(object))
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000518 if isclass(object):
Ka-Ping Yeec99e0f12001-04-13 12:10:40 +0000519 object = sys.modules.get(object.__module__)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000520 if hasattr(object, '__file__'):
521 return object.__file__
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +0000522 raise TypeError('{!r} is a built-in class'.format(object))
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000523 if ismethod(object):
Christian Heimesff737952007-11-27 10:40:20 +0000524 object = object.__func__
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000525 if isfunction(object):
Neal Norwitz221085d2007-02-25 20:55:47 +0000526 object = object.__code__
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000527 if istraceback(object):
528 object = object.tb_frame
529 if isframe(object):
530 object = object.f_code
531 if iscode(object):
532 return object.co_filename
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +0000533 raise TypeError('{!r} is not a module, class, method, '
534 'function, traceback, frame, or code object'.format(object))
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000535
Christian Heimes25bb7832008-01-11 16:17:00 +0000536ModuleInfo = namedtuple('ModuleInfo', 'name suffix mode module_type')
537
Ka-Ping Yee4d6fc7f2001-04-10 11:43:00 +0000538def getmoduleinfo(path):
539 """Get the module name, suffix, mode, and module type for a given file."""
Brett Cannoncb66eb02012-05-11 12:58:42 -0400540 warnings.warn('inspect.getmoduleinfo() is deprecated', DeprecationWarning,
541 2)
Brett Cannone4f41de2013-06-16 13:13:40 -0400542 with warnings.catch_warnings():
543 warnings.simplefilter('ignore', PendingDeprecationWarning)
544 import imp
Ka-Ping Yee4d6fc7f2001-04-10 11:43:00 +0000545 filename = os.path.basename(path)
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000546 suffixes = [(-len(suffix), suffix, mode, mtype)
547 for suffix, mode, mtype in imp.get_suffixes()]
Ka-Ping Yee4d6fc7f2001-04-10 11:43:00 +0000548 suffixes.sort() # try longest suffixes first, in case they overlap
549 for neglen, suffix, mode, mtype in suffixes:
550 if filename[neglen:] == suffix:
Christian Heimes25bb7832008-01-11 16:17:00 +0000551 return ModuleInfo(filename[:neglen], suffix, mode, mtype)
Ka-Ping Yee4d6fc7f2001-04-10 11:43:00 +0000552
553def getmodulename(path):
554 """Return the module name for a given file, or None."""
Nick Coghlan76e07702012-07-18 23:14:57 +1000555 fname = os.path.basename(path)
556 # Check for paths that look like an actual module file
557 suffixes = [(-len(suffix), suffix)
558 for suffix in importlib.machinery.all_suffixes()]
559 suffixes.sort() # try longest suffixes first, in case they overlap
560 for neglen, suffix in suffixes:
561 if fname.endswith(suffix):
562 return fname[:neglen]
563 return None
Ka-Ping Yee4d6fc7f2001-04-10 11:43:00 +0000564
Ka-Ping Yeec113c242001-03-02 02:08:53 +0000565def getsourcefile(object):
R. David Murraya1b37402010-06-17 02:04:29 +0000566 """Return the filename that can be used to locate an object's source.
567 Return None if no way can be identified to get the source.
568 """
Ka-Ping Yeec113c242001-03-02 02:08:53 +0000569 filename = getfile(object)
Brett Cannoncb66eb02012-05-11 12:58:42 -0400570 all_bytecode_suffixes = importlib.machinery.DEBUG_BYTECODE_SUFFIXES[:]
571 all_bytecode_suffixes += importlib.machinery.OPTIMIZED_BYTECODE_SUFFIXES[:]
572 if any(filename.endswith(s) for s in all_bytecode_suffixes):
573 filename = (os.path.splitext(filename)[0] +
574 importlib.machinery.SOURCE_SUFFIXES[0])
575 elif any(filename.endswith(s) for s in
576 importlib.machinery.EXTENSION_SUFFIXES):
577 return None
Thomas Wouters477c8d52006-05-27 19:21:47 +0000578 if os.path.exists(filename):
579 return filename
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000580 # only return a non-existent filename if the module has a PEP 302 loader
Brett Cannon4c14b5d2013-05-04 13:56:58 -0400581 if getattr(getmodule(object, filename), '__loader__', None) is not None:
Ka-Ping Yeec113c242001-03-02 02:08:53 +0000582 return filename
R. David Murraya1b37402010-06-17 02:04:29 +0000583 # or it is in the linecache
584 if filename in linecache.cache:
585 return filename
Ka-Ping Yeec113c242001-03-02 02:08:53 +0000586
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000587def getabsfile(object, _filename=None):
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000588 """Return an absolute path to the source or compiled file for an object.
Ka-Ping Yeec113c242001-03-02 02:08:53 +0000589
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000590 The idea is for each object to have a unique origin, so this routine
591 normalizes the result as much as possible."""
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000592 if _filename is None:
593 _filename = getsourcefile(object) or getfile(object)
594 return os.path.normcase(os.path.abspath(_filename))
Ka-Ping Yeec113c242001-03-02 02:08:53 +0000595
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000596modulesbyfile = {}
Thomas Wouters89f507f2006-12-13 04:49:30 +0000597_filesbymodname = {}
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000598
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000599def getmodule(object, _filename=None):
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000600 """Return the module an object was defined in, or None if not found."""
Ka-Ping Yee202c99b2001-04-13 09:15:08 +0000601 if ismodule(object):
602 return object
Johannes Gijsbers93245262004-09-11 15:53:22 +0000603 if hasattr(object, '__module__'):
Ka-Ping Yee8b58b842001-03-01 13:56:16 +0000604 return sys.modules.get(object.__module__)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000605 # Try the filename to modulename cache
606 if _filename is not None and _filename in modulesbyfile:
607 return sys.modules.get(modulesbyfile[_filename])
608 # Try the cache again with the absolute file name
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000609 try:
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000610 file = getabsfile(object, _filename)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000611 except TypeError:
612 return None
Raymond Hettinger54f02222002-06-01 14:18:47 +0000613 if file in modulesbyfile:
Ka-Ping Yeeb38bbbd2003-03-28 16:29:50 +0000614 return sys.modules.get(modulesbyfile[file])
Thomas Wouters89f507f2006-12-13 04:49:30 +0000615 # Update the filename to module name cache and check yet again
616 # Copy sys.modules in order to cope with changes while iterating
Éric Araujoa74f8ef2011-11-29 16:58:53 +0100617 for modname, module in list(sys.modules.items()):
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000618 if ismodule(module) and hasattr(module, '__file__'):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000619 f = module.__file__
620 if f == _filesbymodname.get(modname, None):
621 # Have already mapped this module, so skip it
622 continue
623 _filesbymodname[modname] = f
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000624 f = getabsfile(module)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000625 # Always map to the name the module knows itself by
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000626 modulesbyfile[f] = modulesbyfile[
627 os.path.realpath(f)] = module.__name__
Raymond Hettinger54f02222002-06-01 14:18:47 +0000628 if file in modulesbyfile:
Ka-Ping Yeeb38bbbd2003-03-28 16:29:50 +0000629 return sys.modules.get(modulesbyfile[file])
Thomas Wouters89f507f2006-12-13 04:49:30 +0000630 # Check the main module
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000631 main = sys.modules['__main__']
Brett Cannon4a671fe2003-06-15 22:33:28 +0000632 if not hasattr(object, '__name__'):
633 return None
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000634 if hasattr(main, object.__name__):
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000635 mainobject = getattr(main, object.__name__)
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000636 if mainobject is object:
637 return main
Thomas Wouters89f507f2006-12-13 04:49:30 +0000638 # Check builtins
Georg Brandl1a3284e2007-12-02 09:40:06 +0000639 builtin = sys.modules['builtins']
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000640 if hasattr(builtin, object.__name__):
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000641 builtinobject = getattr(builtin, object.__name__)
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000642 if builtinobject is object:
643 return builtin
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000644
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000645def findsource(object):
646 """Return the entire source file and starting line number for an object.
647
648 The argument may be a module, class, method, function, traceback, frame,
649 or code object. The source code is returned as a list of all the lines
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200650 in the file and the line number indexes a line in that list. An OSError
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000651 is raised if the source code cannot be retrieved."""
Benjamin Peterson9620cc02011-06-11 15:53:11 -0500652
653 file = getfile(object)
654 sourcefile = getsourcefile(object)
Ezio Melotti1b145922013-03-30 05:17:24 +0200655 if not sourcefile and file[:1] + file[-1:] != '<>':
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200656 raise OSError('source code not available')
Benjamin Peterson9620cc02011-06-11 15:53:11 -0500657 file = sourcefile if sourcefile else file
658
Thomas Wouters89f507f2006-12-13 04:49:30 +0000659 module = getmodule(object, file)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000660 if module:
661 lines = linecache.getlines(file, module.__dict__)
662 else:
663 lines = linecache.getlines(file)
Neil Schemenauerf06f8532002-03-23 23:51:04 +0000664 if not lines:
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200665 raise OSError('could not get source code')
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000666
667 if ismodule(object):
668 return lines, 0
669
670 if isclass(object):
671 name = object.__name__
Thomas Wouters89f507f2006-12-13 04:49:30 +0000672 pat = re.compile(r'^(\s*)class\s*' + name + r'\b')
673 # make some effort to find the best matching class definition:
674 # use the one with the least indentation, which is the one
675 # that's most probably not inside a function definition.
676 candidates = []
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000677 for i in range(len(lines)):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000678 match = pat.match(lines[i])
679 if match:
680 # if it's at toplevel, it's already the best one
681 if lines[i][0] == 'c':
682 return lines, i
683 # else add whitespace to candidate list
684 candidates.append((match.group(1), i))
685 if candidates:
686 # this will sort by whitespace, and by line number,
687 # less whitespace first
688 candidates.sort()
689 return lines, candidates[0][1]
Jeremy Hyltonab919022003-06-27 18:41:20 +0000690 else:
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200691 raise OSError('could not find class definition')
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000692
693 if ismethod(object):
Christian Heimesff737952007-11-27 10:40:20 +0000694 object = object.__func__
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000695 if isfunction(object):
Neal Norwitz221085d2007-02-25 20:55:47 +0000696 object = object.__code__
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000697 if istraceback(object):
698 object = object.tb_frame
699 if isframe(object):
700 object = object.f_code
701 if iscode(object):
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000702 if not hasattr(object, 'co_firstlineno'):
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200703 raise OSError('could not find function definition')
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000704 lnum = object.co_firstlineno - 1
Johannes Gijsbers1542f342004-12-12 16:46:28 +0000705 pat = re.compile(r'^(\s*def\s)|(.*(?<!\w)lambda(:|\s))|^(\s*@)')
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000706 while lnum > 0:
Ka-Ping Yeea6e59712001-03-10 09:31:55 +0000707 if pat.match(lines[lnum]): break
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000708 lnum = lnum - 1
709 return lines, lnum
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200710 raise OSError('could not find code object')
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000711
712def getcomments(object):
Jeremy Hyltonb4c17c82002-03-28 23:01:56 +0000713 """Get lines of comments immediately preceding an object's source code.
714
715 Returns None when source can't be found.
716 """
717 try:
718 lines, lnum = findsource(object)
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200719 except (OSError, TypeError):
Jeremy Hyltonb4c17c82002-03-28 23:01:56 +0000720 return None
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000721
722 if ismodule(object):
723 # Look for a comment block at the top of the file.
724 start = 0
Ka-Ping Yeeb910efe2001-04-12 13:17:17 +0000725 if lines and lines[0][:2] == '#!': start = 1
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000726 while start < len(lines) and lines[start].strip() in ('', '#'):
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000727 start = start + 1
Ka-Ping Yeeb910efe2001-04-12 13:17:17 +0000728 if start < len(lines) and lines[start][:1] == '#':
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000729 comments = []
730 end = start
731 while end < len(lines) and lines[end][:1] == '#':
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000732 comments.append(lines[end].expandtabs())
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000733 end = end + 1
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000734 return ''.join(comments)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000735
736 # Look for a preceding block of comments at the same indentation.
737 elif lnum > 0:
738 indent = indentsize(lines[lnum])
739 end = lnum - 1
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000740 if end >= 0 and lines[end].lstrip()[:1] == '#' and \
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000741 indentsize(lines[end]) == indent:
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000742 comments = [lines[end].expandtabs().lstrip()]
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000743 if end > 0:
744 end = end - 1
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000745 comment = lines[end].expandtabs().lstrip()
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000746 while comment[:1] == '#' and indentsize(lines[end]) == indent:
747 comments[:0] = [comment]
748 end = end - 1
749 if end < 0: break
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000750 comment = lines[end].expandtabs().lstrip()
751 while comments and comments[0].strip() == '#':
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000752 comments[:1] = []
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000753 while comments and comments[-1].strip() == '#':
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000754 comments[-1:] = []
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000755 return ''.join(comments)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000756
Tim Peters4efb6e92001-06-29 23:51:08 +0000757class EndOfBlock(Exception): pass
758
759class BlockFinder:
760 """Provide a tokeneater() method to detect the end of a code block."""
761 def __init__(self):
762 self.indent = 0
Johannes Gijsbersa5855d52005-03-12 16:37:11 +0000763 self.islambda = False
Johannes Gijsbers1542f342004-12-12 16:46:28 +0000764 self.started = False
765 self.passline = False
Armin Rigodd5c0232005-09-25 11:45:45 +0000766 self.last = 1
Tim Peters4efb6e92001-06-29 23:51:08 +0000767
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000768 def tokeneater(self, type, token, srowcol, erowcol, line):
Tim Peters4efb6e92001-06-29 23:51:08 +0000769 if not self.started:
Armin Rigodd5c0232005-09-25 11:45:45 +0000770 # look for the first "def", "class" or "lambda"
Johannes Gijsbers1542f342004-12-12 16:46:28 +0000771 if token in ("def", "class", "lambda"):
Johannes Gijsbersa5855d52005-03-12 16:37:11 +0000772 if token == "lambda":
773 self.islambda = True
Johannes Gijsbers1542f342004-12-12 16:46:28 +0000774 self.started = True
Armin Rigodd5c0232005-09-25 11:45:45 +0000775 self.passline = True # skip to the end of the line
Tim Peters4efb6e92001-06-29 23:51:08 +0000776 elif type == tokenize.NEWLINE:
Armin Rigodd5c0232005-09-25 11:45:45 +0000777 self.passline = False # stop skipping when a NEWLINE is seen
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000778 self.last = srowcol[0]
Armin Rigodd5c0232005-09-25 11:45:45 +0000779 if self.islambda: # lambdas always end at the first NEWLINE
780 raise EndOfBlock
Johannes Gijsbers1542f342004-12-12 16:46:28 +0000781 elif self.passline:
782 pass
Tim Peters4efb6e92001-06-29 23:51:08 +0000783 elif type == tokenize.INDENT:
784 self.indent = self.indent + 1
Johannes Gijsbers1542f342004-12-12 16:46:28 +0000785 self.passline = True
Tim Peters4efb6e92001-06-29 23:51:08 +0000786 elif type == tokenize.DEDENT:
787 self.indent = self.indent - 1
Armin Rigodd5c0232005-09-25 11:45:45 +0000788 # the end of matching indent/dedent pairs end a block
789 # (note that this only works for "def"/"class" blocks,
790 # not e.g. for "if: else:" or "try: finally:" blocks)
791 if self.indent <= 0:
792 raise EndOfBlock
793 elif self.indent == 0 and type not in (tokenize.COMMENT, tokenize.NL):
794 # any other token on the same indentation level end the previous
795 # block as well, except the pseudo-tokens COMMENT and NL.
796 raise EndOfBlock
Tim Peters4efb6e92001-06-29 23:51:08 +0000797
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000798def getblock(lines):
799 """Extract the block of code at the top of the given list of lines."""
Armin Rigodd5c0232005-09-25 11:45:45 +0000800 blockfinder = BlockFinder()
Tim Peters4efb6e92001-06-29 23:51:08 +0000801 try:
Trent Nelson428de652008-03-18 22:41:35 +0000802 tokens = tokenize.generate_tokens(iter(lines).__next__)
803 for _token in tokens:
804 blockfinder.tokeneater(*_token)
Armin Rigodd5c0232005-09-25 11:45:45 +0000805 except (EndOfBlock, IndentationError):
806 pass
807 return lines[:blockfinder.last]
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000808
809def getsourcelines(object):
810 """Return a list of source lines and starting line number for an object.
811
812 The argument may be a module, class, method, function, traceback, frame,
813 or code object. The source code is returned as a list of the lines
814 corresponding to the object and the line number indicates where in the
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200815 original source file the first line of code was found. An OSError is
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000816 raised if the source code cannot be retrieved."""
817 lines, lnum = findsource(object)
818
819 if ismodule(object): return lines, 0
820 else: return getblock(lines[lnum:]), lnum + 1
821
822def getsource(object):
823 """Return the text of the source code for an object.
824
825 The argument may be a module, class, method, function, traceback, frame,
826 or code object. The source code is returned as a single string. An
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200827 OSError is raised if the source code cannot be retrieved."""
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000828 lines, lnum = getsourcelines(object)
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000829 return ''.join(lines)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000830
831# --------------------------------------------------- class tree extraction
832def walktree(classes, children, parent):
833 """Recursive helper function for getclasstree()."""
834 results = []
Raymond Hettingera1a992c2005-03-11 06:46:45 +0000835 classes.sort(key=attrgetter('__module__', '__name__'))
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000836 for c in classes:
837 results.append((c, c.__bases__))
Raymond Hettinger54f02222002-06-01 14:18:47 +0000838 if c in children:
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000839 results.append(walktree(children[c], children, c))
840 return results
841
Georg Brandl5ce83a02009-06-01 17:23:51 +0000842def getclasstree(classes, unique=False):
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000843 """Arrange the given list of classes into a hierarchy of nested lists.
844
845 Where a nested list appears, it contains classes derived from the class
846 whose entry immediately precedes the list. Each entry is a 2-tuple
847 containing a class and a tuple of its base classes. If the 'unique'
848 argument is true, exactly one entry appears in the returned structure
849 for each class in the given list. Otherwise, classes using multiple
850 inheritance and their descendants will appear multiple times."""
851 children = {}
852 roots = []
853 for c in classes:
854 if c.__bases__:
855 for parent in c.__bases__:
Raymond Hettinger54f02222002-06-01 14:18:47 +0000856 if not parent in children:
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000857 children[parent] = []
Serhiy Storchaka362c1b52013-09-05 17:14:32 +0300858 if c not in children[parent]:
859 children[parent].append(c)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000860 if unique and parent in classes: break
861 elif c not in roots:
862 roots.append(c)
Raymond Hettingere0d49722002-06-02 18:55:56 +0000863 for parent in children:
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000864 if parent not in classes:
865 roots.append(parent)
866 return walktree(roots, children, None)
867
868# ------------------------------------------------ argument list extraction
Christian Heimes25bb7832008-01-11 16:17:00 +0000869Arguments = namedtuple('Arguments', 'args, varargs, varkw')
870
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000871def getargs(co):
872 """Get information about the arguments accepted by a code object.
873
Guido van Rossum2e65f892007-02-28 22:03:49 +0000874 Three things are returned: (args, varargs, varkw), where
Georg Brandlc1c4bf82010-10-15 16:07:41 +0000875 'args' is the list of argument names. Keyword-only arguments are
876 appended. 'varargs' and 'varkw' are the names of the * and **
877 arguments or None."""
Guido van Rossum2e65f892007-02-28 22:03:49 +0000878 args, varargs, kwonlyargs, varkw = _getfullargs(co)
Christian Heimes25bb7832008-01-11 16:17:00 +0000879 return Arguments(args + kwonlyargs, varargs, varkw)
Guido van Rossum2e65f892007-02-28 22:03:49 +0000880
881def _getfullargs(co):
882 """Get information about the arguments accepted by a code object.
883
884 Four things are returned: (args, varargs, kwonlyargs, varkw), where
Georg Brandlc1c4bf82010-10-15 16:07:41 +0000885 'args' and 'kwonlyargs' are lists of argument names, and 'varargs'
886 and 'varkw' are the names of the * and ** arguments or None."""
Jeremy Hylton64967882003-06-27 18:14:39 +0000887
888 if not iscode(co):
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +0000889 raise TypeError('{!r} is not a code object'.format(co))
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000890
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000891 nargs = co.co_argcount
892 names = co.co_varnames
Guido van Rossum2e65f892007-02-28 22:03:49 +0000893 nkwargs = co.co_kwonlyargcount
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000894 args = list(names[:nargs])
Guido van Rossum2e65f892007-02-28 22:03:49 +0000895 kwonlyargs = list(names[nargs:nargs+nkwargs])
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000896 step = 0
897
Guido van Rossum2e65f892007-02-28 22:03:49 +0000898 nargs += nkwargs
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000899 varargs = None
900 if co.co_flags & CO_VARARGS:
901 varargs = co.co_varnames[nargs]
902 nargs = nargs + 1
903 varkw = None
904 if co.co_flags & CO_VARKEYWORDS:
905 varkw = co.co_varnames[nargs]
Guido van Rossum2e65f892007-02-28 22:03:49 +0000906 return args, varargs, kwonlyargs, varkw
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000907
Christian Heimes25bb7832008-01-11 16:17:00 +0000908
909ArgSpec = namedtuple('ArgSpec', 'args varargs keywords defaults')
910
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000911def getargspec(func):
912 """Get the names and default values of a function's arguments.
913
914 A tuple of four things is returned: (args, varargs, varkw, defaults).
Georg Brandlc1c4bf82010-10-15 16:07:41 +0000915 'args' is a list of the argument names.
Guido van Rossum2e65f892007-02-28 22:03:49 +0000916 'args' will include keyword-only argument names.
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000917 'varargs' and 'varkw' are the names of the * and ** arguments or None.
Jeremy Hylton64967882003-06-27 18:14:39 +0000918 'defaults' is an n-tuple of the default values of the last n arguments.
Guido van Rossuma8add0e2007-05-14 22:03:55 +0000919
Guido van Rossum2e65f892007-02-28 22:03:49 +0000920 Use the getfullargspec() API for Python-3000 code, as annotations
921 and keyword arguments are supported. getargspec() will raise ValueError
922 if the func has either annotations or keyword arguments.
923 """
924
925 args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults, ann = \
926 getfullargspec(func)
927 if kwonlyargs or ann:
Collin Winterce36ad82007-08-30 01:19:48 +0000928 raise ValueError("Function has keyword-only arguments or annotations"
929 ", use getfullargspec() API which can support them")
Christian Heimes25bb7832008-01-11 16:17:00 +0000930 return ArgSpec(args, varargs, varkw, defaults)
931
932FullArgSpec = namedtuple('FullArgSpec',
Benjamin Peterson3d4ca742008-11-12 21:39:01 +0000933 'args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults, annotations')
Guido van Rossum2e65f892007-02-28 22:03:49 +0000934
935def getfullargspec(func):
936 """Get the names and default values of a function's arguments.
937
Brett Cannon504d8852007-09-07 02:12:14 +0000938 A tuple of seven things is returned:
939 (args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults annotations).
Georg Brandlc1c4bf82010-10-15 16:07:41 +0000940 'args' is a list of the argument names.
Guido van Rossum2e65f892007-02-28 22:03:49 +0000941 'varargs' and 'varkw' are the names of the * and ** arguments or None.
942 'defaults' is an n-tuple of the default values of the last n arguments.
943 'kwonlyargs' is a list of keyword-only argument names.
944 'kwonlydefaults' is a dictionary mapping names from kwonlyargs to defaults.
945 'annotations' is a dictionary mapping argument names to annotations.
Guido van Rossuma8add0e2007-05-14 22:03:55 +0000946
Guido van Rossum2e65f892007-02-28 22:03:49 +0000947 The first four items in the tuple correspond to getargspec().
Jeremy Hylton64967882003-06-27 18:14:39 +0000948 """
949
950 if ismethod(func):
Christian Heimesff737952007-11-27 10:40:20 +0000951 func = func.__func__
Jeremy Hylton64967882003-06-27 18:14:39 +0000952 if not isfunction(func):
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +0000953 raise TypeError('{!r} is not a Python function'.format(func))
Guido van Rossum2e65f892007-02-28 22:03:49 +0000954 args, varargs, kwonlyargs, varkw = _getfullargs(func.__code__)
Christian Heimes25bb7832008-01-11 16:17:00 +0000955 return FullArgSpec(args, varargs, varkw, func.__defaults__,
Guido van Rossum2e65f892007-02-28 22:03:49 +0000956 kwonlyargs, func.__kwdefaults__, func.__annotations__)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000957
Christian Heimes25bb7832008-01-11 16:17:00 +0000958ArgInfo = namedtuple('ArgInfo', 'args varargs keywords locals')
959
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000960def getargvalues(frame):
961 """Get information about arguments passed into a particular frame.
962
963 A tuple of four things is returned: (args, varargs, varkw, locals).
Georg Brandlc1c4bf82010-10-15 16:07:41 +0000964 'args' is a list of the argument names.
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000965 'varargs' and 'varkw' are the names of the * and ** arguments or None.
966 'locals' is the locals dictionary of the given frame."""
967 args, varargs, varkw = getargs(frame.f_code)
Benjamin Peterson1a6e0d02008-10-25 15:49:17 +0000968 return ArgInfo(args, varargs, varkw, frame.f_locals)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000969
Guido van Rossum2e65f892007-02-28 22:03:49 +0000970def formatannotation(annotation, base_module=None):
971 if isinstance(annotation, type):
Georg Brandl1a3284e2007-12-02 09:40:06 +0000972 if annotation.__module__ in ('builtins', base_module):
Guido van Rossum2e65f892007-02-28 22:03:49 +0000973 return annotation.__name__
974 return annotation.__module__+'.'+annotation.__name__
975 return repr(annotation)
Guido van Rossuma8add0e2007-05-14 22:03:55 +0000976
Guido van Rossum2e65f892007-02-28 22:03:49 +0000977def formatannotationrelativeto(object):
Guido van Rossuma8add0e2007-05-14 22:03:55 +0000978 module = getattr(object, '__module__', None)
979 def _formatannotation(annotation):
980 return formatannotation(annotation, module)
981 return _formatannotation
Guido van Rossum2e65f892007-02-28 22:03:49 +0000982
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000983def formatargspec(args, varargs=None, varkw=None, defaults=None,
Guido van Rossum2e65f892007-02-28 22:03:49 +0000984 kwonlyargs=(), kwonlydefaults={}, annotations={},
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000985 formatarg=str,
986 formatvarargs=lambda name: '*' + name,
987 formatvarkw=lambda name: '**' + name,
988 formatvalue=lambda value: '=' + repr(value),
Guido van Rossum2e65f892007-02-28 22:03:49 +0000989 formatreturns=lambda text: ' -> ' + text,
Georg Brandlc1c4bf82010-10-15 16:07:41 +0000990 formatannotation=formatannotation):
Guido van Rossuma8add0e2007-05-14 22:03:55 +0000991 """Format an argument spec from the values returned by getargspec
Guido van Rossum2e65f892007-02-28 22:03:49 +0000992 or getfullargspec.
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000993
Guido van Rossum2e65f892007-02-28 22:03:49 +0000994 The first seven arguments are (args, varargs, varkw, defaults,
995 kwonlyargs, kwonlydefaults, annotations). The other five arguments
996 are the corresponding optional formatting functions that are called to
997 turn names and values into strings. The last argument is an optional
998 function to format the sequence of arguments."""
999 def formatargandannotation(arg):
1000 result = formatarg(arg)
1001 if arg in annotations:
1002 result += ': ' + formatannotation(annotations[arg])
1003 return result
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001004 specs = []
1005 if defaults:
1006 firstdefault = len(args) - len(defaults)
Benjamin Petersonb58dda72009-01-18 22:27:04 +00001007 for i, arg in enumerate(args):
Georg Brandlc1c4bf82010-10-15 16:07:41 +00001008 spec = formatargandannotation(arg)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001009 if defaults and i >= firstdefault:
1010 spec = spec + formatvalue(defaults[i - firstdefault])
1011 specs.append(spec)
Raymond Hettinger936654b2002-06-01 03:06:31 +00001012 if varargs is not None:
Guido van Rossum2e65f892007-02-28 22:03:49 +00001013 specs.append(formatvarargs(formatargandannotation(varargs)))
1014 else:
1015 if kwonlyargs:
1016 specs.append('*')
1017 if kwonlyargs:
1018 for kwonlyarg in kwonlyargs:
1019 spec = formatargandannotation(kwonlyarg)
Benjamin Peterson9953a8d2009-01-17 04:15:01 +00001020 if kwonlydefaults and kwonlyarg in kwonlydefaults:
Guido van Rossum2e65f892007-02-28 22:03:49 +00001021 spec += formatvalue(kwonlydefaults[kwonlyarg])
1022 specs.append(spec)
Raymond Hettinger936654b2002-06-01 03:06:31 +00001023 if varkw is not None:
Guido van Rossum2e65f892007-02-28 22:03:49 +00001024 specs.append(formatvarkw(formatargandannotation(varkw)))
Neal Norwitz9d72bb42007-04-17 08:48:32 +00001025 result = '(' + ', '.join(specs) + ')'
Guido van Rossum2e65f892007-02-28 22:03:49 +00001026 if 'return' in annotations:
1027 result += formatreturns(formatannotation(annotations['return']))
1028 return result
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001029
1030def formatargvalues(args, varargs, varkw, locals,
1031 formatarg=str,
1032 formatvarargs=lambda name: '*' + name,
1033 formatvarkw=lambda name: '**' + name,
Georg Brandlc1c4bf82010-10-15 16:07:41 +00001034 formatvalue=lambda value: '=' + repr(value)):
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001035 """Format an argument spec from the 4 values returned by getargvalues.
1036
1037 The first four arguments are (args, varargs, varkw, locals). The
1038 next four arguments are the corresponding optional formatting functions
1039 that are called to turn names and values into strings. The ninth
1040 argument is an optional function to format the sequence of arguments."""
1041 def convert(name, locals=locals,
1042 formatarg=formatarg, formatvalue=formatvalue):
1043 return formatarg(name) + formatvalue(locals[name])
1044 specs = []
1045 for i in range(len(args)):
Georg Brandlc1c4bf82010-10-15 16:07:41 +00001046 specs.append(convert(args[i]))
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001047 if varargs:
1048 specs.append(formatvarargs(varargs) + formatvalue(locals[varargs]))
1049 if varkw:
1050 specs.append(formatvarkw(varkw) + formatvalue(locals[varkw]))
Neal Norwitz9d72bb42007-04-17 08:48:32 +00001051 return '(' + ', '.join(specs) + ')'
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001052
Benjamin Petersone109c702011-06-24 09:37:26 -05001053def _missing_arguments(f_name, argnames, pos, values):
1054 names = [repr(name) for name in argnames if name not in values]
1055 missing = len(names)
1056 if missing == 1:
1057 s = names[0]
1058 elif missing == 2:
1059 s = "{} and {}".format(*names)
1060 else:
1061 tail = ", {} and {}".format(names[-2:])
1062 del names[-2:]
1063 s = ", ".join(names) + tail
1064 raise TypeError("%s() missing %i required %s argument%s: %s" %
1065 (f_name, missing,
1066 "positional" if pos else "keyword-only",
1067 "" if missing == 1 else "s", s))
1068
1069def _too_many(f_name, args, kwonly, varargs, defcount, given, values):
Benjamin Petersonb204a422011-06-05 22:04:07 -05001070 atleast = len(args) - defcount
Benjamin Petersonb204a422011-06-05 22:04:07 -05001071 kwonly_given = len([arg for arg in kwonly if arg in values])
1072 if varargs:
1073 plural = atleast != 1
1074 sig = "at least %d" % (atleast,)
1075 elif defcount:
1076 plural = True
1077 sig = "from %d to %d" % (atleast, len(args))
1078 else:
1079 plural = len(args) != 1
1080 sig = str(len(args))
1081 kwonly_sig = ""
1082 if kwonly_given:
1083 msg = " positional argument%s (and %d keyword-only argument%s)"
1084 kwonly_sig = (msg % ("s" if given != 1 else "", kwonly_given,
1085 "s" if kwonly_given != 1 else ""))
1086 raise TypeError("%s() takes %s positional argument%s but %d%s %s given" %
1087 (f_name, sig, "s" if plural else "", given, kwonly_sig,
1088 "was" if given == 1 and not kwonly_given else "were"))
1089
Benjamin Peterson3e6ab172014-01-02 12:24:08 -06001090def getcallargs(*func_and_positional, **named):
Benjamin Peterson25cd7eb2010-03-30 18:42:32 +00001091 """Get the mapping of arguments to values.
1092
1093 A dict is returned, with keys the function argument names (including the
1094 names of the * and ** arguments, if any), and values the respective bound
1095 values from 'positional' and 'named'."""
Benjamin Peterson3e6ab172014-01-02 12:24:08 -06001096 func = func_and_positional[0]
1097 positional = func_and_positional[1:]
Benjamin Peterson25cd7eb2010-03-30 18:42:32 +00001098 spec = getfullargspec(func)
1099 args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults, ann = spec
1100 f_name = func.__name__
1101 arg2value = {}
1102
Benjamin Petersonb204a422011-06-05 22:04:07 -05001103
Benjamin Peterson25cd7eb2010-03-30 18:42:32 +00001104 if ismethod(func) and func.__self__ is not None:
1105 # implicit 'self' (or 'cls' for classmethods) argument
1106 positional = (func.__self__,) + positional
1107 num_pos = len(positional)
Benjamin Peterson25cd7eb2010-03-30 18:42:32 +00001108 num_args = len(args)
1109 num_defaults = len(defaults) if defaults else 0
Benjamin Peterson25cd7eb2010-03-30 18:42:32 +00001110
Benjamin Petersonb204a422011-06-05 22:04:07 -05001111 n = min(num_pos, num_args)
1112 for i in range(n):
1113 arg2value[args[i]] = positional[i]
1114 if varargs:
1115 arg2value[varargs] = tuple(positional[n:])
1116 possible_kwargs = set(args + kwonlyargs)
Benjamin Peterson25cd7eb2010-03-30 18:42:32 +00001117 if varkw:
Benjamin Petersonb204a422011-06-05 22:04:07 -05001118 arg2value[varkw] = {}
1119 for kw, value in named.items():
1120 if kw not in possible_kwargs:
1121 if not varkw:
1122 raise TypeError("%s() got an unexpected keyword argument %r" %
1123 (f_name, kw))
1124 arg2value[varkw][kw] = value
1125 continue
1126 if kw in arg2value:
1127 raise TypeError("%s() got multiple values for argument %r" %
1128 (f_name, kw))
1129 arg2value[kw] = value
1130 if num_pos > num_args and not varargs:
Benjamin Petersone109c702011-06-24 09:37:26 -05001131 _too_many(f_name, args, kwonlyargs, varargs, num_defaults,
1132 num_pos, arg2value)
Benjamin Petersonb204a422011-06-05 22:04:07 -05001133 if num_pos < num_args:
Benjamin Petersone109c702011-06-24 09:37:26 -05001134 req = args[:num_args - num_defaults]
1135 for arg in req:
Benjamin Petersonb204a422011-06-05 22:04:07 -05001136 if arg not in arg2value:
Benjamin Petersone109c702011-06-24 09:37:26 -05001137 _missing_arguments(f_name, req, True, arg2value)
Benjamin Petersonb204a422011-06-05 22:04:07 -05001138 for i, arg in enumerate(args[num_args - num_defaults:]):
1139 if arg not in arg2value:
1140 arg2value[arg] = defaults[i]
Benjamin Petersone109c702011-06-24 09:37:26 -05001141 missing = 0
Benjamin Petersonb204a422011-06-05 22:04:07 -05001142 for kwarg in kwonlyargs:
1143 if kwarg not in arg2value:
Benjamin Petersone109c702011-06-24 09:37:26 -05001144 if kwarg in kwonlydefaults:
1145 arg2value[kwarg] = kwonlydefaults[kwarg]
1146 else:
1147 missing += 1
1148 if missing:
1149 _missing_arguments(f_name, kwonlyargs, False, arg2value)
Benjamin Peterson25cd7eb2010-03-30 18:42:32 +00001150 return arg2value
1151
Nick Coghlan2f92e542012-06-23 19:39:55 +10001152ClosureVars = namedtuple('ClosureVars', 'nonlocals globals builtins unbound')
1153
1154def getclosurevars(func):
1155 """
1156 Get the mapping of free variables to their current values.
1157
Meador Inge8fda3592012-07-19 21:33:21 -05001158 Returns a named tuple of dicts mapping the current nonlocal, global
Nick Coghlan2f92e542012-06-23 19:39:55 +10001159 and builtin references as seen by the body of the function. A final
1160 set of unbound names that could not be resolved is also provided.
1161 """
1162
1163 if ismethod(func):
1164 func = func.__func__
1165
1166 if not isfunction(func):
1167 raise TypeError("'{!r}' is not a Python function".format(func))
1168
1169 code = func.__code__
1170 # Nonlocal references are named in co_freevars and resolved
1171 # by looking them up in __closure__ by positional index
1172 if func.__closure__ is None:
1173 nonlocal_vars = {}
1174 else:
1175 nonlocal_vars = {
1176 var : cell.cell_contents
1177 for var, cell in zip(code.co_freevars, func.__closure__)
1178 }
1179
1180 # Global and builtin references are named in co_names and resolved
1181 # by looking them up in __globals__ or __builtins__
1182 global_ns = func.__globals__
1183 builtin_ns = global_ns.get("__builtins__", builtins.__dict__)
1184 if ismodule(builtin_ns):
1185 builtin_ns = builtin_ns.__dict__
1186 global_vars = {}
1187 builtin_vars = {}
1188 unbound_names = set()
1189 for name in code.co_names:
1190 if name in ("None", "True", "False"):
1191 # Because these used to be builtins instead of keywords, they
1192 # may still show up as name references. We ignore them.
1193 continue
1194 try:
1195 global_vars[name] = global_ns[name]
1196 except KeyError:
1197 try:
1198 builtin_vars[name] = builtin_ns[name]
1199 except KeyError:
1200 unbound_names.add(name)
1201
1202 return ClosureVars(nonlocal_vars, global_vars,
1203 builtin_vars, unbound_names)
1204
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001205# -------------------------------------------------- stack frame extraction
Christian Heimes25bb7832008-01-11 16:17:00 +00001206
1207Traceback = namedtuple('Traceback', 'filename lineno function code_context index')
1208
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001209def getframeinfo(frame, context=1):
1210 """Get information about a frame or traceback object.
1211
1212 A tuple of five things is returned: the filename, the line number of
1213 the current line, the function name, a list of lines of context from
1214 the source code, and the index of the current line within that list.
1215 The optional second argument specifies the number of lines of context
1216 to return, which are centered around the current line."""
1217 if istraceback(frame):
Andrew M. Kuchlingba8b6bc2004-06-05 14:11:59 +00001218 lineno = frame.tb_lineno
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001219 frame = frame.tb_frame
Andrew M. Kuchlingba8b6bc2004-06-05 14:11:59 +00001220 else:
1221 lineno = frame.f_lineno
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001222 if not isframe(frame):
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00001223 raise TypeError('{!r} is not a frame or traceback object'.format(frame))
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001224
Neil Schemenauerf06f8532002-03-23 23:51:04 +00001225 filename = getsourcefile(frame) or getfile(frame)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001226 if context > 0:
Guido van Rossum54e54c62001-09-04 19:14:14 +00001227 start = lineno - 1 - context//2
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001228 try:
1229 lines, lnum = findsource(frame)
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02001230 except OSError:
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +00001231 lines = index = None
1232 else:
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001233 start = max(start, 1)
Raymond Hettingera0501712004-06-15 11:22:53 +00001234 start = max(0, min(start, len(lines) - context))
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001235 lines = lines[start:start+context]
Ka-Ping Yee59ade082001-03-01 03:55:35 +00001236 index = lineno - 1 - start
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001237 else:
1238 lines = index = None
1239
Christian Heimes25bb7832008-01-11 16:17:00 +00001240 return Traceback(filename, lineno, frame.f_code.co_name, lines, index)
Ka-Ping Yee59ade082001-03-01 03:55:35 +00001241
1242def getlineno(frame):
1243 """Get the line number from a frame object, allowing for optimization."""
Michael W. Hudsondd32a912002-08-15 14:59:02 +00001244 # FrameType.f_lineno is now a descriptor that grovels co_lnotab
1245 return frame.f_lineno
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001246
1247def getouterframes(frame, context=1):
1248 """Get a list of records for a frame and all higher (calling) frames.
1249
1250 Each record contains a frame object, filename, line number, function
1251 name, a list of lines of context, and index within the context."""
1252 framelist = []
1253 while frame:
1254 framelist.append((frame,) + getframeinfo(frame, context))
1255 frame = frame.f_back
1256 return framelist
1257
1258def getinnerframes(tb, context=1):
1259 """Get a list of records for a traceback's frame and all lower frames.
1260
1261 Each record contains a frame object, filename, line number, function
1262 name, a list of lines of context, and index within the context."""
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001263 framelist = []
1264 while tb:
1265 framelist.append((tb.tb_frame,) + getframeinfo(tb, context))
1266 tb = tb.tb_next
1267 return framelist
1268
Benjamin Peterson42ac4752010-08-09 13:05:35 +00001269def currentframe():
Benjamin Petersona3a3fc62010-08-09 15:49:56 +00001270 """Return the frame of the caller or None if this is not possible."""
Benjamin Peterson42ac4752010-08-09 13:05:35 +00001271 return sys._getframe(1) if hasattr(sys, "_getframe") else None
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001272
1273def stack(context=1):
1274 """Return a list of records for the stack above the caller's frame."""
Jeremy Hyltonab919022003-06-27 18:41:20 +00001275 return getouterframes(sys._getframe(1), context)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001276
1277def trace(context=1):
Tim Peters85ba6732001-02-28 08:26:44 +00001278 """Return a list of records for the stack below the current exception."""
Fred Draked451ec12002-04-26 02:29:55 +00001279 return getinnerframes(sys.exc_info()[2], context)
Michael Foord95fc51d2010-11-20 15:07:30 +00001280
1281
1282# ------------------------------------------------ static version of getattr
1283
1284_sentinel = object()
1285
Michael Foorde5162652010-11-20 16:40:44 +00001286def _static_getmro(klass):
1287 return type.__dict__['__mro__'].__get__(klass)
1288
Michael Foord95fc51d2010-11-20 15:07:30 +00001289def _check_instance(obj, attr):
1290 instance_dict = {}
1291 try:
1292 instance_dict = object.__getattribute__(obj, "__dict__")
1293 except AttributeError:
1294 pass
Michael Foorddcebe0f2011-03-15 19:20:44 -04001295 return dict.get(instance_dict, attr, _sentinel)
Michael Foord95fc51d2010-11-20 15:07:30 +00001296
1297
1298def _check_class(klass, attr):
Michael Foorde5162652010-11-20 16:40:44 +00001299 for entry in _static_getmro(klass):
Michael Foorda51623b2011-12-18 22:01:40 +00001300 if _shadowed_dict(type(entry)) is _sentinel:
Michael Foorddcebe0f2011-03-15 19:20:44 -04001301 try:
1302 return entry.__dict__[attr]
1303 except KeyError:
1304 pass
Michael Foord95fc51d2010-11-20 15:07:30 +00001305 return _sentinel
1306
Michael Foord35184ed2010-11-20 16:58:30 +00001307def _is_type(obj):
1308 try:
1309 _static_getmro(obj)
1310 except TypeError:
1311 return False
1312 return True
1313
Michael Foorddcebe0f2011-03-15 19:20:44 -04001314def _shadowed_dict(klass):
1315 dict_attr = type.__dict__["__dict__"]
1316 for entry in _static_getmro(klass):
1317 try:
1318 class_dict = dict_attr.__get__(entry)["__dict__"]
1319 except KeyError:
1320 pass
1321 else:
1322 if not (type(class_dict) is types.GetSetDescriptorType and
1323 class_dict.__name__ == "__dict__" and
1324 class_dict.__objclass__ is entry):
Michael Foorda51623b2011-12-18 22:01:40 +00001325 return class_dict
1326 return _sentinel
Michael Foord95fc51d2010-11-20 15:07:30 +00001327
1328def getattr_static(obj, attr, default=_sentinel):
1329 """Retrieve attributes without triggering dynamic lookup via the
1330 descriptor protocol, __getattr__ or __getattribute__.
1331
1332 Note: this function may not be able to retrieve all attributes
1333 that getattr can fetch (like dynamically created attributes)
1334 and may find attributes that getattr can't (like descriptors
1335 that raise AttributeError). It can also return descriptor objects
1336 instead of instance members in some cases. See the
1337 documentation for details.
1338 """
1339 instance_result = _sentinel
Michael Foord35184ed2010-11-20 16:58:30 +00001340 if not _is_type(obj):
Michael Foordcc7ebb82010-11-20 16:20:16 +00001341 klass = type(obj)
Michael Foorda51623b2011-12-18 22:01:40 +00001342 dict_attr = _shadowed_dict(klass)
1343 if (dict_attr is _sentinel or
1344 type(dict_attr) is types.MemberDescriptorType):
Michael Foorddcebe0f2011-03-15 19:20:44 -04001345 instance_result = _check_instance(obj, attr)
Michael Foord95fc51d2010-11-20 15:07:30 +00001346 else:
1347 klass = obj
1348
1349 klass_result = _check_class(klass, attr)
1350
1351 if instance_result is not _sentinel and klass_result is not _sentinel:
1352 if (_check_class(type(klass_result), '__get__') is not _sentinel and
1353 _check_class(type(klass_result), '__set__') is not _sentinel):
1354 return klass_result
1355
1356 if instance_result is not _sentinel:
1357 return instance_result
1358 if klass_result is not _sentinel:
1359 return klass_result
1360
1361 if obj is klass:
1362 # for types we check the metaclass too
Michael Foorde5162652010-11-20 16:40:44 +00001363 for entry in _static_getmro(type(klass)):
Michael Foord3ba95f82011-12-22 01:13:37 +00001364 if _shadowed_dict(type(entry)) is _sentinel:
1365 try:
1366 return entry.__dict__[attr]
1367 except KeyError:
1368 pass
Michael Foord95fc51d2010-11-20 15:07:30 +00001369 if default is not _sentinel:
1370 return default
1371 raise AttributeError(attr)
Nick Coghlane0f04652010-11-21 03:44:04 +00001372
1373
Nick Coghlan04e2e3f2012-06-23 19:52:05 +10001374# ------------------------------------------------ generator introspection
1375
Nick Coghlan7921b9f2010-11-30 06:36:04 +00001376GEN_CREATED = 'GEN_CREATED'
1377GEN_RUNNING = 'GEN_RUNNING'
1378GEN_SUSPENDED = 'GEN_SUSPENDED'
1379GEN_CLOSED = 'GEN_CLOSED'
Nick Coghlane0f04652010-11-21 03:44:04 +00001380
1381def getgeneratorstate(generator):
1382 """Get current state of a generator-iterator.
1383
1384 Possible states are:
1385 GEN_CREATED: Waiting to start execution.
1386 GEN_RUNNING: Currently being executed by the interpreter.
1387 GEN_SUSPENDED: Currently suspended at a yield expression.
1388 GEN_CLOSED: Execution has completed.
1389 """
1390 if generator.gi_running:
1391 return GEN_RUNNING
1392 if generator.gi_frame is None:
1393 return GEN_CLOSED
1394 if generator.gi_frame.f_lasti == -1:
1395 return GEN_CREATED
1396 return GEN_SUSPENDED
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07001397
1398
Nick Coghlan04e2e3f2012-06-23 19:52:05 +10001399def getgeneratorlocals(generator):
1400 """
1401 Get the mapping of generator local variables to their current values.
1402
1403 A dict is returned, with the keys the local variable names and values the
1404 bound values."""
1405
1406 if not isgenerator(generator):
1407 raise TypeError("'{!r}' is not a Python generator".format(generator))
1408
1409 frame = getattr(generator, "gi_frame", None)
1410 if frame is not None:
1411 return generator.gi_frame.f_locals
1412 else:
1413 return {}
1414
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07001415###############################################################################
1416### Function Signature Object (PEP 362)
1417###############################################################################
1418
1419
1420_WrapperDescriptor = type(type.__call__)
1421_MethodWrapper = type(all.__call__)
1422
1423_NonUserDefinedCallables = (_WrapperDescriptor,
1424 _MethodWrapper,
1425 types.BuiltinFunctionType)
1426
1427
1428def _get_user_defined_method(cls, method_name):
1429 try:
1430 meth = getattr(cls, method_name)
1431 except AttributeError:
1432 return
1433 else:
1434 if not isinstance(meth, _NonUserDefinedCallables):
1435 # Once '__signature__' will be added to 'C'-level
1436 # callables, this check won't be necessary
1437 return meth
1438
1439
1440def signature(obj):
1441 '''Get a signature object for the passed callable.'''
1442
1443 if not callable(obj):
1444 raise TypeError('{!r} is not a callable object'.format(obj))
1445
1446 if isinstance(obj, types.MethodType):
1447 # In this case we skip the first parameter of the underlying
1448 # function (usually `self` or `cls`).
1449 sig = signature(obj.__func__)
1450 return sig.replace(parameters=tuple(sig.parameters.values())[1:])
1451
Nick Coghlane8c45d62013-07-28 20:00:01 +10001452 # Was this function wrapped by a decorator?
1453 obj = unwrap(obj, stop=(lambda f: hasattr(f, "__signature__")))
1454
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07001455 try:
1456 sig = obj.__signature__
1457 except AttributeError:
1458 pass
1459 else:
1460 if sig is not None:
1461 return sig
1462
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07001463
1464 if isinstance(obj, types.FunctionType):
1465 return Signature.from_function(obj)
1466
Larry Hastings44e2eaa2013-11-23 15:37:55 -08001467 if isinstance(obj, types.BuiltinFunctionType):
1468 return Signature.from_builtin(obj)
1469
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07001470 if isinstance(obj, functools.partial):
1471 sig = signature(obj.func)
1472
1473 new_params = OrderedDict(sig.parameters.items())
1474
1475 partial_args = obj.args or ()
1476 partial_keywords = obj.keywords or {}
1477 try:
1478 ba = sig.bind_partial(*partial_args, **partial_keywords)
1479 except TypeError as ex:
1480 msg = 'partial object {!r} has incorrect arguments'.format(obj)
1481 raise ValueError(msg) from ex
1482
1483 for arg_name, arg_value in ba.arguments.items():
1484 param = new_params[arg_name]
1485 if arg_name in partial_keywords:
1486 # We set a new default value, because the following code
1487 # is correct:
1488 #
1489 # >>> def foo(a): print(a)
1490 # >>> print(partial(partial(foo, a=10), a=20)())
1491 # 20
1492 # >>> print(partial(partial(foo, a=10), a=20)(a=30))
1493 # 30
1494 #
1495 # So, with 'partial' objects, passing a keyword argument is
1496 # like setting a new default value for the corresponding
1497 # parameter
1498 #
1499 # We also mark this parameter with '_partial_kwarg'
1500 # flag. Later, in '_bind', the 'default' value of this
1501 # parameter will be added to 'kwargs', to simulate
1502 # the 'functools.partial' real call.
1503 new_params[arg_name] = param.replace(default=arg_value,
1504 _partial_kwarg=True)
1505
1506 elif (param.kind not in (_VAR_KEYWORD, _VAR_POSITIONAL) and
1507 not param._partial_kwarg):
1508 new_params.pop(arg_name)
1509
1510 return sig.replace(parameters=new_params.values())
1511
1512 sig = None
1513 if isinstance(obj, type):
1514 # obj is a class or a metaclass
1515
1516 # First, let's see if it has an overloaded __call__ defined
1517 # in its metaclass
1518 call = _get_user_defined_method(type(obj), '__call__')
1519 if call is not None:
1520 sig = signature(call)
1521 else:
1522 # Now we check if the 'obj' class has a '__new__' method
1523 new = _get_user_defined_method(obj, '__new__')
1524 if new is not None:
1525 sig = signature(new)
1526 else:
1527 # Finally, we should have at least __init__ implemented
1528 init = _get_user_defined_method(obj, '__init__')
1529 if init is not None:
1530 sig = signature(init)
1531 elif not isinstance(obj, _NonUserDefinedCallables):
1532 # An object with __call__
1533 # We also check that the 'obj' is not an instance of
1534 # _WrapperDescriptor or _MethodWrapper to avoid
1535 # infinite recursion (and even potential segfault)
1536 call = _get_user_defined_method(type(obj), '__call__')
1537 if call is not None:
1538 sig = signature(call)
1539
1540 if sig is not None:
1541 # For classes and objects we skip the first parameter of their
1542 # __call__, __new__, or __init__ methods
1543 return sig.replace(parameters=tuple(sig.parameters.values())[1:])
1544
1545 if isinstance(obj, types.BuiltinFunctionType):
1546 # Raise a nicer error message for builtins
1547 msg = 'no signature found for builtin function {!r}'.format(obj)
1548 raise ValueError(msg)
1549
1550 raise ValueError('callable {!r} is not supported by signature'.format(obj))
1551
1552
1553class _void:
1554 '''A private marker - used in Parameter & Signature'''
1555
1556
1557class _empty:
1558 pass
1559
1560
1561class _ParameterKind(int):
1562 def __new__(self, *args, name):
1563 obj = int.__new__(self, *args)
1564 obj._name = name
1565 return obj
1566
1567 def __str__(self):
1568 return self._name
1569
1570 def __repr__(self):
1571 return '<_ParameterKind: {!r}>'.format(self._name)
1572
1573
1574_POSITIONAL_ONLY = _ParameterKind(0, name='POSITIONAL_ONLY')
1575_POSITIONAL_OR_KEYWORD = _ParameterKind(1, name='POSITIONAL_OR_KEYWORD')
1576_VAR_POSITIONAL = _ParameterKind(2, name='VAR_POSITIONAL')
1577_KEYWORD_ONLY = _ParameterKind(3, name='KEYWORD_ONLY')
1578_VAR_KEYWORD = _ParameterKind(4, name='VAR_KEYWORD')
1579
1580
1581class Parameter:
1582 '''Represents a parameter in a function signature.
1583
1584 Has the following public attributes:
1585
1586 * name : str
1587 The name of the parameter as a string.
1588 * default : object
1589 The default value for the parameter if specified. If the
1590 parameter has no default value, this attribute is not set.
1591 * annotation
1592 The annotation for the parameter if specified. If the
1593 parameter has no annotation, this attribute is not set.
1594 * kind : str
1595 Describes how argument values are bound to the parameter.
1596 Possible values: `Parameter.POSITIONAL_ONLY`,
1597 `Parameter.POSITIONAL_OR_KEYWORD`, `Parameter.VAR_POSITIONAL`,
1598 `Parameter.KEYWORD_ONLY`, `Parameter.VAR_KEYWORD`.
1599 '''
1600
1601 __slots__ = ('_name', '_kind', '_default', '_annotation', '_partial_kwarg')
1602
1603 POSITIONAL_ONLY = _POSITIONAL_ONLY
1604 POSITIONAL_OR_KEYWORD = _POSITIONAL_OR_KEYWORD
1605 VAR_POSITIONAL = _VAR_POSITIONAL
1606 KEYWORD_ONLY = _KEYWORD_ONLY
1607 VAR_KEYWORD = _VAR_KEYWORD
1608
1609 empty = _empty
1610
1611 def __init__(self, name, kind, *, default=_empty, annotation=_empty,
1612 _partial_kwarg=False):
1613
1614 if kind not in (_POSITIONAL_ONLY, _POSITIONAL_OR_KEYWORD,
1615 _VAR_POSITIONAL, _KEYWORD_ONLY, _VAR_KEYWORD):
1616 raise ValueError("invalid value for 'Parameter.kind' attribute")
1617 self._kind = kind
1618
1619 if default is not _empty:
1620 if kind in (_VAR_POSITIONAL, _VAR_KEYWORD):
1621 msg = '{} parameters cannot have default values'.format(kind)
1622 raise ValueError(msg)
1623 self._default = default
1624 self._annotation = annotation
1625
1626 if name is None:
1627 if kind != _POSITIONAL_ONLY:
1628 raise ValueError("None is not a valid name for a "
1629 "non-positional-only parameter")
1630 self._name = name
1631 else:
1632 name = str(name)
1633 if kind != _POSITIONAL_ONLY and not name.isidentifier():
1634 msg = '{!r} is not a valid parameter name'.format(name)
1635 raise ValueError(msg)
1636 self._name = name
1637
1638 self._partial_kwarg = _partial_kwarg
1639
1640 @property
1641 def name(self):
1642 return self._name
1643
1644 @property
1645 def default(self):
1646 return self._default
1647
1648 @property
1649 def annotation(self):
1650 return self._annotation
1651
1652 @property
1653 def kind(self):
1654 return self._kind
1655
1656 def replace(self, *, name=_void, kind=_void, annotation=_void,
1657 default=_void, _partial_kwarg=_void):
1658 '''Creates a customized copy of the Parameter.'''
1659
1660 if name is _void:
1661 name = self._name
1662
1663 if kind is _void:
1664 kind = self._kind
1665
1666 if annotation is _void:
1667 annotation = self._annotation
1668
1669 if default is _void:
1670 default = self._default
1671
1672 if _partial_kwarg is _void:
1673 _partial_kwarg = self._partial_kwarg
1674
1675 return type(self)(name, kind, default=default, annotation=annotation,
1676 _partial_kwarg=_partial_kwarg)
1677
1678 def __str__(self):
1679 kind = self.kind
1680
1681 formatted = self._name
1682 if kind == _POSITIONAL_ONLY:
1683 if formatted is None:
1684 formatted = ''
1685 formatted = '<{}>'.format(formatted)
1686
1687 # Add annotation and default value
1688 if self._annotation is not _empty:
1689 formatted = '{}:{}'.format(formatted,
1690 formatannotation(self._annotation))
1691
1692 if self._default is not _empty:
1693 formatted = '{}={}'.format(formatted, repr(self._default))
1694
1695 if kind == _VAR_POSITIONAL:
1696 formatted = '*' + formatted
1697 elif kind == _VAR_KEYWORD:
1698 formatted = '**' + formatted
1699
1700 return formatted
1701
1702 def __repr__(self):
1703 return '<{} at {:#x} {!r}>'.format(self.__class__.__name__,
1704 id(self), self.name)
1705
1706 def __eq__(self, other):
1707 return (issubclass(other.__class__, Parameter) and
1708 self._name == other._name and
1709 self._kind == other._kind and
1710 self._default == other._default and
1711 self._annotation == other._annotation)
1712
1713 def __ne__(self, other):
1714 return not self.__eq__(other)
1715
1716
1717class BoundArguments:
1718 '''Result of `Signature.bind` call. Holds the mapping of arguments
1719 to the function's parameters.
1720
1721 Has the following public attributes:
1722
1723 * arguments : OrderedDict
1724 An ordered mutable mapping of parameters' names to arguments' values.
1725 Does not contain arguments' default values.
1726 * signature : Signature
1727 The Signature object that created this instance.
1728 * args : tuple
1729 Tuple of positional arguments values.
1730 * kwargs : dict
1731 Dict of keyword arguments values.
1732 '''
1733
1734 def __init__(self, signature, arguments):
1735 self.arguments = arguments
1736 self._signature = signature
1737
1738 @property
1739 def signature(self):
1740 return self._signature
1741
1742 @property
1743 def args(self):
1744 args = []
1745 for param_name, param in self._signature.parameters.items():
1746 if (param.kind in (_VAR_KEYWORD, _KEYWORD_ONLY) or
1747 param._partial_kwarg):
1748 # Keyword arguments mapped by 'functools.partial'
1749 # (Parameter._partial_kwarg is True) are mapped
1750 # in 'BoundArguments.kwargs', along with VAR_KEYWORD &
1751 # KEYWORD_ONLY
1752 break
1753
1754 try:
1755 arg = self.arguments[param_name]
1756 except KeyError:
1757 # We're done here. Other arguments
1758 # will be mapped in 'BoundArguments.kwargs'
1759 break
1760 else:
1761 if param.kind == _VAR_POSITIONAL:
1762 # *args
1763 args.extend(arg)
1764 else:
1765 # plain argument
1766 args.append(arg)
1767
1768 return tuple(args)
1769
1770 @property
1771 def kwargs(self):
1772 kwargs = {}
1773 kwargs_started = False
1774 for param_name, param in self._signature.parameters.items():
1775 if not kwargs_started:
1776 if (param.kind in (_VAR_KEYWORD, _KEYWORD_ONLY) or
1777 param._partial_kwarg):
1778 kwargs_started = True
1779 else:
1780 if param_name not in self.arguments:
1781 kwargs_started = True
1782 continue
1783
1784 if not kwargs_started:
1785 continue
1786
1787 try:
1788 arg = self.arguments[param_name]
1789 except KeyError:
1790 pass
1791 else:
1792 if param.kind == _VAR_KEYWORD:
1793 # **kwargs
1794 kwargs.update(arg)
1795 else:
1796 # plain keyword argument
1797 kwargs[param_name] = arg
1798
1799 return kwargs
1800
1801 def __eq__(self, other):
1802 return (issubclass(other.__class__, BoundArguments) and
1803 self.signature == other.signature and
1804 self.arguments == other.arguments)
1805
1806 def __ne__(self, other):
1807 return not self.__eq__(other)
1808
1809
1810class Signature:
1811 '''A Signature object represents the overall signature of a function.
1812 It stores a Parameter object for each parameter accepted by the
1813 function, as well as information specific to the function itself.
1814
1815 A Signature object has the following public attributes and methods:
1816
1817 * parameters : OrderedDict
1818 An ordered mapping of parameters' names to the corresponding
1819 Parameter objects (keyword-only arguments are in the same order
1820 as listed in `code.co_varnames`).
1821 * return_annotation : object
1822 The annotation for the return type of the function if specified.
1823 If the function has no annotation for its return type, this
1824 attribute is not set.
1825 * bind(*args, **kwargs) -> BoundArguments
1826 Creates a mapping from positional and keyword arguments to
1827 parameters.
1828 * bind_partial(*args, **kwargs) -> BoundArguments
1829 Creates a partial mapping from positional and keyword arguments
1830 to parameters (simulating 'functools.partial' behavior.)
1831 '''
1832
1833 __slots__ = ('_return_annotation', '_parameters')
1834
1835 _parameter_cls = Parameter
1836 _bound_arguments_cls = BoundArguments
1837
1838 empty = _empty
1839
1840 def __init__(self, parameters=None, *, return_annotation=_empty,
1841 __validate_parameters__=True):
1842 '''Constructs Signature from the given list of Parameter
1843 objects and 'return_annotation'. All arguments are optional.
1844 '''
1845
1846 if parameters is None:
1847 params = OrderedDict()
1848 else:
1849 if __validate_parameters__:
1850 params = OrderedDict()
1851 top_kind = _POSITIONAL_ONLY
1852
1853 for idx, param in enumerate(parameters):
1854 kind = param.kind
1855 if kind < top_kind:
1856 msg = 'wrong parameter order: {} before {}'
1857 msg = msg.format(top_kind, param.kind)
1858 raise ValueError(msg)
1859 else:
1860 top_kind = kind
1861
1862 name = param.name
1863 if name is None:
1864 name = str(idx)
1865 param = param.replace(name=name)
1866
1867 if name in params:
1868 msg = 'duplicate parameter name: {!r}'.format(name)
1869 raise ValueError(msg)
1870 params[name] = param
1871 else:
1872 params = OrderedDict(((param.name, param)
1873 for param in parameters))
1874
1875 self._parameters = types.MappingProxyType(params)
1876 self._return_annotation = return_annotation
1877
1878 @classmethod
1879 def from_function(cls, func):
1880 '''Constructs Signature for the given python function'''
1881
1882 if not isinstance(func, types.FunctionType):
1883 raise TypeError('{!r} is not a Python function'.format(func))
1884
1885 Parameter = cls._parameter_cls
1886
1887 # Parameter information.
1888 func_code = func.__code__
1889 pos_count = func_code.co_argcount
1890 arg_names = func_code.co_varnames
1891 positional = tuple(arg_names[:pos_count])
1892 keyword_only_count = func_code.co_kwonlyargcount
1893 keyword_only = arg_names[pos_count:(pos_count + keyword_only_count)]
1894 annotations = func.__annotations__
1895 defaults = func.__defaults__
1896 kwdefaults = func.__kwdefaults__
1897
1898 if defaults:
1899 pos_default_count = len(defaults)
1900 else:
1901 pos_default_count = 0
1902
1903 parameters = []
1904
1905 # Non-keyword-only parameters w/o defaults.
1906 non_default_count = pos_count - pos_default_count
1907 for name in positional[:non_default_count]:
1908 annotation = annotations.get(name, _empty)
1909 parameters.append(Parameter(name, annotation=annotation,
1910 kind=_POSITIONAL_OR_KEYWORD))
1911
1912 # ... w/ defaults.
1913 for offset, name in enumerate(positional[non_default_count:]):
1914 annotation = annotations.get(name, _empty)
1915 parameters.append(Parameter(name, annotation=annotation,
1916 kind=_POSITIONAL_OR_KEYWORD,
1917 default=defaults[offset]))
1918
1919 # *args
1920 if func_code.co_flags & 0x04:
1921 name = arg_names[pos_count + keyword_only_count]
1922 annotation = annotations.get(name, _empty)
1923 parameters.append(Parameter(name, annotation=annotation,
1924 kind=_VAR_POSITIONAL))
1925
1926 # Keyword-only parameters.
1927 for name in keyword_only:
1928 default = _empty
1929 if kwdefaults is not None:
1930 default = kwdefaults.get(name, _empty)
1931
1932 annotation = annotations.get(name, _empty)
1933 parameters.append(Parameter(name, annotation=annotation,
1934 kind=_KEYWORD_ONLY,
1935 default=default))
1936 # **kwargs
1937 if func_code.co_flags & 0x08:
1938 index = pos_count + keyword_only_count
1939 if func_code.co_flags & 0x04:
1940 index += 1
1941
1942 name = arg_names[index]
1943 annotation = annotations.get(name, _empty)
1944 parameters.append(Parameter(name, annotation=annotation,
1945 kind=_VAR_KEYWORD))
1946
1947 return cls(parameters,
1948 return_annotation=annotations.get('return', _empty),
1949 __validate_parameters__=False)
1950
Larry Hastings44e2eaa2013-11-23 15:37:55 -08001951 @classmethod
1952 def from_builtin(cls, func):
1953 s = getattr(func, "__text_signature__", None)
1954 if not s:
1955 return None
1956
Larry Hastings2a727912014-01-16 11:32:01 -08001957 Parameter = cls._parameter_cls
1958
Larry Hastings44e2eaa2013-11-23 15:37:55 -08001959 if s.endswith("/)"):
1960 kind = Parameter.POSITIONAL_ONLY
1961 s = s[:-2] + ')'
1962 else:
1963 kind = Parameter.POSITIONAL_OR_KEYWORD
1964
1965 s = "def foo" + s + ": pass"
1966
1967 try:
1968 module = ast.parse(s)
1969 except SyntaxError:
1970 return None
1971 if not isinstance(module, ast.Module):
1972 return None
1973
Larry Hastings44e2eaa2013-11-23 15:37:55 -08001974 f = module.body[0]
1975
1976 parameters = []
1977 empty = Parameter.empty
Larry Hastings16c51912014-01-07 11:53:01 -08001978 invalid = object()
1979
Larry Hastings2a727912014-01-16 11:32:01 -08001980 module = None
1981 module_dict = {}
1982 module_name = getattr(func, '__module__', None)
1983 if module_name:
1984 module = sys.modules.get(module_name, None)
1985 if module:
1986 module_dict = module.__dict__
1987 sys_module_dict = sys.modules
Larry Hastings16c51912014-01-07 11:53:01 -08001988
Larry Hastings2a727912014-01-16 11:32:01 -08001989 def parse_name(node):
1990 assert isinstance(node, ast.arg)
1991 if node.annotation != None:
1992 raise ValueError("Annotations are not currently supported")
1993 return node.arg
Larry Hastings16c51912014-01-07 11:53:01 -08001994
Larry Hastings2a727912014-01-16 11:32:01 -08001995 def wrap_value(s):
1996 try:
1997 value = eval(s, module_dict)
1998 except NameError:
1999 try:
2000 value = eval(s, sys_module_dict)
2001 except NameError:
2002 raise RuntimeError()
Larry Hastings16c51912014-01-07 11:53:01 -08002003
Larry Hastings2a727912014-01-16 11:32:01 -08002004 if isinstance(value, str):
2005 return ast.Str(value)
2006 if isinstance(value, (int, float)):
2007 return ast.Num(value)
2008 if isinstance(value, bytes):
2009 return ast.Bytes(value)
2010 if value in (True, False, None):
2011 return ast.NameConstant(value)
2012 raise RuntimeError()
Larry Hastings16c51912014-01-07 11:53:01 -08002013
Larry Hastings2a727912014-01-16 11:32:01 -08002014 class RewriteSymbolics(ast.NodeTransformer):
2015 def visit_Attribute(self, node):
2016 a = []
2017 n = node
2018 while isinstance(n, ast.Attribute):
2019 a.append(n.attr)
2020 n = n.value
2021 if not isinstance(n, ast.Name):
2022 raise RuntimeError()
2023 a.append(n.id)
2024 value = ".".join(reversed(a))
2025 return wrap_value(value)
2026
2027 def visit_Name(self, node):
Larry Hastings16c51912014-01-07 11:53:01 -08002028 if not isinstance(node.ctx, ast.Load):
Larry Hastings2a727912014-01-16 11:32:01 -08002029 raise ValueError()
2030 return wrap_value(node.id)
Larry Hastings44e2eaa2013-11-23 15:37:55 -08002031
2032 def p(name_node, default_node, default=empty):
Larry Hastings2a727912014-01-16 11:32:01 -08002033 name = parse_name(name_node)
Larry Hastings16c51912014-01-07 11:53:01 -08002034 if name is invalid:
2035 return None
2036 if default_node:
Larry Hastings2a727912014-01-16 11:32:01 -08002037 try:
2038 default_node = RewriteSymbolics().visit(default_node)
2039 o = ast.literal_eval(default_node)
2040 except ValueError:
2041 o = invalid
Larry Hastings16c51912014-01-07 11:53:01 -08002042 if o is invalid:
2043 return None
2044 default = o if o is not invalid else default
Larry Hastings44e2eaa2013-11-23 15:37:55 -08002045 parameters.append(Parameter(name, kind, default=default, annotation=empty))
2046
2047 # non-keyword-only parameters
Larry Hastings16c51912014-01-07 11:53:01 -08002048 args = reversed(f.args.args)
2049 defaults = reversed(f.args.defaults)
2050 iter = itertools.zip_longest(args, defaults, fillvalue=None)
2051 for name, default in reversed(list(iter)):
Larry Hastings44e2eaa2013-11-23 15:37:55 -08002052 p(name, default)
2053
2054 # *args
2055 if f.args.vararg:
2056 kind = Parameter.VAR_POSITIONAL
2057 p(f.args.vararg, empty)
2058
2059 # keyword-only arguments
2060 kind = Parameter.KEYWORD_ONLY
2061 for name, default in zip(f.args.kwonlyargs, f.args.kw_defaults):
2062 p(name, default)
2063
2064 # **kwargs
2065 if f.args.kwarg:
2066 kind = Parameter.VAR_KEYWORD
2067 p(f.args.kwarg, empty)
2068
2069 return cls(parameters, return_annotation=cls.empty)
2070
2071
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002072 @property
2073 def parameters(self):
2074 return self._parameters
2075
2076 @property
2077 def return_annotation(self):
2078 return self._return_annotation
2079
2080 def replace(self, *, parameters=_void, return_annotation=_void):
2081 '''Creates a customized copy of the Signature.
2082 Pass 'parameters' and/or 'return_annotation' arguments
2083 to override them in the new copy.
2084 '''
2085
2086 if parameters is _void:
2087 parameters = self.parameters.values()
2088
2089 if return_annotation is _void:
2090 return_annotation = self._return_annotation
2091
2092 return type(self)(parameters,
2093 return_annotation=return_annotation)
2094
2095 def __eq__(self, other):
2096 if (not issubclass(type(other), Signature) or
2097 self.return_annotation != other.return_annotation or
2098 len(self.parameters) != len(other.parameters)):
2099 return False
2100
2101 other_positions = {param: idx
2102 for idx, param in enumerate(other.parameters.keys())}
2103
2104 for idx, (param_name, param) in enumerate(self.parameters.items()):
2105 if param.kind == _KEYWORD_ONLY:
2106 try:
2107 other_param = other.parameters[param_name]
2108 except KeyError:
2109 return False
2110 else:
2111 if param != other_param:
2112 return False
2113 else:
2114 try:
2115 other_idx = other_positions[param_name]
2116 except KeyError:
2117 return False
2118 else:
2119 if (idx != other_idx or
2120 param != other.parameters[param_name]):
2121 return False
2122
2123 return True
2124
2125 def __ne__(self, other):
2126 return not self.__eq__(other)
2127
2128 def _bind(self, args, kwargs, *, partial=False):
2129 '''Private method. Don't use directly.'''
2130
2131 arguments = OrderedDict()
2132
2133 parameters = iter(self.parameters.values())
2134 parameters_ex = ()
2135 arg_vals = iter(args)
2136
2137 if partial:
2138 # Support for binding arguments to 'functools.partial' objects.
2139 # See 'functools.partial' case in 'signature()' implementation
2140 # for details.
2141 for param_name, param in self.parameters.items():
2142 if (param._partial_kwarg and param_name not in kwargs):
2143 # Simulating 'functools.partial' behavior
2144 kwargs[param_name] = param.default
2145
2146 while True:
2147 # Let's iterate through the positional arguments and corresponding
2148 # parameters
2149 try:
2150 arg_val = next(arg_vals)
2151 except StopIteration:
2152 # No more positional arguments
2153 try:
2154 param = next(parameters)
2155 except StopIteration:
2156 # No more parameters. That's it. Just need to check that
2157 # we have no `kwargs` after this while loop
2158 break
2159 else:
2160 if param.kind == _VAR_POSITIONAL:
2161 # That's OK, just empty *args. Let's start parsing
2162 # kwargs
2163 break
2164 elif param.name in kwargs:
2165 if param.kind == _POSITIONAL_ONLY:
2166 msg = '{arg!r} parameter is positional only, ' \
2167 'but was passed as a keyword'
2168 msg = msg.format(arg=param.name)
2169 raise TypeError(msg) from None
2170 parameters_ex = (param,)
2171 break
2172 elif (param.kind == _VAR_KEYWORD or
2173 param.default is not _empty):
2174 # That's fine too - we have a default value for this
2175 # parameter. So, lets start parsing `kwargs`, starting
2176 # with the current parameter
2177 parameters_ex = (param,)
2178 break
2179 else:
2180 if partial:
2181 parameters_ex = (param,)
2182 break
2183 else:
2184 msg = '{arg!r} parameter lacking default value'
2185 msg = msg.format(arg=param.name)
2186 raise TypeError(msg) from None
2187 else:
2188 # We have a positional argument to process
2189 try:
2190 param = next(parameters)
2191 except StopIteration:
2192 raise TypeError('too many positional arguments') from None
2193 else:
2194 if param.kind in (_VAR_KEYWORD, _KEYWORD_ONLY):
2195 # Looks like we have no parameter for this positional
2196 # argument
2197 raise TypeError('too many positional arguments')
2198
2199 if param.kind == _VAR_POSITIONAL:
2200 # We have an '*args'-like argument, let's fill it with
2201 # all positional arguments we have left and move on to
2202 # the next phase
2203 values = [arg_val]
2204 values.extend(arg_vals)
2205 arguments[param.name] = tuple(values)
2206 break
2207
2208 if param.name in kwargs:
2209 raise TypeError('multiple values for argument '
2210 '{arg!r}'.format(arg=param.name))
2211
2212 arguments[param.name] = arg_val
2213
2214 # Now, we iterate through the remaining parameters to process
2215 # keyword arguments
2216 kwargs_param = None
2217 for param in itertools.chain(parameters_ex, parameters):
2218 if param.kind == _POSITIONAL_ONLY:
2219 # This should never happen in case of a properly built
2220 # Signature object (but let's have this check here
2221 # to ensure correct behaviour just in case)
2222 raise TypeError('{arg!r} parameter is positional only, '
2223 'but was passed as a keyword'. \
2224 format(arg=param.name))
2225
2226 if param.kind == _VAR_KEYWORD:
2227 # Memorize that we have a '**kwargs'-like parameter
2228 kwargs_param = param
2229 continue
2230
2231 param_name = param.name
2232 try:
2233 arg_val = kwargs.pop(param_name)
2234 except KeyError:
2235 # We have no value for this parameter. It's fine though,
2236 # if it has a default value, or it is an '*args'-like
2237 # parameter, left alone by the processing of positional
2238 # arguments.
2239 if (not partial and param.kind != _VAR_POSITIONAL and
2240 param.default is _empty):
2241 raise TypeError('{arg!r} parameter lacking default value'. \
2242 format(arg=param_name)) from None
2243
2244 else:
2245 arguments[param_name] = arg_val
2246
2247 if kwargs:
2248 if kwargs_param is not None:
2249 # Process our '**kwargs'-like parameter
2250 arguments[kwargs_param.name] = kwargs
2251 else:
2252 raise TypeError('too many keyword arguments')
2253
2254 return self._bound_arguments_cls(self, arguments)
2255
Antoine Pitroubd41d1b2013-01-29 21:20:57 +01002256 def bind(__bind_self, *args, **kwargs):
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002257 '''Get a BoundArguments object, that maps the passed `args`
2258 and `kwargs` to the function's signature. Raises `TypeError`
2259 if the passed arguments can not be bound.
2260 '''
Antoine Pitroubd41d1b2013-01-29 21:20:57 +01002261 return __bind_self._bind(args, kwargs)
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002262
Antoine Pitroubd41d1b2013-01-29 21:20:57 +01002263 def bind_partial(__bind_self, *args, **kwargs):
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002264 '''Get a BoundArguments object, that partially maps the
2265 passed `args` and `kwargs` to the function's signature.
2266 Raises `TypeError` if the passed arguments can not be bound.
2267 '''
Antoine Pitroubd41d1b2013-01-29 21:20:57 +01002268 return __bind_self._bind(args, kwargs, partial=True)
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002269
2270 def __str__(self):
2271 result = []
2272 render_kw_only_separator = True
2273 for idx, param in enumerate(self.parameters.values()):
2274 formatted = str(param)
2275
2276 kind = param.kind
2277 if kind == _VAR_POSITIONAL:
2278 # OK, we have an '*args'-like parameter, so we won't need
2279 # a '*' to separate keyword-only arguments
2280 render_kw_only_separator = False
2281 elif kind == _KEYWORD_ONLY and render_kw_only_separator:
2282 # We have a keyword-only parameter to render and we haven't
2283 # rendered an '*args'-like parameter before, so add a '*'
2284 # separator to the parameters list ("foo(arg1, *, arg2)" case)
2285 result.append('*')
2286 # This condition should be only triggered once, so
2287 # reset the flag
2288 render_kw_only_separator = False
2289
2290 result.append(formatted)
2291
2292 rendered = '({})'.format(', '.join(result))
2293
2294 if self.return_annotation is not _empty:
2295 anno = formatannotation(self.return_annotation)
2296 rendered += ' -> {}'.format(anno)
2297
2298 return rendered
Nick Coghlanf94a16b2013-09-22 22:46:49 +10002299
2300def _main():
2301 """ Logic for inspecting an object given at command line """
2302 import argparse
2303 import importlib
2304
2305 parser = argparse.ArgumentParser()
2306 parser.add_argument(
2307 'object',
2308 help="The object to be analysed. "
2309 "It supports the 'module:qualname' syntax")
2310 parser.add_argument(
2311 '-d', '--details', action='store_true',
2312 help='Display info about the module rather than its source code')
2313
2314 args = parser.parse_args()
2315
2316 target = args.object
2317 mod_name, has_attrs, attrs = target.partition(":")
2318 try:
2319 obj = module = importlib.import_module(mod_name)
2320 except Exception as exc:
2321 msg = "Failed to import {} ({}: {})".format(mod_name,
2322 type(exc).__name__,
2323 exc)
2324 print(msg, file=sys.stderr)
2325 exit(2)
2326
2327 if has_attrs:
2328 parts = attrs.split(".")
2329 obj = module
2330 for part in parts:
2331 obj = getattr(obj, part)
2332
2333 if module.__name__ in sys.builtin_module_names:
2334 print("Can't get info for builtin modules.", file=sys.stderr)
2335 exit(1)
2336
2337 if args.details:
2338 print('Target: {}'.format(target))
2339 print('Origin: {}'.format(getsourcefile(module)))
2340 print('Cached: {}'.format(module.__cached__))
2341 if obj is module:
2342 print('Loader: {}'.format(repr(module.__loader__)))
2343 if hasattr(module, '__path__'):
2344 print('Submodule search path: {}'.format(module.__path__))
2345 else:
2346 try:
2347 __, lineno = findsource(obj)
2348 except Exception:
2349 pass
2350 else:
2351 print('Line: {}'.format(lineno))
2352
2353 print('\n')
2354 else:
2355 print(getsource(obj))
2356
2357
2358if __name__ == "__main__":
2359 _main()