blob: edbf927128afe29cf4319ffb94d68ba85f2a3dc4 [file] [log] [blame]
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001"""Get useful information from live Python objects.
2
3This module encapsulates the interface provided by the internal special
Neal Norwitz221085d2007-02-25 20:55:47 +00004attributes (co_*, im_*, tb_*, etc.) in a friendlier fashion.
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00005It also provides some help for examining source code and class layout.
6
7Here are some of the useful functions provided by this module:
8
Christian Heimes7131fd92008-02-19 14:21:46 +00009 ismodule(), isclass(), ismethod(), isfunction(), isgeneratorfunction(),
10 isgenerator(), istraceback(), isframe(), iscode(), isbuiltin(),
11 isroutine() - check object types
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +000012 getmembers() - get members of an object that satisfy a given condition
13
14 getfile(), getsourcefile(), getsource() - find an object's source code
15 getdoc(), getcomments() - get documentation on an object
16 getmodule() - determine the module that an object came from
17 getclasstree() - arrange classes so as to represent their hierarchy
18
Benjamin Peterson25cd7eb2010-03-30 18:42:32 +000019 getargspec(), getargvalues(), getcallargs() - get info about function arguments
Guido van Rossum2e65f892007-02-28 22:03:49 +000020 getfullargspec() - same, with support for Python-3000 features
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +000021 formatargspec(), formatargvalues() - format an argument spec
22 getouterframes(), getinnerframes() - get info about frames
23 currentframe() - get the current stack frame
24 stack(), trace() - get info about frames on the stack or in a traceback
Larry Hastings7c7cbfc2012-06-22 15:19:35 -070025
26 signature() - get a Signature object for the callable
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +000027"""
28
29# This module is in the public domain. No warranties.
30
Larry Hastings7c7cbfc2012-06-22 15:19:35 -070031__author__ = ('Ka-Ping Yee <ping@lfw.org>',
32 'Yury Selivanov <yselivanov@sprymix.com>')
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +000033
Brett Cannoncb66eb02012-05-11 12:58:42 -040034import importlib.machinery
35import itertools
Christian Heimes7131fd92008-02-19 14:21:46 +000036import linecache
Brett Cannoncb66eb02012-05-11 12:58:42 -040037import os
38import re
39import sys
40import tokenize
41import types
Brett Cannon2b88fcf2012-06-02 22:28:42 -040042import warnings
Larry Hastings7c7cbfc2012-06-22 15:19:35 -070043import functools
Nick Coghlan2f92e542012-06-23 19:39:55 +100044import builtins
Raymond Hettingera1a992c2005-03-11 06:46:45 +000045from operator import attrgetter
Larry Hastings7c7cbfc2012-06-22 15:19:35 -070046from collections import namedtuple, OrderedDict
Nick Coghlan09c81232010-08-17 10:18:16 +000047
48# Create constants for the compiler flags in Include/code.h
49# We try to get them from dis to avoid duplication, but fall
Ezio Melotti30b9d5d2013-08-17 15:50:46 +030050# back to hardcoding so the dependency is optional
Nick Coghlan09c81232010-08-17 10:18:16 +000051try:
52 from dis import COMPILER_FLAG_NAMES as _flag_names
Brett Cannoncd171c82013-07-04 17:43:24 -040053except ImportError:
Nick Coghlan09c81232010-08-17 10:18:16 +000054 CO_OPTIMIZED, CO_NEWLOCALS = 0x1, 0x2
55 CO_VARARGS, CO_VARKEYWORDS = 0x4, 0x8
56 CO_NESTED, CO_GENERATOR, CO_NOFREE = 0x10, 0x20, 0x40
57else:
58 mod_dict = globals()
59 for k, v in _flag_names.items():
60 mod_dict["CO_" + v] = k
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +000061
Christian Heimesbe5b30b2008-03-03 19:18:51 +000062# See Include/object.h
63TPFLAGS_IS_ABSTRACT = 1 << 20
64
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +000065# ----------------------------------------------------------- type-checking
66def ismodule(object):
67 """Return true if the object is a module.
68
69 Module objects provide these attributes:
Barry Warsaw28a691b2010-04-17 00:19:56 +000070 __cached__ pathname to byte compiled file
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +000071 __doc__ documentation string
72 __file__ filename (missing for built-in modules)"""
Tim Peters28bc59f2001-09-16 08:40:16 +000073 return isinstance(object, types.ModuleType)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +000074
75def isclass(object):
76 """Return true if the object is a class.
77
78 Class objects provide these attributes:
79 __doc__ documentation string
80 __module__ name of module in which this class was defined"""
Benjamin Petersonc4656002009-01-17 22:41:18 +000081 return isinstance(object, type)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +000082
83def ismethod(object):
84 """Return true if the object is an instance method.
85
86 Instance method objects provide these attributes:
87 __doc__ documentation string
88 __name__ name with which this method was defined
Christian Heimesff737952007-11-27 10:40:20 +000089 __func__ function object containing implementation of method
90 __self__ instance to which this method is bound"""
Tim Peters28bc59f2001-09-16 08:40:16 +000091 return isinstance(object, types.MethodType)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +000092
Tim Peters536d2262001-09-20 05:13:38 +000093def ismethoddescriptor(object):
Tim Petersf1d90b92001-09-20 05:47:55 +000094 """Return true if the object is a method descriptor.
95
96 But not if ismethod() or isclass() or isfunction() are true.
Tim Peters536d2262001-09-20 05:13:38 +000097
98 This is new in Python 2.2, and, for example, is true of int.__add__.
99 An object passing this test has a __get__ attribute but not a __set__
100 attribute, but beyond that the set of attributes varies. __name__ is
101 usually sensible, and __doc__ often is.
102
Tim Petersf1d90b92001-09-20 05:47:55 +0000103 Methods implemented via descriptors that also pass one of the other
104 tests return false from the ismethoddescriptor() test, simply because
105 the other tests promise more -- you can, e.g., count on having the
Christian Heimesff737952007-11-27 10:40:20 +0000106 __func__ attribute (etc) when an object passes ismethod()."""
Antoine Pitrou86a8a9a2011-12-21 09:57:40 +0100107 if isclass(object) or ismethod(object) or isfunction(object):
108 # mutual exclusion
109 return False
110 tp = type(object)
111 return hasattr(tp, "__get__") and not hasattr(tp, "__set__")
Tim Peters536d2262001-09-20 05:13:38 +0000112
Martin v. Löwise59e2ba2003-05-03 09:09:02 +0000113def isdatadescriptor(object):
114 """Return true if the object is a data descriptor.
115
116 Data descriptors have both a __get__ and a __set__ attribute. Examples are
117 properties (defined in Python) and getsets and members (defined in C).
118 Typically, data descriptors will also have __name__ and __doc__ attributes
119 (properties, getsets, and members have both of these attributes), but this
120 is not guaranteed."""
Antoine Pitrou86a8a9a2011-12-21 09:57:40 +0100121 if isclass(object) or ismethod(object) or isfunction(object):
122 # mutual exclusion
123 return False
124 tp = type(object)
125 return hasattr(tp, "__set__") and hasattr(tp, "__get__")
Martin v. Löwise59e2ba2003-05-03 09:09:02 +0000126
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000127if hasattr(types, 'MemberDescriptorType'):
128 # CPython and equivalent
129 def ismemberdescriptor(object):
130 """Return true if the object is a member descriptor.
131
132 Member descriptors are specialized descriptors defined in extension
133 modules."""
134 return isinstance(object, types.MemberDescriptorType)
135else:
136 # Other implementations
137 def ismemberdescriptor(object):
138 """Return true if the object is a member descriptor.
139
140 Member descriptors are specialized descriptors defined in extension
141 modules."""
142 return False
143
144if hasattr(types, 'GetSetDescriptorType'):
145 # CPython and equivalent
146 def isgetsetdescriptor(object):
147 """Return true if the object is a getset descriptor.
148
149 getset descriptors are specialized descriptors defined in extension
150 modules."""
151 return isinstance(object, types.GetSetDescriptorType)
152else:
153 # Other implementations
154 def isgetsetdescriptor(object):
155 """Return true if the object is a getset descriptor.
156
157 getset descriptors are specialized descriptors defined in extension
158 modules."""
159 return False
160
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000161def isfunction(object):
162 """Return true if the object is a user-defined function.
163
164 Function objects provide these attributes:
165 __doc__ documentation string
166 __name__ name with which this function was defined
Neal Norwitz221085d2007-02-25 20:55:47 +0000167 __code__ code object containing compiled function bytecode
168 __defaults__ tuple of any default values for arguments
169 __globals__ global namespace in which this function was defined
170 __annotations__ dict of parameter annotations
171 __kwdefaults__ dict of keyword only parameters with defaults"""
Tim Peters28bc59f2001-09-16 08:40:16 +0000172 return isinstance(object, types.FunctionType)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000173
Christian Heimes7131fd92008-02-19 14:21:46 +0000174def isgeneratorfunction(object):
175 """Return true if the object is a user-defined generator function.
176
177 Generator function objects provides same attributes as functions.
178
Alexander Belopolsky977a6842010-08-16 20:17:07 +0000179 See help(isfunction) for attributes listing."""
Georg Brandlb1441c72009-01-03 22:33:39 +0000180 return bool((isfunction(object) or ismethod(object)) and
181 object.__code__.co_flags & CO_GENERATOR)
Christian Heimes7131fd92008-02-19 14:21:46 +0000182
183def isgenerator(object):
184 """Return true if the object is a generator.
185
186 Generator objects provide these attributes:
Ezio Melotti30b9d5d2013-08-17 15:50:46 +0300187 __iter__ defined to support iteration over container
Christian Heimes7131fd92008-02-19 14:21:46 +0000188 close raises a new GeneratorExit exception inside the
189 generator to terminate the iteration
190 gi_code code object
191 gi_frame frame object or possibly None once the generator has
192 been exhausted
193 gi_running set to 1 when generator is executing, 0 otherwise
194 next return the next item from the container
195 send resumes the generator and "sends" a value that becomes
196 the result of the current yield-expression
197 throw used to raise an exception inside the generator"""
198 return isinstance(object, types.GeneratorType)
199
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000200def istraceback(object):
201 """Return true if the object is a traceback.
202
203 Traceback objects provide these attributes:
204 tb_frame frame object at this level
205 tb_lasti index of last attempted instruction in bytecode
206 tb_lineno current line number in Python source code
207 tb_next next inner traceback object (called by this level)"""
Tim Peters28bc59f2001-09-16 08:40:16 +0000208 return isinstance(object, types.TracebackType)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000209
210def isframe(object):
211 """Return true if the object is a frame object.
212
213 Frame objects provide these attributes:
214 f_back next outer frame object (this frame's caller)
215 f_builtins built-in namespace seen by this frame
216 f_code code object being executed in this frame
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000217 f_globals global namespace seen by this frame
218 f_lasti index of last attempted instruction in bytecode
219 f_lineno current line number in Python source code
220 f_locals local namespace seen by this frame
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000221 f_trace tracing function for this frame, or None"""
Tim Peters28bc59f2001-09-16 08:40:16 +0000222 return isinstance(object, types.FrameType)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000223
224def iscode(object):
225 """Return true if the object is a code object.
226
227 Code objects provide these attributes:
228 co_argcount number of arguments (not including * or ** args)
229 co_code string of raw compiled bytecode
230 co_consts tuple of constants used in the bytecode
231 co_filename name of file in which this code object was created
232 co_firstlineno number of first line in Python source code
233 co_flags bitmap: 1=optimized | 2=newlocals | 4=*arg | 8=**arg
234 co_lnotab encoded mapping of line numbers to bytecode indices
235 co_name name with which this code object was defined
236 co_names tuple of names of local variables
237 co_nlocals number of local variables
238 co_stacksize virtual machine stack space required
239 co_varnames tuple of names of arguments and local variables"""
Tim Peters28bc59f2001-09-16 08:40:16 +0000240 return isinstance(object, types.CodeType)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000241
242def isbuiltin(object):
243 """Return true if the object is a built-in function or method.
244
245 Built-in functions and methods provide these attributes:
246 __doc__ documentation string
247 __name__ original name of this function or method
248 __self__ instance to which a method is bound, or None"""
Tim Peters28bc59f2001-09-16 08:40:16 +0000249 return isinstance(object, types.BuiltinFunctionType)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000250
251def isroutine(object):
252 """Return true if the object is any kind of function or method."""
Tim Peters536d2262001-09-20 05:13:38 +0000253 return (isbuiltin(object)
254 or isfunction(object)
255 or ismethod(object)
256 or ismethoddescriptor(object))
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000257
Christian Heimesbe5b30b2008-03-03 19:18:51 +0000258def isabstract(object):
259 """Return true if the object is an abstract base class (ABC)."""
Benjamin Petersona0dfa822009-11-13 02:25:08 +0000260 return bool(isinstance(object, type) and object.__flags__ & TPFLAGS_IS_ABSTRACT)
Christian Heimesbe5b30b2008-03-03 19:18:51 +0000261
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000262def getmembers(object, predicate=None):
263 """Return all members of an object as (name, value) pairs sorted by name.
264 Optionally, only return members that satisfy a given predicate."""
Antoine Pitrou86a8a9a2011-12-21 09:57:40 +0100265 if isclass(object):
266 mro = (object,) + getmro(object)
267 else:
268 mro = ()
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000269 results = []
Ethan Furmane03ea372013-09-25 07:14:41 -0700270 processed = set()
271 names = dir(object)
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700272 # :dd any DynamicClassAttributes to the list of names if object is a class;
Ethan Furmane03ea372013-09-25 07:14:41 -0700273 # this may result in duplicate entries if, for example, a virtual
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700274 # attribute with the same name as a DynamicClassAttribute exists
Ethan Furmane03ea372013-09-25 07:14:41 -0700275 try:
276 for base in object.__bases__:
277 for k, v in base.__dict__.items():
278 if isinstance(v, types.DynamicClassAttribute):
279 names.append(k)
280 except AttributeError:
281 pass
282 for key in names:
Ethan Furman63c141c2013-10-18 00:27:39 -0700283 # First try to get the value via getattr. Some descriptors don't
284 # like calling their __get__ (see bug #1785), so fall back to
285 # looking in the __dict__.
286 try:
287 value = getattr(object, key)
288 # handle the duplicate key
289 if key in processed:
290 raise AttributeError
291 except AttributeError:
292 for base in mro:
293 if key in base.__dict__:
294 value = base.__dict__[key]
295 break
296 else:
297 # could be a (currently) missing slot member, or a buggy
298 # __dir__; discard and move on
Antoine Pitrou86a8a9a2011-12-21 09:57:40 +0100299 continue
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000300 if not predicate or predicate(value):
301 results.append((key, value))
Ethan Furmane03ea372013-09-25 07:14:41 -0700302 processed.add(key)
303 results.sort(key=lambda pair: pair[0])
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000304 return results
305
Christian Heimes25bb7832008-01-11 16:17:00 +0000306Attribute = namedtuple('Attribute', 'name kind defining_class object')
307
Tim Peters13b49d32001-09-23 02:00:29 +0000308def classify_class_attrs(cls):
309 """Return list of attribute-descriptor tuples.
310
311 For each name in dir(cls), the return list contains a 4-tuple
312 with these elements:
313
314 0. The name (a string).
315
316 1. The kind of attribute this is, one of these strings:
317 'class method' created via classmethod()
318 'static method' created via staticmethod()
319 'property' created via property()
Ethan Furmane03ea372013-09-25 07:14:41 -0700320 'method' any other flavor of method or descriptor
Tim Peters13b49d32001-09-23 02:00:29 +0000321 'data' not a method
322
323 2. The class which defined this attribute (a class).
324
Ethan Furmane03ea372013-09-25 07:14:41 -0700325 3. The object as obtained by calling getattr; if this fails, or if the
326 resulting object does not live anywhere in the class' mro (including
327 metaclasses) then the object is looked up in the defining class's
328 dict (found by walking the mro).
Ethan Furman668dede2013-09-14 18:53:26 -0700329
330 If one of the items in dir(cls) is stored in the metaclass it will now
331 be discovered and not have None be listed as the class in which it was
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700332 defined. Any items whose home class cannot be discovered are skipped.
Tim Peters13b49d32001-09-23 02:00:29 +0000333 """
334
335 mro = getmro(cls)
Ethan Furman668dede2013-09-14 18:53:26 -0700336 metamro = getmro(type(cls)) # for attributes stored in the metaclass
Ethan Furmane03ea372013-09-25 07:14:41 -0700337 metamro = tuple([cls for cls in metamro if cls not in (type, object)])
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700338 class_bases = (cls,) + mro
339 all_bases = class_bases + metamro
Tim Peters13b49d32001-09-23 02:00:29 +0000340 names = dir(cls)
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700341 # :dd any DynamicClassAttributes to the list of names;
Ethan Furmane03ea372013-09-25 07:14:41 -0700342 # this may result in duplicate entries if, for example, a virtual
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700343 # attribute with the same name as a DynamicClassAttribute exists.
Ethan Furman63c141c2013-10-18 00:27:39 -0700344 for base in mro:
Ethan Furmane03ea372013-09-25 07:14:41 -0700345 for k, v in base.__dict__.items():
346 if isinstance(v, types.DynamicClassAttribute):
347 names.append(k)
Tim Peters13b49d32001-09-23 02:00:29 +0000348 result = []
Ethan Furmane03ea372013-09-25 07:14:41 -0700349 processed = set()
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700350
Tim Peters13b49d32001-09-23 02:00:29 +0000351 for name in names:
Antoine Pitrou86a8a9a2011-12-21 09:57:40 +0100352 # Get the object associated with the name, and where it was defined.
Ethan Furmane03ea372013-09-25 07:14:41 -0700353 # Normal objects will be looked up with both getattr and directly in
354 # its class' dict (in case getattr fails [bug #1785], and also to look
355 # for a docstring).
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700356 # For DynamicClassAttributes on the second pass we only look in the
Ethan Furmane03ea372013-09-25 07:14:41 -0700357 # class's dict.
358 #
Tim Peters13b49d32001-09-23 02:00:29 +0000359 # Getting an obj from the __dict__ sometimes reveals more than
360 # using getattr. Static and class methods are dramatic examples.
Antoine Pitrou86a8a9a2011-12-21 09:57:40 +0100361 homecls = None
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700362 get_obj = None
363 dict_obj = None
Ethan Furmane03ea372013-09-25 07:14:41 -0700364 if name not in processed:
365 try:
Ethan Furmana8b07072013-10-18 01:22:08 -0700366 if name == '__dict__':
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700367 raise Exception("__dict__ is special, don't want the proxy")
Ethan Furmane03ea372013-09-25 07:14:41 -0700368 get_obj = getattr(cls, name)
369 except Exception as exc:
370 pass
371 else:
Ethan Furmane03ea372013-09-25 07:14:41 -0700372 homecls = getattr(get_obj, "__objclass__", homecls)
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700373 if homecls not in class_bases:
Ethan Furmane03ea372013-09-25 07:14:41 -0700374 # if the resulting object does not live somewhere in the
Ethan Furman63c141c2013-10-18 00:27:39 -0700375 # mro, drop it and search the mro manually
Ethan Furmane03ea372013-09-25 07:14:41 -0700376 homecls = None
Ethan Furman63c141c2013-10-18 00:27:39 -0700377 last_cls = None
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700378 # first look in the classes
379 for srch_cls in class_bases:
Ethan Furman63c141c2013-10-18 00:27:39 -0700380 srch_obj = getattr(srch_cls, name, None)
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700381 if srch_obj == get_obj:
Ethan Furman63c141c2013-10-18 00:27:39 -0700382 last_cls = srch_cls
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700383 # then check the metaclasses
384 for srch_cls in metamro:
385 try:
386 srch_obj = srch_cls.__getattr__(cls, name)
387 except AttributeError:
388 continue
389 if srch_obj == get_obj:
390 last_cls = srch_cls
Ethan Furman63c141c2013-10-18 00:27:39 -0700391 if last_cls is not None:
392 homecls = last_cls
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700393 for base in all_bases:
Ethan Furmane03ea372013-09-25 07:14:41 -0700394 if name in base.__dict__:
395 dict_obj = base.__dict__[name]
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700396 if homecls not in metamro:
397 homecls = base
Ethan Furmane03ea372013-09-25 07:14:41 -0700398 break
Ethan Furman63c141c2013-10-18 00:27:39 -0700399 if homecls is None:
400 # unable to locate the attribute anywhere, most likely due to
401 # buggy custom __dir__; discard and move on
402 continue
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700403 obj = get_obj or dict_obj
Ethan Furmane03ea372013-09-25 07:14:41 -0700404 # Classify the object or its descriptor.
Ethan Furman63c141c2013-10-18 00:27:39 -0700405 if isinstance(dict_obj, staticmethod):
Tim Peters13b49d32001-09-23 02:00:29 +0000406 kind = "static method"
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700407 obj = dict_obj
Ethan Furman63c141c2013-10-18 00:27:39 -0700408 elif isinstance(dict_obj, classmethod):
Tim Peters13b49d32001-09-23 02:00:29 +0000409 kind = "class method"
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700410 obj = dict_obj
411 elif isinstance(dict_obj, property):
Tim Peters13b49d32001-09-23 02:00:29 +0000412 kind = "property"
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700413 obj = dict_obj
Ethan Furmane03ea372013-09-25 07:14:41 -0700414 elif isfunction(obj) or ismethoddescriptor(obj):
Tim Peters13b49d32001-09-23 02:00:29 +0000415 kind = "method"
Antoine Pitrou86a8a9a2011-12-21 09:57:40 +0100416 else:
Ethan Furmane03ea372013-09-25 07:14:41 -0700417 kind = "data"
Christian Heimes25bb7832008-01-11 16:17:00 +0000418 result.append(Attribute(name, kind, homecls, obj))
Ethan Furmane03ea372013-09-25 07:14:41 -0700419 processed.add(name)
Tim Peters13b49d32001-09-23 02:00:29 +0000420 return result
421
Tim Peterse0b2d7a2001-09-22 06:10:55 +0000422# ----------------------------------------------------------- class helpers
Tim Peterse0b2d7a2001-09-22 06:10:55 +0000423
424def getmro(cls):
425 "Return tuple of base classes (including cls) in method resolution order."
Benjamin Petersonb82c8e52010-11-04 00:38:49 +0000426 return cls.__mro__
Tim Peterse0b2d7a2001-09-22 06:10:55 +0000427
Nick Coghlane8c45d62013-07-28 20:00:01 +1000428# -------------------------------------------------------- function helpers
429
430def unwrap(func, *, stop=None):
431 """Get the object wrapped by *func*.
432
433 Follows the chain of :attr:`__wrapped__` attributes returning the last
434 object in the chain.
435
436 *stop* is an optional callback accepting an object in the wrapper chain
437 as its sole argument that allows the unwrapping to be terminated early if
438 the callback returns a true value. If the callback never returns a true
439 value, the last object in the chain is returned as usual. For example,
440 :func:`signature` uses this to stop unwrapping if any object in the
441 chain has a ``__signature__`` attribute defined.
442
443 :exc:`ValueError` is raised if a cycle is encountered.
444
445 """
446 if stop is None:
447 def _is_wrapper(f):
448 return hasattr(f, '__wrapped__')
449 else:
450 def _is_wrapper(f):
451 return hasattr(f, '__wrapped__') and not stop(f)
452 f = func # remember the original func for error reporting
453 memo = {id(f)} # Memoise by id to tolerate non-hashable objects
454 while _is_wrapper(func):
455 func = func.__wrapped__
456 id_func = id(func)
457 if id_func in memo:
458 raise ValueError('wrapper loop when unwrapping {!r}'.format(f))
459 memo.add(id_func)
460 return func
461
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000462# -------------------------------------------------- source code extraction
463def indentsize(line):
464 """Return the indent size, in spaces, at the start of a line of text."""
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000465 expline = line.expandtabs()
466 return len(expline) - len(expline.lstrip())
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000467
468def getdoc(object):
469 """Get the documentation string for an object.
470
471 All tabs are expanded to spaces. To clean up docstrings that are
472 indented to line up with blocks of code, any whitespace than can be
473 uniformly removed from the second line onwards is removed."""
Tim Peters24008312002-03-17 18:56:20 +0000474 try:
475 doc = object.__doc__
476 except AttributeError:
477 return None
Guido van Rossum3172c5d2007-10-16 18:12:55 +0000478 if not isinstance(doc, str):
Tim Peters24008312002-03-17 18:56:20 +0000479 return None
Georg Brandl0c77a822008-06-10 16:37:50 +0000480 return cleandoc(doc)
481
482def cleandoc(doc):
483 """Clean up indentation from docstrings.
484
485 Any whitespace that can be uniformly removed from the second line
486 onwards is removed."""
Tim Peters24008312002-03-17 18:56:20 +0000487 try:
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000488 lines = doc.expandtabs().split('\n')
Tim Peters24008312002-03-17 18:56:20 +0000489 except UnicodeError:
490 return None
491 else:
Ka-Ping Yeea59ef7b2002-11-30 03:53:15 +0000492 # Find minimum indentation of any non-blank lines after first line.
Christian Heimesa37d4c62007-12-04 23:02:19 +0000493 margin = sys.maxsize
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000494 for line in lines[1:]:
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000495 content = len(line.lstrip())
Ka-Ping Yeea59ef7b2002-11-30 03:53:15 +0000496 if content:
497 indent = len(line) - content
498 margin = min(margin, indent)
499 # Remove indentation.
500 if lines:
501 lines[0] = lines[0].lstrip()
Christian Heimesa37d4c62007-12-04 23:02:19 +0000502 if margin < sys.maxsize:
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000503 for i in range(1, len(lines)): lines[i] = lines[i][margin:]
Ka-Ping Yeea59ef7b2002-11-30 03:53:15 +0000504 # Remove any trailing or leading blank lines.
505 while lines and not lines[-1]:
506 lines.pop()
507 while lines and not lines[0]:
508 lines.pop(0)
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000509 return '\n'.join(lines)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000510
511def getfile(object):
Ka-Ping Yeec113c242001-03-02 02:08:53 +0000512 """Work out which source or compiled file an object was defined in."""
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000513 if ismodule(object):
514 if hasattr(object, '__file__'):
515 return object.__file__
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +0000516 raise TypeError('{!r} is a built-in module'.format(object))
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000517 if isclass(object):
Ka-Ping Yeec99e0f12001-04-13 12:10:40 +0000518 object = sys.modules.get(object.__module__)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000519 if hasattr(object, '__file__'):
520 return object.__file__
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +0000521 raise TypeError('{!r} is a built-in class'.format(object))
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000522 if ismethod(object):
Christian Heimesff737952007-11-27 10:40:20 +0000523 object = object.__func__
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000524 if isfunction(object):
Neal Norwitz221085d2007-02-25 20:55:47 +0000525 object = object.__code__
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000526 if istraceback(object):
527 object = object.tb_frame
528 if isframe(object):
529 object = object.f_code
530 if iscode(object):
531 return object.co_filename
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +0000532 raise TypeError('{!r} is not a module, class, method, '
533 'function, traceback, frame, or code object'.format(object))
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000534
Christian Heimes25bb7832008-01-11 16:17:00 +0000535ModuleInfo = namedtuple('ModuleInfo', 'name suffix mode module_type')
536
Ka-Ping Yee4d6fc7f2001-04-10 11:43:00 +0000537def getmoduleinfo(path):
538 """Get the module name, suffix, mode, and module type for a given file."""
Brett Cannoncb66eb02012-05-11 12:58:42 -0400539 warnings.warn('inspect.getmoduleinfo() is deprecated', DeprecationWarning,
540 2)
Brett Cannone4f41de2013-06-16 13:13:40 -0400541 with warnings.catch_warnings():
542 warnings.simplefilter('ignore', PendingDeprecationWarning)
543 import imp
Ka-Ping Yee4d6fc7f2001-04-10 11:43:00 +0000544 filename = os.path.basename(path)
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000545 suffixes = [(-len(suffix), suffix, mode, mtype)
546 for suffix, mode, mtype in imp.get_suffixes()]
Ka-Ping Yee4d6fc7f2001-04-10 11:43:00 +0000547 suffixes.sort() # try longest suffixes first, in case they overlap
548 for neglen, suffix, mode, mtype in suffixes:
549 if filename[neglen:] == suffix:
Christian Heimes25bb7832008-01-11 16:17:00 +0000550 return ModuleInfo(filename[:neglen], suffix, mode, mtype)
Ka-Ping Yee4d6fc7f2001-04-10 11:43:00 +0000551
552def getmodulename(path):
553 """Return the module name for a given file, or None."""
Nick Coghlan76e07702012-07-18 23:14:57 +1000554 fname = os.path.basename(path)
555 # Check for paths that look like an actual module file
556 suffixes = [(-len(suffix), suffix)
557 for suffix in importlib.machinery.all_suffixes()]
558 suffixes.sort() # try longest suffixes first, in case they overlap
559 for neglen, suffix in suffixes:
560 if fname.endswith(suffix):
561 return fname[:neglen]
562 return None
Ka-Ping Yee4d6fc7f2001-04-10 11:43:00 +0000563
Ka-Ping Yeec113c242001-03-02 02:08:53 +0000564def getsourcefile(object):
R. David Murraya1b37402010-06-17 02:04:29 +0000565 """Return the filename that can be used to locate an object's source.
566 Return None if no way can be identified to get the source.
567 """
Ka-Ping Yeec113c242001-03-02 02:08:53 +0000568 filename = getfile(object)
Brett Cannoncb66eb02012-05-11 12:58:42 -0400569 all_bytecode_suffixes = importlib.machinery.DEBUG_BYTECODE_SUFFIXES[:]
570 all_bytecode_suffixes += importlib.machinery.OPTIMIZED_BYTECODE_SUFFIXES[:]
571 if any(filename.endswith(s) for s in all_bytecode_suffixes):
572 filename = (os.path.splitext(filename)[0] +
573 importlib.machinery.SOURCE_SUFFIXES[0])
574 elif any(filename.endswith(s) for s in
575 importlib.machinery.EXTENSION_SUFFIXES):
576 return None
Thomas Wouters477c8d52006-05-27 19:21:47 +0000577 if os.path.exists(filename):
578 return filename
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000579 # only return a non-existent filename if the module has a PEP 302 loader
Brett Cannon4c14b5d2013-05-04 13:56:58 -0400580 if getattr(getmodule(object, filename), '__loader__', None) is not None:
Ka-Ping Yeec113c242001-03-02 02:08:53 +0000581 return filename
R. David Murraya1b37402010-06-17 02:04:29 +0000582 # or it is in the linecache
583 if filename in linecache.cache:
584 return filename
Ka-Ping Yeec113c242001-03-02 02:08:53 +0000585
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000586def getabsfile(object, _filename=None):
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000587 """Return an absolute path to the source or compiled file for an object.
Ka-Ping Yeec113c242001-03-02 02:08:53 +0000588
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000589 The idea is for each object to have a unique origin, so this routine
590 normalizes the result as much as possible."""
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000591 if _filename is None:
592 _filename = getsourcefile(object) or getfile(object)
593 return os.path.normcase(os.path.abspath(_filename))
Ka-Ping Yeec113c242001-03-02 02:08:53 +0000594
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000595modulesbyfile = {}
Thomas Wouters89f507f2006-12-13 04:49:30 +0000596_filesbymodname = {}
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000597
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000598def getmodule(object, _filename=None):
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000599 """Return the module an object was defined in, or None if not found."""
Ka-Ping Yee202c99b2001-04-13 09:15:08 +0000600 if ismodule(object):
601 return object
Johannes Gijsbers93245262004-09-11 15:53:22 +0000602 if hasattr(object, '__module__'):
Ka-Ping Yee8b58b842001-03-01 13:56:16 +0000603 return sys.modules.get(object.__module__)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000604 # Try the filename to modulename cache
605 if _filename is not None and _filename in modulesbyfile:
606 return sys.modules.get(modulesbyfile[_filename])
607 # Try the cache again with the absolute file name
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000608 try:
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000609 file = getabsfile(object, _filename)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000610 except TypeError:
611 return None
Raymond Hettinger54f02222002-06-01 14:18:47 +0000612 if file in modulesbyfile:
Ka-Ping Yeeb38bbbd2003-03-28 16:29:50 +0000613 return sys.modules.get(modulesbyfile[file])
Thomas Wouters89f507f2006-12-13 04:49:30 +0000614 # Update the filename to module name cache and check yet again
615 # Copy sys.modules in order to cope with changes while iterating
Éric Araujoa74f8ef2011-11-29 16:58:53 +0100616 for modname, module in list(sys.modules.items()):
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000617 if ismodule(module) and hasattr(module, '__file__'):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000618 f = module.__file__
619 if f == _filesbymodname.get(modname, None):
620 # Have already mapped this module, so skip it
621 continue
622 _filesbymodname[modname] = f
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000623 f = getabsfile(module)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000624 # Always map to the name the module knows itself by
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000625 modulesbyfile[f] = modulesbyfile[
626 os.path.realpath(f)] = module.__name__
Raymond Hettinger54f02222002-06-01 14:18:47 +0000627 if file in modulesbyfile:
Ka-Ping Yeeb38bbbd2003-03-28 16:29:50 +0000628 return sys.modules.get(modulesbyfile[file])
Thomas Wouters89f507f2006-12-13 04:49:30 +0000629 # Check the main module
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000630 main = sys.modules['__main__']
Brett Cannon4a671fe2003-06-15 22:33:28 +0000631 if not hasattr(object, '__name__'):
632 return None
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000633 if hasattr(main, object.__name__):
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000634 mainobject = getattr(main, object.__name__)
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000635 if mainobject is object:
636 return main
Thomas Wouters89f507f2006-12-13 04:49:30 +0000637 # Check builtins
Georg Brandl1a3284e2007-12-02 09:40:06 +0000638 builtin = sys.modules['builtins']
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000639 if hasattr(builtin, object.__name__):
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000640 builtinobject = getattr(builtin, object.__name__)
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000641 if builtinobject is object:
642 return builtin
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000643
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000644def findsource(object):
645 """Return the entire source file and starting line number for an object.
646
647 The argument may be a module, class, method, function, traceback, frame,
648 or code object. The source code is returned as a list of all the lines
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200649 in the file and the line number indexes a line in that list. An OSError
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000650 is raised if the source code cannot be retrieved."""
Benjamin Peterson9620cc02011-06-11 15:53:11 -0500651
652 file = getfile(object)
653 sourcefile = getsourcefile(object)
Ezio Melotti1b145922013-03-30 05:17:24 +0200654 if not sourcefile and file[:1] + file[-1:] != '<>':
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200655 raise OSError('source code not available')
Benjamin Peterson9620cc02011-06-11 15:53:11 -0500656 file = sourcefile if sourcefile else file
657
Thomas Wouters89f507f2006-12-13 04:49:30 +0000658 module = getmodule(object, file)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000659 if module:
660 lines = linecache.getlines(file, module.__dict__)
661 else:
662 lines = linecache.getlines(file)
Neil Schemenauerf06f8532002-03-23 23:51:04 +0000663 if not lines:
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200664 raise OSError('could not get source code')
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000665
666 if ismodule(object):
667 return lines, 0
668
669 if isclass(object):
670 name = object.__name__
Thomas Wouters89f507f2006-12-13 04:49:30 +0000671 pat = re.compile(r'^(\s*)class\s*' + name + r'\b')
672 # make some effort to find the best matching class definition:
673 # use the one with the least indentation, which is the one
674 # that's most probably not inside a function definition.
675 candidates = []
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000676 for i in range(len(lines)):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000677 match = pat.match(lines[i])
678 if match:
679 # if it's at toplevel, it's already the best one
680 if lines[i][0] == 'c':
681 return lines, i
682 # else add whitespace to candidate list
683 candidates.append((match.group(1), i))
684 if candidates:
685 # this will sort by whitespace, and by line number,
686 # less whitespace first
687 candidates.sort()
688 return lines, candidates[0][1]
Jeremy Hyltonab919022003-06-27 18:41:20 +0000689 else:
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200690 raise OSError('could not find class definition')
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000691
692 if ismethod(object):
Christian Heimesff737952007-11-27 10:40:20 +0000693 object = object.__func__
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000694 if isfunction(object):
Neal Norwitz221085d2007-02-25 20:55:47 +0000695 object = object.__code__
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000696 if istraceback(object):
697 object = object.tb_frame
698 if isframe(object):
699 object = object.f_code
700 if iscode(object):
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000701 if not hasattr(object, 'co_firstlineno'):
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200702 raise OSError('could not find function definition')
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000703 lnum = object.co_firstlineno - 1
Johannes Gijsbers1542f342004-12-12 16:46:28 +0000704 pat = re.compile(r'^(\s*def\s)|(.*(?<!\w)lambda(:|\s))|^(\s*@)')
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000705 while lnum > 0:
Ka-Ping Yeea6e59712001-03-10 09:31:55 +0000706 if pat.match(lines[lnum]): break
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000707 lnum = lnum - 1
708 return lines, lnum
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200709 raise OSError('could not find code object')
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000710
711def getcomments(object):
Jeremy Hyltonb4c17c82002-03-28 23:01:56 +0000712 """Get lines of comments immediately preceding an object's source code.
713
714 Returns None when source can't be found.
715 """
716 try:
717 lines, lnum = findsource(object)
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200718 except (OSError, TypeError):
Jeremy Hyltonb4c17c82002-03-28 23:01:56 +0000719 return None
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000720
721 if ismodule(object):
722 # Look for a comment block at the top of the file.
723 start = 0
Ka-Ping Yeeb910efe2001-04-12 13:17:17 +0000724 if lines and lines[0][:2] == '#!': start = 1
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000725 while start < len(lines) and lines[start].strip() in ('', '#'):
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000726 start = start + 1
Ka-Ping Yeeb910efe2001-04-12 13:17:17 +0000727 if start < len(lines) and lines[start][:1] == '#':
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000728 comments = []
729 end = start
730 while end < len(lines) and lines[end][:1] == '#':
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000731 comments.append(lines[end].expandtabs())
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000732 end = end + 1
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000733 return ''.join(comments)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000734
735 # Look for a preceding block of comments at the same indentation.
736 elif lnum > 0:
737 indent = indentsize(lines[lnum])
738 end = lnum - 1
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000739 if end >= 0 and lines[end].lstrip()[:1] == '#' and \
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000740 indentsize(lines[end]) == indent:
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000741 comments = [lines[end].expandtabs().lstrip()]
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000742 if end > 0:
743 end = end - 1
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000744 comment = lines[end].expandtabs().lstrip()
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000745 while comment[:1] == '#' and indentsize(lines[end]) == indent:
746 comments[:0] = [comment]
747 end = end - 1
748 if end < 0: break
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000749 comment = lines[end].expandtabs().lstrip()
750 while comments and comments[0].strip() == '#':
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000751 comments[:1] = []
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000752 while comments and comments[-1].strip() == '#':
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000753 comments[-1:] = []
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000754 return ''.join(comments)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000755
Tim Peters4efb6e92001-06-29 23:51:08 +0000756class EndOfBlock(Exception): pass
757
758class BlockFinder:
759 """Provide a tokeneater() method to detect the end of a code block."""
760 def __init__(self):
761 self.indent = 0
Johannes Gijsbersa5855d52005-03-12 16:37:11 +0000762 self.islambda = False
Johannes Gijsbers1542f342004-12-12 16:46:28 +0000763 self.started = False
764 self.passline = False
Armin Rigodd5c0232005-09-25 11:45:45 +0000765 self.last = 1
Tim Peters4efb6e92001-06-29 23:51:08 +0000766
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000767 def tokeneater(self, type, token, srowcol, erowcol, line):
Tim Peters4efb6e92001-06-29 23:51:08 +0000768 if not self.started:
Armin Rigodd5c0232005-09-25 11:45:45 +0000769 # look for the first "def", "class" or "lambda"
Johannes Gijsbers1542f342004-12-12 16:46:28 +0000770 if token in ("def", "class", "lambda"):
Johannes Gijsbersa5855d52005-03-12 16:37:11 +0000771 if token == "lambda":
772 self.islambda = True
Johannes Gijsbers1542f342004-12-12 16:46:28 +0000773 self.started = True
Armin Rigodd5c0232005-09-25 11:45:45 +0000774 self.passline = True # skip to the end of the line
Tim Peters4efb6e92001-06-29 23:51:08 +0000775 elif type == tokenize.NEWLINE:
Armin Rigodd5c0232005-09-25 11:45:45 +0000776 self.passline = False # stop skipping when a NEWLINE is seen
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000777 self.last = srowcol[0]
Armin Rigodd5c0232005-09-25 11:45:45 +0000778 if self.islambda: # lambdas always end at the first NEWLINE
779 raise EndOfBlock
Johannes Gijsbers1542f342004-12-12 16:46:28 +0000780 elif self.passline:
781 pass
Tim Peters4efb6e92001-06-29 23:51:08 +0000782 elif type == tokenize.INDENT:
783 self.indent = self.indent + 1
Johannes Gijsbers1542f342004-12-12 16:46:28 +0000784 self.passline = True
Tim Peters4efb6e92001-06-29 23:51:08 +0000785 elif type == tokenize.DEDENT:
786 self.indent = self.indent - 1
Armin Rigodd5c0232005-09-25 11:45:45 +0000787 # the end of matching indent/dedent pairs end a block
788 # (note that this only works for "def"/"class" blocks,
789 # not e.g. for "if: else:" or "try: finally:" blocks)
790 if self.indent <= 0:
791 raise EndOfBlock
792 elif self.indent == 0 and type not in (tokenize.COMMENT, tokenize.NL):
793 # any other token on the same indentation level end the previous
794 # block as well, except the pseudo-tokens COMMENT and NL.
795 raise EndOfBlock
Tim Peters4efb6e92001-06-29 23:51:08 +0000796
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000797def getblock(lines):
798 """Extract the block of code at the top of the given list of lines."""
Armin Rigodd5c0232005-09-25 11:45:45 +0000799 blockfinder = BlockFinder()
Tim Peters4efb6e92001-06-29 23:51:08 +0000800 try:
Trent Nelson428de652008-03-18 22:41:35 +0000801 tokens = tokenize.generate_tokens(iter(lines).__next__)
802 for _token in tokens:
803 blockfinder.tokeneater(*_token)
Armin Rigodd5c0232005-09-25 11:45:45 +0000804 except (EndOfBlock, IndentationError):
805 pass
806 return lines[:blockfinder.last]
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000807
808def getsourcelines(object):
809 """Return a list of source lines and starting line number for an object.
810
811 The argument may be a module, class, method, function, traceback, frame,
812 or code object. The source code is returned as a list of the lines
813 corresponding to the object and the line number indicates where in the
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200814 original source file the first line of code was found. An OSError is
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000815 raised if the source code cannot be retrieved."""
816 lines, lnum = findsource(object)
817
818 if ismodule(object): return lines, 0
819 else: return getblock(lines[lnum:]), lnum + 1
820
821def getsource(object):
822 """Return the text of the source code for an object.
823
824 The argument may be a module, class, method, function, traceback, frame,
825 or code object. The source code is returned as a single string. An
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200826 OSError is raised if the source code cannot be retrieved."""
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000827 lines, lnum = getsourcelines(object)
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000828 return ''.join(lines)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000829
830# --------------------------------------------------- class tree extraction
831def walktree(classes, children, parent):
832 """Recursive helper function for getclasstree()."""
833 results = []
Raymond Hettingera1a992c2005-03-11 06:46:45 +0000834 classes.sort(key=attrgetter('__module__', '__name__'))
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000835 for c in classes:
836 results.append((c, c.__bases__))
Raymond Hettinger54f02222002-06-01 14:18:47 +0000837 if c in children:
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000838 results.append(walktree(children[c], children, c))
839 return results
840
Georg Brandl5ce83a02009-06-01 17:23:51 +0000841def getclasstree(classes, unique=False):
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000842 """Arrange the given list of classes into a hierarchy of nested lists.
843
844 Where a nested list appears, it contains classes derived from the class
845 whose entry immediately precedes the list. Each entry is a 2-tuple
846 containing a class and a tuple of its base classes. If the 'unique'
847 argument is true, exactly one entry appears in the returned structure
848 for each class in the given list. Otherwise, classes using multiple
849 inheritance and their descendants will appear multiple times."""
850 children = {}
851 roots = []
852 for c in classes:
853 if c.__bases__:
854 for parent in c.__bases__:
Raymond Hettinger54f02222002-06-01 14:18:47 +0000855 if not parent in children:
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000856 children[parent] = []
Serhiy Storchaka362c1b52013-09-05 17:14:32 +0300857 if c not in children[parent]:
858 children[parent].append(c)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000859 if unique and parent in classes: break
860 elif c not in roots:
861 roots.append(c)
Raymond Hettingere0d49722002-06-02 18:55:56 +0000862 for parent in children:
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000863 if parent not in classes:
864 roots.append(parent)
865 return walktree(roots, children, None)
866
867# ------------------------------------------------ argument list extraction
Christian Heimes25bb7832008-01-11 16:17:00 +0000868Arguments = namedtuple('Arguments', 'args, varargs, varkw')
869
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000870def getargs(co):
871 """Get information about the arguments accepted by a code object.
872
Guido van Rossum2e65f892007-02-28 22:03:49 +0000873 Three things are returned: (args, varargs, varkw), where
Georg Brandlc1c4bf82010-10-15 16:07:41 +0000874 'args' is the list of argument names. Keyword-only arguments are
875 appended. 'varargs' and 'varkw' are the names of the * and **
876 arguments or None."""
Guido van Rossum2e65f892007-02-28 22:03:49 +0000877 args, varargs, kwonlyargs, varkw = _getfullargs(co)
Christian Heimes25bb7832008-01-11 16:17:00 +0000878 return Arguments(args + kwonlyargs, varargs, varkw)
Guido van Rossum2e65f892007-02-28 22:03:49 +0000879
880def _getfullargs(co):
881 """Get information about the arguments accepted by a code object.
882
883 Four things are returned: (args, varargs, kwonlyargs, varkw), where
Georg Brandlc1c4bf82010-10-15 16:07:41 +0000884 'args' and 'kwonlyargs' are lists of argument names, and 'varargs'
885 and 'varkw' are the names of the * and ** arguments or None."""
Jeremy Hylton64967882003-06-27 18:14:39 +0000886
887 if not iscode(co):
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +0000888 raise TypeError('{!r} is not a code object'.format(co))
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000889
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000890 nargs = co.co_argcount
891 names = co.co_varnames
Guido van Rossum2e65f892007-02-28 22:03:49 +0000892 nkwargs = co.co_kwonlyargcount
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000893 args = list(names[:nargs])
Guido van Rossum2e65f892007-02-28 22:03:49 +0000894 kwonlyargs = list(names[nargs:nargs+nkwargs])
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000895 step = 0
896
Guido van Rossum2e65f892007-02-28 22:03:49 +0000897 nargs += nkwargs
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000898 varargs = None
899 if co.co_flags & CO_VARARGS:
900 varargs = co.co_varnames[nargs]
901 nargs = nargs + 1
902 varkw = None
903 if co.co_flags & CO_VARKEYWORDS:
904 varkw = co.co_varnames[nargs]
Guido van Rossum2e65f892007-02-28 22:03:49 +0000905 return args, varargs, kwonlyargs, varkw
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000906
Christian Heimes25bb7832008-01-11 16:17:00 +0000907
908ArgSpec = namedtuple('ArgSpec', 'args varargs keywords defaults')
909
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000910def getargspec(func):
911 """Get the names and default values of a function's arguments.
912
913 A tuple of four things is returned: (args, varargs, varkw, defaults).
Georg Brandlc1c4bf82010-10-15 16:07:41 +0000914 'args' is a list of the argument names.
Guido van Rossum2e65f892007-02-28 22:03:49 +0000915 'args' will include keyword-only argument names.
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000916 'varargs' and 'varkw' are the names of the * and ** arguments or None.
Jeremy Hylton64967882003-06-27 18:14:39 +0000917 'defaults' is an n-tuple of the default values of the last n arguments.
Guido van Rossuma8add0e2007-05-14 22:03:55 +0000918
Guido van Rossum2e65f892007-02-28 22:03:49 +0000919 Use the getfullargspec() API for Python-3000 code, as annotations
920 and keyword arguments are supported. getargspec() will raise ValueError
921 if the func has either annotations or keyword arguments.
922 """
923
924 args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults, ann = \
925 getfullargspec(func)
926 if kwonlyargs or ann:
Collin Winterce36ad82007-08-30 01:19:48 +0000927 raise ValueError("Function has keyword-only arguments or annotations"
928 ", use getfullargspec() API which can support them")
Christian Heimes25bb7832008-01-11 16:17:00 +0000929 return ArgSpec(args, varargs, varkw, defaults)
930
931FullArgSpec = namedtuple('FullArgSpec',
Benjamin Peterson3d4ca742008-11-12 21:39:01 +0000932 'args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults, annotations')
Guido van Rossum2e65f892007-02-28 22:03:49 +0000933
934def getfullargspec(func):
935 """Get the names and default values of a function's arguments.
936
Brett Cannon504d8852007-09-07 02:12:14 +0000937 A tuple of seven things is returned:
938 (args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults annotations).
Georg Brandlc1c4bf82010-10-15 16:07:41 +0000939 'args' is a list of the argument names.
Guido van Rossum2e65f892007-02-28 22:03:49 +0000940 'varargs' and 'varkw' are the names of the * and ** arguments or None.
941 'defaults' is an n-tuple of the default values of the last n arguments.
942 'kwonlyargs' is a list of keyword-only argument names.
943 'kwonlydefaults' is a dictionary mapping names from kwonlyargs to defaults.
944 'annotations' is a dictionary mapping argument names to annotations.
Guido van Rossuma8add0e2007-05-14 22:03:55 +0000945
Guido van Rossum2e65f892007-02-28 22:03:49 +0000946 The first four items in the tuple correspond to getargspec().
Jeremy Hylton64967882003-06-27 18:14:39 +0000947 """
948
949 if ismethod(func):
Christian Heimesff737952007-11-27 10:40:20 +0000950 func = func.__func__
Jeremy Hylton64967882003-06-27 18:14:39 +0000951 if not isfunction(func):
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +0000952 raise TypeError('{!r} is not a Python function'.format(func))
Guido van Rossum2e65f892007-02-28 22:03:49 +0000953 args, varargs, kwonlyargs, varkw = _getfullargs(func.__code__)
Christian Heimes25bb7832008-01-11 16:17:00 +0000954 return FullArgSpec(args, varargs, varkw, func.__defaults__,
Guido van Rossum2e65f892007-02-28 22:03:49 +0000955 kwonlyargs, func.__kwdefaults__, func.__annotations__)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000956
Christian Heimes25bb7832008-01-11 16:17:00 +0000957ArgInfo = namedtuple('ArgInfo', 'args varargs keywords locals')
958
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000959def getargvalues(frame):
960 """Get information about arguments passed into a particular frame.
961
962 A tuple of four things is returned: (args, varargs, varkw, locals).
Georg Brandlc1c4bf82010-10-15 16:07:41 +0000963 'args' is a list of the argument names.
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000964 'varargs' and 'varkw' are the names of the * and ** arguments or None.
965 'locals' is the locals dictionary of the given frame."""
966 args, varargs, varkw = getargs(frame.f_code)
Benjamin Peterson1a6e0d02008-10-25 15:49:17 +0000967 return ArgInfo(args, varargs, varkw, frame.f_locals)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000968
Guido van Rossum2e65f892007-02-28 22:03:49 +0000969def formatannotation(annotation, base_module=None):
970 if isinstance(annotation, type):
Georg Brandl1a3284e2007-12-02 09:40:06 +0000971 if annotation.__module__ in ('builtins', base_module):
Guido van Rossum2e65f892007-02-28 22:03:49 +0000972 return annotation.__name__
973 return annotation.__module__+'.'+annotation.__name__
974 return repr(annotation)
Guido van Rossuma8add0e2007-05-14 22:03:55 +0000975
Guido van Rossum2e65f892007-02-28 22:03:49 +0000976def formatannotationrelativeto(object):
Guido van Rossuma8add0e2007-05-14 22:03:55 +0000977 module = getattr(object, '__module__', None)
978 def _formatannotation(annotation):
979 return formatannotation(annotation, module)
980 return _formatannotation
Guido van Rossum2e65f892007-02-28 22:03:49 +0000981
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000982def formatargspec(args, varargs=None, varkw=None, defaults=None,
Guido van Rossum2e65f892007-02-28 22:03:49 +0000983 kwonlyargs=(), kwonlydefaults={}, annotations={},
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000984 formatarg=str,
985 formatvarargs=lambda name: '*' + name,
986 formatvarkw=lambda name: '**' + name,
987 formatvalue=lambda value: '=' + repr(value),
Guido van Rossum2e65f892007-02-28 22:03:49 +0000988 formatreturns=lambda text: ' -> ' + text,
Georg Brandlc1c4bf82010-10-15 16:07:41 +0000989 formatannotation=formatannotation):
Guido van Rossuma8add0e2007-05-14 22:03:55 +0000990 """Format an argument spec from the values returned by getargspec
Guido van Rossum2e65f892007-02-28 22:03:49 +0000991 or getfullargspec.
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000992
Guido van Rossum2e65f892007-02-28 22:03:49 +0000993 The first seven arguments are (args, varargs, varkw, defaults,
994 kwonlyargs, kwonlydefaults, annotations). The other five arguments
995 are the corresponding optional formatting functions that are called to
996 turn names and values into strings. The last argument is an optional
997 function to format the sequence of arguments."""
998 def formatargandannotation(arg):
999 result = formatarg(arg)
1000 if arg in annotations:
1001 result += ': ' + formatannotation(annotations[arg])
1002 return result
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001003 specs = []
1004 if defaults:
1005 firstdefault = len(args) - len(defaults)
Benjamin Petersonb58dda72009-01-18 22:27:04 +00001006 for i, arg in enumerate(args):
Georg Brandlc1c4bf82010-10-15 16:07:41 +00001007 spec = formatargandannotation(arg)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001008 if defaults and i >= firstdefault:
1009 spec = spec + formatvalue(defaults[i - firstdefault])
1010 specs.append(spec)
Raymond Hettinger936654b2002-06-01 03:06:31 +00001011 if varargs is not None:
Guido van Rossum2e65f892007-02-28 22:03:49 +00001012 specs.append(formatvarargs(formatargandannotation(varargs)))
1013 else:
1014 if kwonlyargs:
1015 specs.append('*')
1016 if kwonlyargs:
1017 for kwonlyarg in kwonlyargs:
1018 spec = formatargandannotation(kwonlyarg)
Benjamin Peterson9953a8d2009-01-17 04:15:01 +00001019 if kwonlydefaults and kwonlyarg in kwonlydefaults:
Guido van Rossum2e65f892007-02-28 22:03:49 +00001020 spec += formatvalue(kwonlydefaults[kwonlyarg])
1021 specs.append(spec)
Raymond Hettinger936654b2002-06-01 03:06:31 +00001022 if varkw is not None:
Guido van Rossum2e65f892007-02-28 22:03:49 +00001023 specs.append(formatvarkw(formatargandannotation(varkw)))
Neal Norwitz9d72bb42007-04-17 08:48:32 +00001024 result = '(' + ', '.join(specs) + ')'
Guido van Rossum2e65f892007-02-28 22:03:49 +00001025 if 'return' in annotations:
1026 result += formatreturns(formatannotation(annotations['return']))
1027 return result
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001028
1029def formatargvalues(args, varargs, varkw, locals,
1030 formatarg=str,
1031 formatvarargs=lambda name: '*' + name,
1032 formatvarkw=lambda name: '**' + name,
Georg Brandlc1c4bf82010-10-15 16:07:41 +00001033 formatvalue=lambda value: '=' + repr(value)):
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001034 """Format an argument spec from the 4 values returned by getargvalues.
1035
1036 The first four arguments are (args, varargs, varkw, locals). The
1037 next four arguments are the corresponding optional formatting functions
1038 that are called to turn names and values into strings. The ninth
1039 argument is an optional function to format the sequence of arguments."""
1040 def convert(name, locals=locals,
1041 formatarg=formatarg, formatvalue=formatvalue):
1042 return formatarg(name) + formatvalue(locals[name])
1043 specs = []
1044 for i in range(len(args)):
Georg Brandlc1c4bf82010-10-15 16:07:41 +00001045 specs.append(convert(args[i]))
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001046 if varargs:
1047 specs.append(formatvarargs(varargs) + formatvalue(locals[varargs]))
1048 if varkw:
1049 specs.append(formatvarkw(varkw) + formatvalue(locals[varkw]))
Neal Norwitz9d72bb42007-04-17 08:48:32 +00001050 return '(' + ', '.join(specs) + ')'
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001051
Benjamin Petersone109c702011-06-24 09:37:26 -05001052def _missing_arguments(f_name, argnames, pos, values):
1053 names = [repr(name) for name in argnames if name not in values]
1054 missing = len(names)
1055 if missing == 1:
1056 s = names[0]
1057 elif missing == 2:
1058 s = "{} and {}".format(*names)
1059 else:
1060 tail = ", {} and {}".format(names[-2:])
1061 del names[-2:]
1062 s = ", ".join(names) + tail
1063 raise TypeError("%s() missing %i required %s argument%s: %s" %
1064 (f_name, missing,
1065 "positional" if pos else "keyword-only",
1066 "" if missing == 1 else "s", s))
1067
1068def _too_many(f_name, args, kwonly, varargs, defcount, given, values):
Benjamin Petersonb204a422011-06-05 22:04:07 -05001069 atleast = len(args) - defcount
Benjamin Petersonb204a422011-06-05 22:04:07 -05001070 kwonly_given = len([arg for arg in kwonly if arg in values])
1071 if varargs:
1072 plural = atleast != 1
1073 sig = "at least %d" % (atleast,)
1074 elif defcount:
1075 plural = True
1076 sig = "from %d to %d" % (atleast, len(args))
1077 else:
1078 plural = len(args) != 1
1079 sig = str(len(args))
1080 kwonly_sig = ""
1081 if kwonly_given:
1082 msg = " positional argument%s (and %d keyword-only argument%s)"
1083 kwonly_sig = (msg % ("s" if given != 1 else "", kwonly_given,
1084 "s" if kwonly_given != 1 else ""))
1085 raise TypeError("%s() takes %s positional argument%s but %d%s %s given" %
1086 (f_name, sig, "s" if plural else "", given, kwonly_sig,
1087 "was" if given == 1 and not kwonly_given else "were"))
1088
Benjamin Peterson25cd7eb2010-03-30 18:42:32 +00001089def getcallargs(func, *positional, **named):
1090 """Get the mapping of arguments to values.
1091
1092 A dict is returned, with keys the function argument names (including the
1093 names of the * and ** arguments, if any), and values the respective bound
1094 values from 'positional' and 'named'."""
1095 spec = getfullargspec(func)
1096 args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults, ann = spec
1097 f_name = func.__name__
1098 arg2value = {}
1099
Benjamin Petersonb204a422011-06-05 22:04:07 -05001100
Benjamin Peterson25cd7eb2010-03-30 18:42:32 +00001101 if ismethod(func) and func.__self__ is not None:
1102 # implicit 'self' (or 'cls' for classmethods) argument
1103 positional = (func.__self__,) + positional
1104 num_pos = len(positional)
Benjamin Peterson25cd7eb2010-03-30 18:42:32 +00001105 num_args = len(args)
1106 num_defaults = len(defaults) if defaults else 0
Benjamin Peterson25cd7eb2010-03-30 18:42:32 +00001107
Benjamin Petersonb204a422011-06-05 22:04:07 -05001108 n = min(num_pos, num_args)
1109 for i in range(n):
1110 arg2value[args[i]] = positional[i]
1111 if varargs:
1112 arg2value[varargs] = tuple(positional[n:])
1113 possible_kwargs = set(args + kwonlyargs)
Benjamin Peterson25cd7eb2010-03-30 18:42:32 +00001114 if varkw:
Benjamin Petersonb204a422011-06-05 22:04:07 -05001115 arg2value[varkw] = {}
1116 for kw, value in named.items():
1117 if kw not in possible_kwargs:
1118 if not varkw:
1119 raise TypeError("%s() got an unexpected keyword argument %r" %
1120 (f_name, kw))
1121 arg2value[varkw][kw] = value
1122 continue
1123 if kw in arg2value:
1124 raise TypeError("%s() got multiple values for argument %r" %
1125 (f_name, kw))
1126 arg2value[kw] = value
1127 if num_pos > num_args and not varargs:
Benjamin Petersone109c702011-06-24 09:37:26 -05001128 _too_many(f_name, args, kwonlyargs, varargs, num_defaults,
1129 num_pos, arg2value)
Benjamin Petersonb204a422011-06-05 22:04:07 -05001130 if num_pos < num_args:
Benjamin Petersone109c702011-06-24 09:37:26 -05001131 req = args[:num_args - num_defaults]
1132 for arg in req:
Benjamin Petersonb204a422011-06-05 22:04:07 -05001133 if arg not in arg2value:
Benjamin Petersone109c702011-06-24 09:37:26 -05001134 _missing_arguments(f_name, req, True, arg2value)
Benjamin Petersonb204a422011-06-05 22:04:07 -05001135 for i, arg in enumerate(args[num_args - num_defaults:]):
1136 if arg not in arg2value:
1137 arg2value[arg] = defaults[i]
Benjamin Petersone109c702011-06-24 09:37:26 -05001138 missing = 0
Benjamin Petersonb204a422011-06-05 22:04:07 -05001139 for kwarg in kwonlyargs:
1140 if kwarg not in arg2value:
Benjamin Petersone109c702011-06-24 09:37:26 -05001141 if kwarg in kwonlydefaults:
1142 arg2value[kwarg] = kwonlydefaults[kwarg]
1143 else:
1144 missing += 1
1145 if missing:
1146 _missing_arguments(f_name, kwonlyargs, False, arg2value)
Benjamin Peterson25cd7eb2010-03-30 18:42:32 +00001147 return arg2value
1148
Nick Coghlan2f92e542012-06-23 19:39:55 +10001149ClosureVars = namedtuple('ClosureVars', 'nonlocals globals builtins unbound')
1150
1151def getclosurevars(func):
1152 """
1153 Get the mapping of free variables to their current values.
1154
Meador Inge8fda3592012-07-19 21:33:21 -05001155 Returns a named tuple of dicts mapping the current nonlocal, global
Nick Coghlan2f92e542012-06-23 19:39:55 +10001156 and builtin references as seen by the body of the function. A final
1157 set of unbound names that could not be resolved is also provided.
1158 """
1159
1160 if ismethod(func):
1161 func = func.__func__
1162
1163 if not isfunction(func):
1164 raise TypeError("'{!r}' is not a Python function".format(func))
1165
1166 code = func.__code__
1167 # Nonlocal references are named in co_freevars and resolved
1168 # by looking them up in __closure__ by positional index
1169 if func.__closure__ is None:
1170 nonlocal_vars = {}
1171 else:
1172 nonlocal_vars = {
1173 var : cell.cell_contents
1174 for var, cell in zip(code.co_freevars, func.__closure__)
1175 }
1176
1177 # Global and builtin references are named in co_names and resolved
1178 # by looking them up in __globals__ or __builtins__
1179 global_ns = func.__globals__
1180 builtin_ns = global_ns.get("__builtins__", builtins.__dict__)
1181 if ismodule(builtin_ns):
1182 builtin_ns = builtin_ns.__dict__
1183 global_vars = {}
1184 builtin_vars = {}
1185 unbound_names = set()
1186 for name in code.co_names:
1187 if name in ("None", "True", "False"):
1188 # Because these used to be builtins instead of keywords, they
1189 # may still show up as name references. We ignore them.
1190 continue
1191 try:
1192 global_vars[name] = global_ns[name]
1193 except KeyError:
1194 try:
1195 builtin_vars[name] = builtin_ns[name]
1196 except KeyError:
1197 unbound_names.add(name)
1198
1199 return ClosureVars(nonlocal_vars, global_vars,
1200 builtin_vars, unbound_names)
1201
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001202# -------------------------------------------------- stack frame extraction
Christian Heimes25bb7832008-01-11 16:17:00 +00001203
1204Traceback = namedtuple('Traceback', 'filename lineno function code_context index')
1205
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001206def getframeinfo(frame, context=1):
1207 """Get information about a frame or traceback object.
1208
1209 A tuple of five things is returned: the filename, the line number of
1210 the current line, the function name, a list of lines of context from
1211 the source code, and the index of the current line within that list.
1212 The optional second argument specifies the number of lines of context
1213 to return, which are centered around the current line."""
1214 if istraceback(frame):
Andrew M. Kuchlingba8b6bc2004-06-05 14:11:59 +00001215 lineno = frame.tb_lineno
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001216 frame = frame.tb_frame
Andrew M. Kuchlingba8b6bc2004-06-05 14:11:59 +00001217 else:
1218 lineno = frame.f_lineno
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001219 if not isframe(frame):
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00001220 raise TypeError('{!r} is not a frame or traceback object'.format(frame))
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001221
Neil Schemenauerf06f8532002-03-23 23:51:04 +00001222 filename = getsourcefile(frame) or getfile(frame)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001223 if context > 0:
Guido van Rossum54e54c62001-09-04 19:14:14 +00001224 start = lineno - 1 - context//2
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001225 try:
1226 lines, lnum = findsource(frame)
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02001227 except OSError:
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +00001228 lines = index = None
1229 else:
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001230 start = max(start, 1)
Raymond Hettingera0501712004-06-15 11:22:53 +00001231 start = max(0, min(start, len(lines) - context))
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001232 lines = lines[start:start+context]
Ka-Ping Yee59ade082001-03-01 03:55:35 +00001233 index = lineno - 1 - start
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001234 else:
1235 lines = index = None
1236
Christian Heimes25bb7832008-01-11 16:17:00 +00001237 return Traceback(filename, lineno, frame.f_code.co_name, lines, index)
Ka-Ping Yee59ade082001-03-01 03:55:35 +00001238
1239def getlineno(frame):
1240 """Get the line number from a frame object, allowing for optimization."""
Michael W. Hudsondd32a912002-08-15 14:59:02 +00001241 # FrameType.f_lineno is now a descriptor that grovels co_lnotab
1242 return frame.f_lineno
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001243
1244def getouterframes(frame, context=1):
1245 """Get a list of records for a frame and all higher (calling) frames.
1246
1247 Each record contains a frame object, filename, line number, function
1248 name, a list of lines of context, and index within the context."""
1249 framelist = []
1250 while frame:
1251 framelist.append((frame,) + getframeinfo(frame, context))
1252 frame = frame.f_back
1253 return framelist
1254
1255def getinnerframes(tb, context=1):
1256 """Get a list of records for a traceback's frame and all lower frames.
1257
1258 Each record contains a frame object, filename, line number, function
1259 name, a list of lines of context, and index within the context."""
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001260 framelist = []
1261 while tb:
1262 framelist.append((tb.tb_frame,) + getframeinfo(tb, context))
1263 tb = tb.tb_next
1264 return framelist
1265
Benjamin Peterson42ac4752010-08-09 13:05:35 +00001266def currentframe():
Benjamin Petersona3a3fc62010-08-09 15:49:56 +00001267 """Return the frame of the caller or None if this is not possible."""
Benjamin Peterson42ac4752010-08-09 13:05:35 +00001268 return sys._getframe(1) if hasattr(sys, "_getframe") else None
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001269
1270def stack(context=1):
1271 """Return a list of records for the stack above the caller's frame."""
Jeremy Hyltonab919022003-06-27 18:41:20 +00001272 return getouterframes(sys._getframe(1), context)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001273
1274def trace(context=1):
Tim Peters85ba6732001-02-28 08:26:44 +00001275 """Return a list of records for the stack below the current exception."""
Fred Draked451ec12002-04-26 02:29:55 +00001276 return getinnerframes(sys.exc_info()[2], context)
Michael Foord95fc51d2010-11-20 15:07:30 +00001277
1278
1279# ------------------------------------------------ static version of getattr
1280
1281_sentinel = object()
1282
Michael Foorde5162652010-11-20 16:40:44 +00001283def _static_getmro(klass):
1284 return type.__dict__['__mro__'].__get__(klass)
1285
Michael Foord95fc51d2010-11-20 15:07:30 +00001286def _check_instance(obj, attr):
1287 instance_dict = {}
1288 try:
1289 instance_dict = object.__getattribute__(obj, "__dict__")
1290 except AttributeError:
1291 pass
Michael Foorddcebe0f2011-03-15 19:20:44 -04001292 return dict.get(instance_dict, attr, _sentinel)
Michael Foord95fc51d2010-11-20 15:07:30 +00001293
1294
1295def _check_class(klass, attr):
Michael Foorde5162652010-11-20 16:40:44 +00001296 for entry in _static_getmro(klass):
Michael Foorda51623b2011-12-18 22:01:40 +00001297 if _shadowed_dict(type(entry)) is _sentinel:
Michael Foorddcebe0f2011-03-15 19:20:44 -04001298 try:
1299 return entry.__dict__[attr]
1300 except KeyError:
1301 pass
Michael Foord95fc51d2010-11-20 15:07:30 +00001302 return _sentinel
1303
Michael Foord35184ed2010-11-20 16:58:30 +00001304def _is_type(obj):
1305 try:
1306 _static_getmro(obj)
1307 except TypeError:
1308 return False
1309 return True
1310
Michael Foorddcebe0f2011-03-15 19:20:44 -04001311def _shadowed_dict(klass):
1312 dict_attr = type.__dict__["__dict__"]
1313 for entry in _static_getmro(klass):
1314 try:
1315 class_dict = dict_attr.__get__(entry)["__dict__"]
1316 except KeyError:
1317 pass
1318 else:
1319 if not (type(class_dict) is types.GetSetDescriptorType and
1320 class_dict.__name__ == "__dict__" and
1321 class_dict.__objclass__ is entry):
Michael Foorda51623b2011-12-18 22:01:40 +00001322 return class_dict
1323 return _sentinel
Michael Foord95fc51d2010-11-20 15:07:30 +00001324
1325def getattr_static(obj, attr, default=_sentinel):
1326 """Retrieve attributes without triggering dynamic lookup via the
1327 descriptor protocol, __getattr__ or __getattribute__.
1328
1329 Note: this function may not be able to retrieve all attributes
1330 that getattr can fetch (like dynamically created attributes)
1331 and may find attributes that getattr can't (like descriptors
1332 that raise AttributeError). It can also return descriptor objects
1333 instead of instance members in some cases. See the
1334 documentation for details.
1335 """
1336 instance_result = _sentinel
Michael Foord35184ed2010-11-20 16:58:30 +00001337 if not _is_type(obj):
Michael Foordcc7ebb82010-11-20 16:20:16 +00001338 klass = type(obj)
Michael Foorda51623b2011-12-18 22:01:40 +00001339 dict_attr = _shadowed_dict(klass)
1340 if (dict_attr is _sentinel or
1341 type(dict_attr) is types.MemberDescriptorType):
Michael Foorddcebe0f2011-03-15 19:20:44 -04001342 instance_result = _check_instance(obj, attr)
Michael Foord95fc51d2010-11-20 15:07:30 +00001343 else:
1344 klass = obj
1345
1346 klass_result = _check_class(klass, attr)
1347
1348 if instance_result is not _sentinel and klass_result is not _sentinel:
1349 if (_check_class(type(klass_result), '__get__') is not _sentinel and
1350 _check_class(type(klass_result), '__set__') is not _sentinel):
1351 return klass_result
1352
1353 if instance_result is not _sentinel:
1354 return instance_result
1355 if klass_result is not _sentinel:
1356 return klass_result
1357
1358 if obj is klass:
1359 # for types we check the metaclass too
Michael Foorde5162652010-11-20 16:40:44 +00001360 for entry in _static_getmro(type(klass)):
Michael Foord3ba95f82011-12-22 01:13:37 +00001361 if _shadowed_dict(type(entry)) is _sentinel:
1362 try:
1363 return entry.__dict__[attr]
1364 except KeyError:
1365 pass
Michael Foord95fc51d2010-11-20 15:07:30 +00001366 if default is not _sentinel:
1367 return default
1368 raise AttributeError(attr)
Nick Coghlane0f04652010-11-21 03:44:04 +00001369
1370
Nick Coghlan04e2e3f2012-06-23 19:52:05 +10001371# ------------------------------------------------ generator introspection
1372
Nick Coghlan7921b9f2010-11-30 06:36:04 +00001373GEN_CREATED = 'GEN_CREATED'
1374GEN_RUNNING = 'GEN_RUNNING'
1375GEN_SUSPENDED = 'GEN_SUSPENDED'
1376GEN_CLOSED = 'GEN_CLOSED'
Nick Coghlane0f04652010-11-21 03:44:04 +00001377
1378def getgeneratorstate(generator):
1379 """Get current state of a generator-iterator.
1380
1381 Possible states are:
1382 GEN_CREATED: Waiting to start execution.
1383 GEN_RUNNING: Currently being executed by the interpreter.
1384 GEN_SUSPENDED: Currently suspended at a yield expression.
1385 GEN_CLOSED: Execution has completed.
1386 """
1387 if generator.gi_running:
1388 return GEN_RUNNING
1389 if generator.gi_frame is None:
1390 return GEN_CLOSED
1391 if generator.gi_frame.f_lasti == -1:
1392 return GEN_CREATED
1393 return GEN_SUSPENDED
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07001394
1395
Nick Coghlan04e2e3f2012-06-23 19:52:05 +10001396def getgeneratorlocals(generator):
1397 """
1398 Get the mapping of generator local variables to their current values.
1399
1400 A dict is returned, with the keys the local variable names and values the
1401 bound values."""
1402
1403 if not isgenerator(generator):
1404 raise TypeError("'{!r}' is not a Python generator".format(generator))
1405
1406 frame = getattr(generator, "gi_frame", None)
1407 if frame is not None:
1408 return generator.gi_frame.f_locals
1409 else:
1410 return {}
1411
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07001412###############################################################################
1413### Function Signature Object (PEP 362)
1414###############################################################################
1415
1416
1417_WrapperDescriptor = type(type.__call__)
1418_MethodWrapper = type(all.__call__)
1419
1420_NonUserDefinedCallables = (_WrapperDescriptor,
1421 _MethodWrapper,
1422 types.BuiltinFunctionType)
1423
1424
1425def _get_user_defined_method(cls, method_name):
1426 try:
1427 meth = getattr(cls, method_name)
1428 except AttributeError:
1429 return
1430 else:
1431 if not isinstance(meth, _NonUserDefinedCallables):
1432 # Once '__signature__' will be added to 'C'-level
1433 # callables, this check won't be necessary
1434 return meth
1435
1436
1437def signature(obj):
1438 '''Get a signature object for the passed callable.'''
1439
1440 if not callable(obj):
1441 raise TypeError('{!r} is not a callable object'.format(obj))
1442
1443 if isinstance(obj, types.MethodType):
1444 # In this case we skip the first parameter of the underlying
1445 # function (usually `self` or `cls`).
1446 sig = signature(obj.__func__)
1447 return sig.replace(parameters=tuple(sig.parameters.values())[1:])
1448
Nick Coghlane8c45d62013-07-28 20:00:01 +10001449 # Was this function wrapped by a decorator?
1450 obj = unwrap(obj, stop=(lambda f: hasattr(f, "__signature__")))
1451
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07001452 try:
1453 sig = obj.__signature__
1454 except AttributeError:
1455 pass
1456 else:
1457 if sig is not None:
1458 return sig
1459
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07001460
1461 if isinstance(obj, types.FunctionType):
1462 return Signature.from_function(obj)
1463
1464 if isinstance(obj, functools.partial):
1465 sig = signature(obj.func)
1466
1467 new_params = OrderedDict(sig.parameters.items())
1468
1469 partial_args = obj.args or ()
1470 partial_keywords = obj.keywords or {}
1471 try:
1472 ba = sig.bind_partial(*partial_args, **partial_keywords)
1473 except TypeError as ex:
1474 msg = 'partial object {!r} has incorrect arguments'.format(obj)
1475 raise ValueError(msg) from ex
1476
1477 for arg_name, arg_value in ba.arguments.items():
1478 param = new_params[arg_name]
1479 if arg_name in partial_keywords:
1480 # We set a new default value, because the following code
1481 # is correct:
1482 #
1483 # >>> def foo(a): print(a)
1484 # >>> print(partial(partial(foo, a=10), a=20)())
1485 # 20
1486 # >>> print(partial(partial(foo, a=10), a=20)(a=30))
1487 # 30
1488 #
1489 # So, with 'partial' objects, passing a keyword argument is
1490 # like setting a new default value for the corresponding
1491 # parameter
1492 #
1493 # We also mark this parameter with '_partial_kwarg'
1494 # flag. Later, in '_bind', the 'default' value of this
1495 # parameter will be added to 'kwargs', to simulate
1496 # the 'functools.partial' real call.
1497 new_params[arg_name] = param.replace(default=arg_value,
1498 _partial_kwarg=True)
1499
1500 elif (param.kind not in (_VAR_KEYWORD, _VAR_POSITIONAL) and
1501 not param._partial_kwarg):
1502 new_params.pop(arg_name)
1503
1504 return sig.replace(parameters=new_params.values())
1505
1506 sig = None
1507 if isinstance(obj, type):
1508 # obj is a class or a metaclass
1509
1510 # First, let's see if it has an overloaded __call__ defined
1511 # in its metaclass
1512 call = _get_user_defined_method(type(obj), '__call__')
1513 if call is not None:
1514 sig = signature(call)
1515 else:
1516 # Now we check if the 'obj' class has a '__new__' method
1517 new = _get_user_defined_method(obj, '__new__')
1518 if new is not None:
1519 sig = signature(new)
1520 else:
1521 # Finally, we should have at least __init__ implemented
1522 init = _get_user_defined_method(obj, '__init__')
1523 if init is not None:
1524 sig = signature(init)
1525 elif not isinstance(obj, _NonUserDefinedCallables):
1526 # An object with __call__
1527 # We also check that the 'obj' is not an instance of
1528 # _WrapperDescriptor or _MethodWrapper to avoid
1529 # infinite recursion (and even potential segfault)
1530 call = _get_user_defined_method(type(obj), '__call__')
1531 if call is not None:
1532 sig = signature(call)
1533
1534 if sig is not None:
1535 # For classes and objects we skip the first parameter of their
1536 # __call__, __new__, or __init__ methods
1537 return sig.replace(parameters=tuple(sig.parameters.values())[1:])
1538
1539 if isinstance(obj, types.BuiltinFunctionType):
1540 # Raise a nicer error message for builtins
1541 msg = 'no signature found for builtin function {!r}'.format(obj)
1542 raise ValueError(msg)
1543
1544 raise ValueError('callable {!r} is not supported by signature'.format(obj))
1545
1546
1547class _void:
1548 '''A private marker - used in Parameter & Signature'''
1549
1550
1551class _empty:
1552 pass
1553
1554
1555class _ParameterKind(int):
1556 def __new__(self, *args, name):
1557 obj = int.__new__(self, *args)
1558 obj._name = name
1559 return obj
1560
1561 def __str__(self):
1562 return self._name
1563
1564 def __repr__(self):
1565 return '<_ParameterKind: {!r}>'.format(self._name)
1566
1567
1568_POSITIONAL_ONLY = _ParameterKind(0, name='POSITIONAL_ONLY')
1569_POSITIONAL_OR_KEYWORD = _ParameterKind(1, name='POSITIONAL_OR_KEYWORD')
1570_VAR_POSITIONAL = _ParameterKind(2, name='VAR_POSITIONAL')
1571_KEYWORD_ONLY = _ParameterKind(3, name='KEYWORD_ONLY')
1572_VAR_KEYWORD = _ParameterKind(4, name='VAR_KEYWORD')
1573
1574
1575class Parameter:
1576 '''Represents a parameter in a function signature.
1577
1578 Has the following public attributes:
1579
1580 * name : str
1581 The name of the parameter as a string.
1582 * default : object
1583 The default value for the parameter if specified. If the
1584 parameter has no default value, this attribute is not set.
1585 * annotation
1586 The annotation for the parameter if specified. If the
1587 parameter has no annotation, this attribute is not set.
1588 * kind : str
1589 Describes how argument values are bound to the parameter.
1590 Possible values: `Parameter.POSITIONAL_ONLY`,
1591 `Parameter.POSITIONAL_OR_KEYWORD`, `Parameter.VAR_POSITIONAL`,
1592 `Parameter.KEYWORD_ONLY`, `Parameter.VAR_KEYWORD`.
1593 '''
1594
1595 __slots__ = ('_name', '_kind', '_default', '_annotation', '_partial_kwarg')
1596
1597 POSITIONAL_ONLY = _POSITIONAL_ONLY
1598 POSITIONAL_OR_KEYWORD = _POSITIONAL_OR_KEYWORD
1599 VAR_POSITIONAL = _VAR_POSITIONAL
1600 KEYWORD_ONLY = _KEYWORD_ONLY
1601 VAR_KEYWORD = _VAR_KEYWORD
1602
1603 empty = _empty
1604
1605 def __init__(self, name, kind, *, default=_empty, annotation=_empty,
1606 _partial_kwarg=False):
1607
1608 if kind not in (_POSITIONAL_ONLY, _POSITIONAL_OR_KEYWORD,
1609 _VAR_POSITIONAL, _KEYWORD_ONLY, _VAR_KEYWORD):
1610 raise ValueError("invalid value for 'Parameter.kind' attribute")
1611 self._kind = kind
1612
1613 if default is not _empty:
1614 if kind in (_VAR_POSITIONAL, _VAR_KEYWORD):
1615 msg = '{} parameters cannot have default values'.format(kind)
1616 raise ValueError(msg)
1617 self._default = default
1618 self._annotation = annotation
1619
1620 if name is None:
1621 if kind != _POSITIONAL_ONLY:
1622 raise ValueError("None is not a valid name for a "
1623 "non-positional-only parameter")
1624 self._name = name
1625 else:
1626 name = str(name)
1627 if kind != _POSITIONAL_ONLY and not name.isidentifier():
1628 msg = '{!r} is not a valid parameter name'.format(name)
1629 raise ValueError(msg)
1630 self._name = name
1631
1632 self._partial_kwarg = _partial_kwarg
1633
1634 @property
1635 def name(self):
1636 return self._name
1637
1638 @property
1639 def default(self):
1640 return self._default
1641
1642 @property
1643 def annotation(self):
1644 return self._annotation
1645
1646 @property
1647 def kind(self):
1648 return self._kind
1649
1650 def replace(self, *, name=_void, kind=_void, annotation=_void,
1651 default=_void, _partial_kwarg=_void):
1652 '''Creates a customized copy of the Parameter.'''
1653
1654 if name is _void:
1655 name = self._name
1656
1657 if kind is _void:
1658 kind = self._kind
1659
1660 if annotation is _void:
1661 annotation = self._annotation
1662
1663 if default is _void:
1664 default = self._default
1665
1666 if _partial_kwarg is _void:
1667 _partial_kwarg = self._partial_kwarg
1668
1669 return type(self)(name, kind, default=default, annotation=annotation,
1670 _partial_kwarg=_partial_kwarg)
1671
1672 def __str__(self):
1673 kind = self.kind
1674
1675 formatted = self._name
1676 if kind == _POSITIONAL_ONLY:
1677 if formatted is None:
1678 formatted = ''
1679 formatted = '<{}>'.format(formatted)
1680
1681 # Add annotation and default value
1682 if self._annotation is not _empty:
1683 formatted = '{}:{}'.format(formatted,
1684 formatannotation(self._annotation))
1685
1686 if self._default is not _empty:
1687 formatted = '{}={}'.format(formatted, repr(self._default))
1688
1689 if kind == _VAR_POSITIONAL:
1690 formatted = '*' + formatted
1691 elif kind == _VAR_KEYWORD:
1692 formatted = '**' + formatted
1693
1694 return formatted
1695
1696 def __repr__(self):
1697 return '<{} at {:#x} {!r}>'.format(self.__class__.__name__,
1698 id(self), self.name)
1699
1700 def __eq__(self, other):
1701 return (issubclass(other.__class__, Parameter) and
1702 self._name == other._name and
1703 self._kind == other._kind and
1704 self._default == other._default and
1705 self._annotation == other._annotation)
1706
1707 def __ne__(self, other):
1708 return not self.__eq__(other)
1709
1710
1711class BoundArguments:
1712 '''Result of `Signature.bind` call. Holds the mapping of arguments
1713 to the function's parameters.
1714
1715 Has the following public attributes:
1716
1717 * arguments : OrderedDict
1718 An ordered mutable mapping of parameters' names to arguments' values.
1719 Does not contain arguments' default values.
1720 * signature : Signature
1721 The Signature object that created this instance.
1722 * args : tuple
1723 Tuple of positional arguments values.
1724 * kwargs : dict
1725 Dict of keyword arguments values.
1726 '''
1727
1728 def __init__(self, signature, arguments):
1729 self.arguments = arguments
1730 self._signature = signature
1731
1732 @property
1733 def signature(self):
1734 return self._signature
1735
1736 @property
1737 def args(self):
1738 args = []
1739 for param_name, param in self._signature.parameters.items():
1740 if (param.kind in (_VAR_KEYWORD, _KEYWORD_ONLY) or
1741 param._partial_kwarg):
1742 # Keyword arguments mapped by 'functools.partial'
1743 # (Parameter._partial_kwarg is True) are mapped
1744 # in 'BoundArguments.kwargs', along with VAR_KEYWORD &
1745 # KEYWORD_ONLY
1746 break
1747
1748 try:
1749 arg = self.arguments[param_name]
1750 except KeyError:
1751 # We're done here. Other arguments
1752 # will be mapped in 'BoundArguments.kwargs'
1753 break
1754 else:
1755 if param.kind == _VAR_POSITIONAL:
1756 # *args
1757 args.extend(arg)
1758 else:
1759 # plain argument
1760 args.append(arg)
1761
1762 return tuple(args)
1763
1764 @property
1765 def kwargs(self):
1766 kwargs = {}
1767 kwargs_started = False
1768 for param_name, param in self._signature.parameters.items():
1769 if not kwargs_started:
1770 if (param.kind in (_VAR_KEYWORD, _KEYWORD_ONLY) or
1771 param._partial_kwarg):
1772 kwargs_started = True
1773 else:
1774 if param_name not in self.arguments:
1775 kwargs_started = True
1776 continue
1777
1778 if not kwargs_started:
1779 continue
1780
1781 try:
1782 arg = self.arguments[param_name]
1783 except KeyError:
1784 pass
1785 else:
1786 if param.kind == _VAR_KEYWORD:
1787 # **kwargs
1788 kwargs.update(arg)
1789 else:
1790 # plain keyword argument
1791 kwargs[param_name] = arg
1792
1793 return kwargs
1794
1795 def __eq__(self, other):
1796 return (issubclass(other.__class__, BoundArguments) and
1797 self.signature == other.signature and
1798 self.arguments == other.arguments)
1799
1800 def __ne__(self, other):
1801 return not self.__eq__(other)
1802
1803
1804class Signature:
1805 '''A Signature object represents the overall signature of a function.
1806 It stores a Parameter object for each parameter accepted by the
1807 function, as well as information specific to the function itself.
1808
1809 A Signature object has the following public attributes and methods:
1810
1811 * parameters : OrderedDict
1812 An ordered mapping of parameters' names to the corresponding
1813 Parameter objects (keyword-only arguments are in the same order
1814 as listed in `code.co_varnames`).
1815 * return_annotation : object
1816 The annotation for the return type of the function if specified.
1817 If the function has no annotation for its return type, this
1818 attribute is not set.
1819 * bind(*args, **kwargs) -> BoundArguments
1820 Creates a mapping from positional and keyword arguments to
1821 parameters.
1822 * bind_partial(*args, **kwargs) -> BoundArguments
1823 Creates a partial mapping from positional and keyword arguments
1824 to parameters (simulating 'functools.partial' behavior.)
1825 '''
1826
1827 __slots__ = ('_return_annotation', '_parameters')
1828
1829 _parameter_cls = Parameter
1830 _bound_arguments_cls = BoundArguments
1831
1832 empty = _empty
1833
1834 def __init__(self, parameters=None, *, return_annotation=_empty,
1835 __validate_parameters__=True):
1836 '''Constructs Signature from the given list of Parameter
1837 objects and 'return_annotation'. All arguments are optional.
1838 '''
1839
1840 if parameters is None:
1841 params = OrderedDict()
1842 else:
1843 if __validate_parameters__:
1844 params = OrderedDict()
1845 top_kind = _POSITIONAL_ONLY
1846
1847 for idx, param in enumerate(parameters):
1848 kind = param.kind
1849 if kind < top_kind:
1850 msg = 'wrong parameter order: {} before {}'
1851 msg = msg.format(top_kind, param.kind)
1852 raise ValueError(msg)
1853 else:
1854 top_kind = kind
1855
1856 name = param.name
1857 if name is None:
1858 name = str(idx)
1859 param = param.replace(name=name)
1860
1861 if name in params:
1862 msg = 'duplicate parameter name: {!r}'.format(name)
1863 raise ValueError(msg)
1864 params[name] = param
1865 else:
1866 params = OrderedDict(((param.name, param)
1867 for param in parameters))
1868
1869 self._parameters = types.MappingProxyType(params)
1870 self._return_annotation = return_annotation
1871
1872 @classmethod
1873 def from_function(cls, func):
1874 '''Constructs Signature for the given python function'''
1875
1876 if not isinstance(func, types.FunctionType):
1877 raise TypeError('{!r} is not a Python function'.format(func))
1878
1879 Parameter = cls._parameter_cls
1880
1881 # Parameter information.
1882 func_code = func.__code__
1883 pos_count = func_code.co_argcount
1884 arg_names = func_code.co_varnames
1885 positional = tuple(arg_names[:pos_count])
1886 keyword_only_count = func_code.co_kwonlyargcount
1887 keyword_only = arg_names[pos_count:(pos_count + keyword_only_count)]
1888 annotations = func.__annotations__
1889 defaults = func.__defaults__
1890 kwdefaults = func.__kwdefaults__
1891
1892 if defaults:
1893 pos_default_count = len(defaults)
1894 else:
1895 pos_default_count = 0
1896
1897 parameters = []
1898
1899 # Non-keyword-only parameters w/o defaults.
1900 non_default_count = pos_count - pos_default_count
1901 for name in positional[:non_default_count]:
1902 annotation = annotations.get(name, _empty)
1903 parameters.append(Parameter(name, annotation=annotation,
1904 kind=_POSITIONAL_OR_KEYWORD))
1905
1906 # ... w/ defaults.
1907 for offset, name in enumerate(positional[non_default_count:]):
1908 annotation = annotations.get(name, _empty)
1909 parameters.append(Parameter(name, annotation=annotation,
1910 kind=_POSITIONAL_OR_KEYWORD,
1911 default=defaults[offset]))
1912
1913 # *args
1914 if func_code.co_flags & 0x04:
1915 name = arg_names[pos_count + keyword_only_count]
1916 annotation = annotations.get(name, _empty)
1917 parameters.append(Parameter(name, annotation=annotation,
1918 kind=_VAR_POSITIONAL))
1919
1920 # Keyword-only parameters.
1921 for name in keyword_only:
1922 default = _empty
1923 if kwdefaults is not None:
1924 default = kwdefaults.get(name, _empty)
1925
1926 annotation = annotations.get(name, _empty)
1927 parameters.append(Parameter(name, annotation=annotation,
1928 kind=_KEYWORD_ONLY,
1929 default=default))
1930 # **kwargs
1931 if func_code.co_flags & 0x08:
1932 index = pos_count + keyword_only_count
1933 if func_code.co_flags & 0x04:
1934 index += 1
1935
1936 name = arg_names[index]
1937 annotation = annotations.get(name, _empty)
1938 parameters.append(Parameter(name, annotation=annotation,
1939 kind=_VAR_KEYWORD))
1940
1941 return cls(parameters,
1942 return_annotation=annotations.get('return', _empty),
1943 __validate_parameters__=False)
1944
1945 @property
1946 def parameters(self):
1947 return self._parameters
1948
1949 @property
1950 def return_annotation(self):
1951 return self._return_annotation
1952
1953 def replace(self, *, parameters=_void, return_annotation=_void):
1954 '''Creates a customized copy of the Signature.
1955 Pass 'parameters' and/or 'return_annotation' arguments
1956 to override them in the new copy.
1957 '''
1958
1959 if parameters is _void:
1960 parameters = self.parameters.values()
1961
1962 if return_annotation is _void:
1963 return_annotation = self._return_annotation
1964
1965 return type(self)(parameters,
1966 return_annotation=return_annotation)
1967
1968 def __eq__(self, other):
1969 if (not issubclass(type(other), Signature) or
1970 self.return_annotation != other.return_annotation or
1971 len(self.parameters) != len(other.parameters)):
1972 return False
1973
1974 other_positions = {param: idx
1975 for idx, param in enumerate(other.parameters.keys())}
1976
1977 for idx, (param_name, param) in enumerate(self.parameters.items()):
1978 if param.kind == _KEYWORD_ONLY:
1979 try:
1980 other_param = other.parameters[param_name]
1981 except KeyError:
1982 return False
1983 else:
1984 if param != other_param:
1985 return False
1986 else:
1987 try:
1988 other_idx = other_positions[param_name]
1989 except KeyError:
1990 return False
1991 else:
1992 if (idx != other_idx or
1993 param != other.parameters[param_name]):
1994 return False
1995
1996 return True
1997
1998 def __ne__(self, other):
1999 return not self.__eq__(other)
2000
2001 def _bind(self, args, kwargs, *, partial=False):
2002 '''Private method. Don't use directly.'''
2003
2004 arguments = OrderedDict()
2005
2006 parameters = iter(self.parameters.values())
2007 parameters_ex = ()
2008 arg_vals = iter(args)
2009
2010 if partial:
2011 # Support for binding arguments to 'functools.partial' objects.
2012 # See 'functools.partial' case in 'signature()' implementation
2013 # for details.
2014 for param_name, param in self.parameters.items():
2015 if (param._partial_kwarg and param_name not in kwargs):
2016 # Simulating 'functools.partial' behavior
2017 kwargs[param_name] = param.default
2018
2019 while True:
2020 # Let's iterate through the positional arguments and corresponding
2021 # parameters
2022 try:
2023 arg_val = next(arg_vals)
2024 except StopIteration:
2025 # No more positional arguments
2026 try:
2027 param = next(parameters)
2028 except StopIteration:
2029 # No more parameters. That's it. Just need to check that
2030 # we have no `kwargs` after this while loop
2031 break
2032 else:
2033 if param.kind == _VAR_POSITIONAL:
2034 # That's OK, just empty *args. Let's start parsing
2035 # kwargs
2036 break
2037 elif param.name in kwargs:
2038 if param.kind == _POSITIONAL_ONLY:
2039 msg = '{arg!r} parameter is positional only, ' \
2040 'but was passed as a keyword'
2041 msg = msg.format(arg=param.name)
2042 raise TypeError(msg) from None
2043 parameters_ex = (param,)
2044 break
2045 elif (param.kind == _VAR_KEYWORD or
2046 param.default is not _empty):
2047 # That's fine too - we have a default value for this
2048 # parameter. So, lets start parsing `kwargs`, starting
2049 # with the current parameter
2050 parameters_ex = (param,)
2051 break
2052 else:
2053 if partial:
2054 parameters_ex = (param,)
2055 break
2056 else:
2057 msg = '{arg!r} parameter lacking default value'
2058 msg = msg.format(arg=param.name)
2059 raise TypeError(msg) from None
2060 else:
2061 # We have a positional argument to process
2062 try:
2063 param = next(parameters)
2064 except StopIteration:
2065 raise TypeError('too many positional arguments') from None
2066 else:
2067 if param.kind in (_VAR_KEYWORD, _KEYWORD_ONLY):
2068 # Looks like we have no parameter for this positional
2069 # argument
2070 raise TypeError('too many positional arguments')
2071
2072 if param.kind == _VAR_POSITIONAL:
2073 # We have an '*args'-like argument, let's fill it with
2074 # all positional arguments we have left and move on to
2075 # the next phase
2076 values = [arg_val]
2077 values.extend(arg_vals)
2078 arguments[param.name] = tuple(values)
2079 break
2080
2081 if param.name in kwargs:
2082 raise TypeError('multiple values for argument '
2083 '{arg!r}'.format(arg=param.name))
2084
2085 arguments[param.name] = arg_val
2086
2087 # Now, we iterate through the remaining parameters to process
2088 # keyword arguments
2089 kwargs_param = None
2090 for param in itertools.chain(parameters_ex, parameters):
2091 if param.kind == _POSITIONAL_ONLY:
2092 # This should never happen in case of a properly built
2093 # Signature object (but let's have this check here
2094 # to ensure correct behaviour just in case)
2095 raise TypeError('{arg!r} parameter is positional only, '
2096 'but was passed as a keyword'. \
2097 format(arg=param.name))
2098
2099 if param.kind == _VAR_KEYWORD:
2100 # Memorize that we have a '**kwargs'-like parameter
2101 kwargs_param = param
2102 continue
2103
2104 param_name = param.name
2105 try:
2106 arg_val = kwargs.pop(param_name)
2107 except KeyError:
2108 # We have no value for this parameter. It's fine though,
2109 # if it has a default value, or it is an '*args'-like
2110 # parameter, left alone by the processing of positional
2111 # arguments.
2112 if (not partial and param.kind != _VAR_POSITIONAL and
2113 param.default is _empty):
2114 raise TypeError('{arg!r} parameter lacking default value'. \
2115 format(arg=param_name)) from None
2116
2117 else:
2118 arguments[param_name] = arg_val
2119
2120 if kwargs:
2121 if kwargs_param is not None:
2122 # Process our '**kwargs'-like parameter
2123 arguments[kwargs_param.name] = kwargs
2124 else:
2125 raise TypeError('too many keyword arguments')
2126
2127 return self._bound_arguments_cls(self, arguments)
2128
Antoine Pitroubd41d1b2013-01-29 21:20:57 +01002129 def bind(__bind_self, *args, **kwargs):
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002130 '''Get a BoundArguments object, that maps the passed `args`
2131 and `kwargs` to the function's signature. Raises `TypeError`
2132 if the passed arguments can not be bound.
2133 '''
Antoine Pitroubd41d1b2013-01-29 21:20:57 +01002134 return __bind_self._bind(args, kwargs)
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002135
Antoine Pitroubd41d1b2013-01-29 21:20:57 +01002136 def bind_partial(__bind_self, *args, **kwargs):
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002137 '''Get a BoundArguments object, that partially maps the
2138 passed `args` and `kwargs` to the function's signature.
2139 Raises `TypeError` if the passed arguments can not be bound.
2140 '''
Antoine Pitroubd41d1b2013-01-29 21:20:57 +01002141 return __bind_self._bind(args, kwargs, partial=True)
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002142
2143 def __str__(self):
2144 result = []
2145 render_kw_only_separator = True
2146 for idx, param in enumerate(self.parameters.values()):
2147 formatted = str(param)
2148
2149 kind = param.kind
2150 if kind == _VAR_POSITIONAL:
2151 # OK, we have an '*args'-like parameter, so we won't need
2152 # a '*' to separate keyword-only arguments
2153 render_kw_only_separator = False
2154 elif kind == _KEYWORD_ONLY and render_kw_only_separator:
2155 # We have a keyword-only parameter to render and we haven't
2156 # rendered an '*args'-like parameter before, so add a '*'
2157 # separator to the parameters list ("foo(arg1, *, arg2)" case)
2158 result.append('*')
2159 # This condition should be only triggered once, so
2160 # reset the flag
2161 render_kw_only_separator = False
2162
2163 result.append(formatted)
2164
2165 rendered = '({})'.format(', '.join(result))
2166
2167 if self.return_annotation is not _empty:
2168 anno = formatannotation(self.return_annotation)
2169 rendered += ' -> {}'.format(anno)
2170
2171 return rendered
Nick Coghlanf94a16b2013-09-22 22:46:49 +10002172
2173def _main():
2174 """ Logic for inspecting an object given at command line """
2175 import argparse
2176 import importlib
2177
2178 parser = argparse.ArgumentParser()
2179 parser.add_argument(
2180 'object',
2181 help="The object to be analysed. "
2182 "It supports the 'module:qualname' syntax")
2183 parser.add_argument(
2184 '-d', '--details', action='store_true',
2185 help='Display info about the module rather than its source code')
2186
2187 args = parser.parse_args()
2188
2189 target = args.object
2190 mod_name, has_attrs, attrs = target.partition(":")
2191 try:
2192 obj = module = importlib.import_module(mod_name)
2193 except Exception as exc:
2194 msg = "Failed to import {} ({}: {})".format(mod_name,
2195 type(exc).__name__,
2196 exc)
2197 print(msg, file=sys.stderr)
2198 exit(2)
2199
2200 if has_attrs:
2201 parts = attrs.split(".")
2202 obj = module
2203 for part in parts:
2204 obj = getattr(obj, part)
2205
2206 if module.__name__ in sys.builtin_module_names:
2207 print("Can't get info for builtin modules.", file=sys.stderr)
2208 exit(1)
2209
2210 if args.details:
2211 print('Target: {}'.format(target))
2212 print('Origin: {}'.format(getsourcefile(module)))
2213 print('Cached: {}'.format(module.__cached__))
2214 if obj is module:
2215 print('Loader: {}'.format(repr(module.__loader__)))
2216 if hasattr(module, '__path__'):
2217 print('Submodule search path: {}'.format(module.__path__))
2218 else:
2219 try:
2220 __, lineno = findsource(obj)
2221 except Exception:
2222 pass
2223 else:
2224 print('Line: {}'.format(lineno))
2225
2226 print('\n')
2227 else:
2228 print(getsource(obj))
2229
2230
2231if __name__ == "__main__":
2232 _main()