blob: 7cd70115c62d6f074f4a333e739f1f8709894569 [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)
272 # add any virtual attributes to the list of names if object is a class
273 # this may result in duplicate entries if, for example, a virtual
274 # attribute with the same name as a member property exists
275 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
332 defined.
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)])
338 possible_bases = (cls,) + mro + metamro
Tim Peters13b49d32001-09-23 02:00:29 +0000339 names = dir(cls)
Ethan Furmane03ea372013-09-25 07:14:41 -0700340 # add any virtual attributes to the list of names
341 # this may result in duplicate entries if, for example, a virtual
342 # attribute with the same name as a member property exists
Ethan Furman63c141c2013-10-18 00:27:39 -0700343 for base in mro:
Ethan Furmane03ea372013-09-25 07:14:41 -0700344 for k, v in base.__dict__.items():
345 if isinstance(v, types.DynamicClassAttribute):
346 names.append(k)
Tim Peters13b49d32001-09-23 02:00:29 +0000347 result = []
Ethan Furmane03ea372013-09-25 07:14:41 -0700348 processed = set()
349 sentinel = object()
Tim Peters13b49d32001-09-23 02:00:29 +0000350 for name in names:
Antoine Pitrou86a8a9a2011-12-21 09:57:40 +0100351 # Get the object associated with the name, and where it was defined.
Ethan Furmane03ea372013-09-25 07:14:41 -0700352 # Normal objects will be looked up with both getattr and directly in
353 # its class' dict (in case getattr fails [bug #1785], and also to look
354 # for a docstring).
355 # For VirtualAttributes on the second pass we only look in the
356 # class's dict.
357 #
Tim Peters13b49d32001-09-23 02:00:29 +0000358 # Getting an obj from the __dict__ sometimes reveals more than
359 # using getattr. Static and class methods are dramatic examples.
Antoine Pitrou86a8a9a2011-12-21 09:57:40 +0100360 homecls = None
Ethan Furmane03ea372013-09-25 07:14:41 -0700361 get_obj = sentinel
362 dict_obj = sentinel
Ethan Furmane03ea372013-09-25 07:14:41 -0700363 if name not in processed:
364 try:
365 get_obj = getattr(cls, name)
366 except Exception as exc:
367 pass
368 else:
Ethan Furmane03ea372013-09-25 07:14:41 -0700369 homecls = getattr(get_obj, "__objclass__", homecls)
370 if homecls not in possible_bases:
371 # if the resulting object does not live somewhere in the
Ethan Furman63c141c2013-10-18 00:27:39 -0700372 # mro, drop it and search the mro manually
Ethan Furmane03ea372013-09-25 07:14:41 -0700373 homecls = None
Ethan Furman63c141c2013-10-18 00:27:39 -0700374 last_cls = None
375 last_obj = None
376 for srch_cls in ((cls,) + mro):
377 srch_obj = getattr(srch_cls, name, None)
378 if srch_obj is get_obj:
379 last_cls = srch_cls
380 last_obj = srch_obj
381 if last_cls is not None:
382 homecls = last_cls
Ethan Furmane03ea372013-09-25 07:14:41 -0700383 for base in possible_bases:
384 if name in base.__dict__:
385 dict_obj = base.__dict__[name]
386 homecls = homecls or base
387 break
Ethan Furman63c141c2013-10-18 00:27:39 -0700388 if homecls is None:
389 # unable to locate the attribute anywhere, most likely due to
390 # buggy custom __dir__; discard and move on
391 continue
Ethan Furmane03ea372013-09-25 07:14:41 -0700392 # Classify the object or its descriptor.
393 if get_obj is not sentinel:
394 obj = get_obj
395 else:
396 obj = dict_obj
Ethan Furman63c141c2013-10-18 00:27:39 -0700397 if isinstance(dict_obj, staticmethod):
Tim Peters13b49d32001-09-23 02:00:29 +0000398 kind = "static method"
Ethan Furman63c141c2013-10-18 00:27:39 -0700399 elif isinstance(dict_obj, classmethod):
Tim Peters13b49d32001-09-23 02:00:29 +0000400 kind = "class method"
401 elif isinstance(obj, property):
402 kind = "property"
Ethan Furmane03ea372013-09-25 07:14:41 -0700403 elif isfunction(obj) or ismethoddescriptor(obj):
Tim Peters13b49d32001-09-23 02:00:29 +0000404 kind = "method"
Antoine Pitrou86a8a9a2011-12-21 09:57:40 +0100405 else:
Ethan Furmane03ea372013-09-25 07:14:41 -0700406 kind = "data"
Christian Heimes25bb7832008-01-11 16:17:00 +0000407 result.append(Attribute(name, kind, homecls, obj))
Ethan Furmane03ea372013-09-25 07:14:41 -0700408 processed.add(name)
Tim Peters13b49d32001-09-23 02:00:29 +0000409 return result
410
Tim Peterse0b2d7a2001-09-22 06:10:55 +0000411# ----------------------------------------------------------- class helpers
Tim Peterse0b2d7a2001-09-22 06:10:55 +0000412
413def getmro(cls):
414 "Return tuple of base classes (including cls) in method resolution order."
Benjamin Petersonb82c8e52010-11-04 00:38:49 +0000415 return cls.__mro__
Tim Peterse0b2d7a2001-09-22 06:10:55 +0000416
Nick Coghlane8c45d62013-07-28 20:00:01 +1000417# -------------------------------------------------------- function helpers
418
419def unwrap(func, *, stop=None):
420 """Get the object wrapped by *func*.
421
422 Follows the chain of :attr:`__wrapped__` attributes returning the last
423 object in the chain.
424
425 *stop* is an optional callback accepting an object in the wrapper chain
426 as its sole argument that allows the unwrapping to be terminated early if
427 the callback returns a true value. If the callback never returns a true
428 value, the last object in the chain is returned as usual. For example,
429 :func:`signature` uses this to stop unwrapping if any object in the
430 chain has a ``__signature__`` attribute defined.
431
432 :exc:`ValueError` is raised if a cycle is encountered.
433
434 """
435 if stop is None:
436 def _is_wrapper(f):
437 return hasattr(f, '__wrapped__')
438 else:
439 def _is_wrapper(f):
440 return hasattr(f, '__wrapped__') and not stop(f)
441 f = func # remember the original func for error reporting
442 memo = {id(f)} # Memoise by id to tolerate non-hashable objects
443 while _is_wrapper(func):
444 func = func.__wrapped__
445 id_func = id(func)
446 if id_func in memo:
447 raise ValueError('wrapper loop when unwrapping {!r}'.format(f))
448 memo.add(id_func)
449 return func
450
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000451# -------------------------------------------------- source code extraction
452def indentsize(line):
453 """Return the indent size, in spaces, at the start of a line of text."""
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000454 expline = line.expandtabs()
455 return len(expline) - len(expline.lstrip())
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000456
457def getdoc(object):
458 """Get the documentation string for an object.
459
460 All tabs are expanded to spaces. To clean up docstrings that are
461 indented to line up with blocks of code, any whitespace than can be
462 uniformly removed from the second line onwards is removed."""
Tim Peters24008312002-03-17 18:56:20 +0000463 try:
464 doc = object.__doc__
465 except AttributeError:
466 return None
Guido van Rossum3172c5d2007-10-16 18:12:55 +0000467 if not isinstance(doc, str):
Tim Peters24008312002-03-17 18:56:20 +0000468 return None
Georg Brandl0c77a822008-06-10 16:37:50 +0000469 return cleandoc(doc)
470
471def cleandoc(doc):
472 """Clean up indentation from docstrings.
473
474 Any whitespace that can be uniformly removed from the second line
475 onwards is removed."""
Tim Peters24008312002-03-17 18:56:20 +0000476 try:
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000477 lines = doc.expandtabs().split('\n')
Tim Peters24008312002-03-17 18:56:20 +0000478 except UnicodeError:
479 return None
480 else:
Ka-Ping Yeea59ef7b2002-11-30 03:53:15 +0000481 # Find minimum indentation of any non-blank lines after first line.
Christian Heimesa37d4c62007-12-04 23:02:19 +0000482 margin = sys.maxsize
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000483 for line in lines[1:]:
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000484 content = len(line.lstrip())
Ka-Ping Yeea59ef7b2002-11-30 03:53:15 +0000485 if content:
486 indent = len(line) - content
487 margin = min(margin, indent)
488 # Remove indentation.
489 if lines:
490 lines[0] = lines[0].lstrip()
Christian Heimesa37d4c62007-12-04 23:02:19 +0000491 if margin < sys.maxsize:
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000492 for i in range(1, len(lines)): lines[i] = lines[i][margin:]
Ka-Ping Yeea59ef7b2002-11-30 03:53:15 +0000493 # Remove any trailing or leading blank lines.
494 while lines and not lines[-1]:
495 lines.pop()
496 while lines and not lines[0]:
497 lines.pop(0)
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000498 return '\n'.join(lines)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000499
500def getfile(object):
Ka-Ping Yeec113c242001-03-02 02:08:53 +0000501 """Work out which source or compiled file an object was defined in."""
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000502 if ismodule(object):
503 if hasattr(object, '__file__'):
504 return object.__file__
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +0000505 raise TypeError('{!r} is a built-in module'.format(object))
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000506 if isclass(object):
Ka-Ping Yeec99e0f12001-04-13 12:10:40 +0000507 object = sys.modules.get(object.__module__)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000508 if hasattr(object, '__file__'):
509 return object.__file__
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +0000510 raise TypeError('{!r} is a built-in class'.format(object))
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000511 if ismethod(object):
Christian Heimesff737952007-11-27 10:40:20 +0000512 object = object.__func__
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000513 if isfunction(object):
Neal Norwitz221085d2007-02-25 20:55:47 +0000514 object = object.__code__
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000515 if istraceback(object):
516 object = object.tb_frame
517 if isframe(object):
518 object = object.f_code
519 if iscode(object):
520 return object.co_filename
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +0000521 raise TypeError('{!r} is not a module, class, method, '
522 'function, traceback, frame, or code object'.format(object))
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000523
Christian Heimes25bb7832008-01-11 16:17:00 +0000524ModuleInfo = namedtuple('ModuleInfo', 'name suffix mode module_type')
525
Ka-Ping Yee4d6fc7f2001-04-10 11:43:00 +0000526def getmoduleinfo(path):
527 """Get the module name, suffix, mode, and module type for a given file."""
Brett Cannoncb66eb02012-05-11 12:58:42 -0400528 warnings.warn('inspect.getmoduleinfo() is deprecated', DeprecationWarning,
529 2)
Brett Cannone4f41de2013-06-16 13:13:40 -0400530 with warnings.catch_warnings():
531 warnings.simplefilter('ignore', PendingDeprecationWarning)
532 import imp
Ka-Ping Yee4d6fc7f2001-04-10 11:43:00 +0000533 filename = os.path.basename(path)
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000534 suffixes = [(-len(suffix), suffix, mode, mtype)
535 for suffix, mode, mtype in imp.get_suffixes()]
Ka-Ping Yee4d6fc7f2001-04-10 11:43:00 +0000536 suffixes.sort() # try longest suffixes first, in case they overlap
537 for neglen, suffix, mode, mtype in suffixes:
538 if filename[neglen:] == suffix:
Christian Heimes25bb7832008-01-11 16:17:00 +0000539 return ModuleInfo(filename[:neglen], suffix, mode, mtype)
Ka-Ping Yee4d6fc7f2001-04-10 11:43:00 +0000540
541def getmodulename(path):
542 """Return the module name for a given file, or None."""
Nick Coghlan76e07702012-07-18 23:14:57 +1000543 fname = os.path.basename(path)
544 # Check for paths that look like an actual module file
545 suffixes = [(-len(suffix), suffix)
546 for suffix in importlib.machinery.all_suffixes()]
547 suffixes.sort() # try longest suffixes first, in case they overlap
548 for neglen, suffix in suffixes:
549 if fname.endswith(suffix):
550 return fname[:neglen]
551 return None
Ka-Ping Yee4d6fc7f2001-04-10 11:43:00 +0000552
Ka-Ping Yeec113c242001-03-02 02:08:53 +0000553def getsourcefile(object):
R. David Murraya1b37402010-06-17 02:04:29 +0000554 """Return the filename that can be used to locate an object's source.
555 Return None if no way can be identified to get the source.
556 """
Ka-Ping Yeec113c242001-03-02 02:08:53 +0000557 filename = getfile(object)
Brett Cannoncb66eb02012-05-11 12:58:42 -0400558 all_bytecode_suffixes = importlib.machinery.DEBUG_BYTECODE_SUFFIXES[:]
559 all_bytecode_suffixes += importlib.machinery.OPTIMIZED_BYTECODE_SUFFIXES[:]
560 if any(filename.endswith(s) for s in all_bytecode_suffixes):
561 filename = (os.path.splitext(filename)[0] +
562 importlib.machinery.SOURCE_SUFFIXES[0])
563 elif any(filename.endswith(s) for s in
564 importlib.machinery.EXTENSION_SUFFIXES):
565 return None
Thomas Wouters477c8d52006-05-27 19:21:47 +0000566 if os.path.exists(filename):
567 return filename
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000568 # only return a non-existent filename if the module has a PEP 302 loader
Brett Cannon4c14b5d2013-05-04 13:56:58 -0400569 if getattr(getmodule(object, filename), '__loader__', None) is not None:
Ka-Ping Yeec113c242001-03-02 02:08:53 +0000570 return filename
R. David Murraya1b37402010-06-17 02:04:29 +0000571 # or it is in the linecache
572 if filename in linecache.cache:
573 return filename
Ka-Ping Yeec113c242001-03-02 02:08:53 +0000574
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000575def getabsfile(object, _filename=None):
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000576 """Return an absolute path to the source or compiled file for an object.
Ka-Ping Yeec113c242001-03-02 02:08:53 +0000577
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000578 The idea is for each object to have a unique origin, so this routine
579 normalizes the result as much as possible."""
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000580 if _filename is None:
581 _filename = getsourcefile(object) or getfile(object)
582 return os.path.normcase(os.path.abspath(_filename))
Ka-Ping Yeec113c242001-03-02 02:08:53 +0000583
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000584modulesbyfile = {}
Thomas Wouters89f507f2006-12-13 04:49:30 +0000585_filesbymodname = {}
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000586
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000587def getmodule(object, _filename=None):
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000588 """Return the module an object was defined in, or None if not found."""
Ka-Ping Yee202c99b2001-04-13 09:15:08 +0000589 if ismodule(object):
590 return object
Johannes Gijsbers93245262004-09-11 15:53:22 +0000591 if hasattr(object, '__module__'):
Ka-Ping Yee8b58b842001-03-01 13:56:16 +0000592 return sys.modules.get(object.__module__)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000593 # Try the filename to modulename cache
594 if _filename is not None and _filename in modulesbyfile:
595 return sys.modules.get(modulesbyfile[_filename])
596 # Try the cache again with the absolute file name
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000597 try:
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000598 file = getabsfile(object, _filename)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000599 except TypeError:
600 return None
Raymond Hettinger54f02222002-06-01 14:18:47 +0000601 if file in modulesbyfile:
Ka-Ping Yeeb38bbbd2003-03-28 16:29:50 +0000602 return sys.modules.get(modulesbyfile[file])
Thomas Wouters89f507f2006-12-13 04:49:30 +0000603 # Update the filename to module name cache and check yet again
604 # Copy sys.modules in order to cope with changes while iterating
Éric Araujoa74f8ef2011-11-29 16:58:53 +0100605 for modname, module in list(sys.modules.items()):
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000606 if ismodule(module) and hasattr(module, '__file__'):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000607 f = module.__file__
608 if f == _filesbymodname.get(modname, None):
609 # Have already mapped this module, so skip it
610 continue
611 _filesbymodname[modname] = f
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000612 f = getabsfile(module)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000613 # Always map to the name the module knows itself by
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000614 modulesbyfile[f] = modulesbyfile[
615 os.path.realpath(f)] = module.__name__
Raymond Hettinger54f02222002-06-01 14:18:47 +0000616 if file in modulesbyfile:
Ka-Ping Yeeb38bbbd2003-03-28 16:29:50 +0000617 return sys.modules.get(modulesbyfile[file])
Thomas Wouters89f507f2006-12-13 04:49:30 +0000618 # Check the main module
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000619 main = sys.modules['__main__']
Brett Cannon4a671fe2003-06-15 22:33:28 +0000620 if not hasattr(object, '__name__'):
621 return None
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000622 if hasattr(main, object.__name__):
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000623 mainobject = getattr(main, object.__name__)
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000624 if mainobject is object:
625 return main
Thomas Wouters89f507f2006-12-13 04:49:30 +0000626 # Check builtins
Georg Brandl1a3284e2007-12-02 09:40:06 +0000627 builtin = sys.modules['builtins']
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000628 if hasattr(builtin, object.__name__):
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000629 builtinobject = getattr(builtin, object.__name__)
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000630 if builtinobject is object:
631 return builtin
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000632
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000633def findsource(object):
634 """Return the entire source file and starting line number for an object.
635
636 The argument may be a module, class, method, function, traceback, frame,
637 or code object. The source code is returned as a list of all the lines
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200638 in the file and the line number indexes a line in that list. An OSError
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000639 is raised if the source code cannot be retrieved."""
Benjamin Peterson9620cc02011-06-11 15:53:11 -0500640
641 file = getfile(object)
642 sourcefile = getsourcefile(object)
Ezio Melotti1b145922013-03-30 05:17:24 +0200643 if not sourcefile and file[:1] + file[-1:] != '<>':
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200644 raise OSError('source code not available')
Benjamin Peterson9620cc02011-06-11 15:53:11 -0500645 file = sourcefile if sourcefile else file
646
Thomas Wouters89f507f2006-12-13 04:49:30 +0000647 module = getmodule(object, file)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000648 if module:
649 lines = linecache.getlines(file, module.__dict__)
650 else:
651 lines = linecache.getlines(file)
Neil Schemenauerf06f8532002-03-23 23:51:04 +0000652 if not lines:
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200653 raise OSError('could not get source code')
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000654
655 if ismodule(object):
656 return lines, 0
657
658 if isclass(object):
659 name = object.__name__
Thomas Wouters89f507f2006-12-13 04:49:30 +0000660 pat = re.compile(r'^(\s*)class\s*' + name + r'\b')
661 # make some effort to find the best matching class definition:
662 # use the one with the least indentation, which is the one
663 # that's most probably not inside a function definition.
664 candidates = []
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000665 for i in range(len(lines)):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000666 match = pat.match(lines[i])
667 if match:
668 # if it's at toplevel, it's already the best one
669 if lines[i][0] == 'c':
670 return lines, i
671 # else add whitespace to candidate list
672 candidates.append((match.group(1), i))
673 if candidates:
674 # this will sort by whitespace, and by line number,
675 # less whitespace first
676 candidates.sort()
677 return lines, candidates[0][1]
Jeremy Hyltonab919022003-06-27 18:41:20 +0000678 else:
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200679 raise OSError('could not find class definition')
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000680
681 if ismethod(object):
Christian Heimesff737952007-11-27 10:40:20 +0000682 object = object.__func__
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000683 if isfunction(object):
Neal Norwitz221085d2007-02-25 20:55:47 +0000684 object = object.__code__
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000685 if istraceback(object):
686 object = object.tb_frame
687 if isframe(object):
688 object = object.f_code
689 if iscode(object):
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000690 if not hasattr(object, 'co_firstlineno'):
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200691 raise OSError('could not find function definition')
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000692 lnum = object.co_firstlineno - 1
Johannes Gijsbers1542f342004-12-12 16:46:28 +0000693 pat = re.compile(r'^(\s*def\s)|(.*(?<!\w)lambda(:|\s))|^(\s*@)')
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000694 while lnum > 0:
Ka-Ping Yeea6e59712001-03-10 09:31:55 +0000695 if pat.match(lines[lnum]): break
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000696 lnum = lnum - 1
697 return lines, lnum
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200698 raise OSError('could not find code object')
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000699
700def getcomments(object):
Jeremy Hyltonb4c17c82002-03-28 23:01:56 +0000701 """Get lines of comments immediately preceding an object's source code.
702
703 Returns None when source can't be found.
704 """
705 try:
706 lines, lnum = findsource(object)
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200707 except (OSError, TypeError):
Jeremy Hyltonb4c17c82002-03-28 23:01:56 +0000708 return None
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000709
710 if ismodule(object):
711 # Look for a comment block at the top of the file.
712 start = 0
Ka-Ping Yeeb910efe2001-04-12 13:17:17 +0000713 if lines and lines[0][:2] == '#!': start = 1
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000714 while start < len(lines) and lines[start].strip() in ('', '#'):
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000715 start = start + 1
Ka-Ping Yeeb910efe2001-04-12 13:17:17 +0000716 if start < len(lines) and lines[start][:1] == '#':
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000717 comments = []
718 end = start
719 while end < len(lines) and lines[end][:1] == '#':
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000720 comments.append(lines[end].expandtabs())
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000721 end = end + 1
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000722 return ''.join(comments)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000723
724 # Look for a preceding block of comments at the same indentation.
725 elif lnum > 0:
726 indent = indentsize(lines[lnum])
727 end = lnum - 1
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000728 if end >= 0 and lines[end].lstrip()[:1] == '#' and \
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000729 indentsize(lines[end]) == indent:
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000730 comments = [lines[end].expandtabs().lstrip()]
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000731 if end > 0:
732 end = end - 1
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000733 comment = lines[end].expandtabs().lstrip()
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000734 while comment[:1] == '#' and indentsize(lines[end]) == indent:
735 comments[:0] = [comment]
736 end = end - 1
737 if end < 0: break
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000738 comment = lines[end].expandtabs().lstrip()
739 while comments and comments[0].strip() == '#':
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000740 comments[:1] = []
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000741 while comments and comments[-1].strip() == '#':
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000742 comments[-1:] = []
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000743 return ''.join(comments)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000744
Tim Peters4efb6e92001-06-29 23:51:08 +0000745class EndOfBlock(Exception): pass
746
747class BlockFinder:
748 """Provide a tokeneater() method to detect the end of a code block."""
749 def __init__(self):
750 self.indent = 0
Johannes Gijsbersa5855d52005-03-12 16:37:11 +0000751 self.islambda = False
Johannes Gijsbers1542f342004-12-12 16:46:28 +0000752 self.started = False
753 self.passline = False
Armin Rigodd5c0232005-09-25 11:45:45 +0000754 self.last = 1
Tim Peters4efb6e92001-06-29 23:51:08 +0000755
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000756 def tokeneater(self, type, token, srowcol, erowcol, line):
Tim Peters4efb6e92001-06-29 23:51:08 +0000757 if not self.started:
Armin Rigodd5c0232005-09-25 11:45:45 +0000758 # look for the first "def", "class" or "lambda"
Johannes Gijsbers1542f342004-12-12 16:46:28 +0000759 if token in ("def", "class", "lambda"):
Johannes Gijsbersa5855d52005-03-12 16:37:11 +0000760 if token == "lambda":
761 self.islambda = True
Johannes Gijsbers1542f342004-12-12 16:46:28 +0000762 self.started = True
Armin Rigodd5c0232005-09-25 11:45:45 +0000763 self.passline = True # skip to the end of the line
Tim Peters4efb6e92001-06-29 23:51:08 +0000764 elif type == tokenize.NEWLINE:
Armin Rigodd5c0232005-09-25 11:45:45 +0000765 self.passline = False # stop skipping when a NEWLINE is seen
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000766 self.last = srowcol[0]
Armin Rigodd5c0232005-09-25 11:45:45 +0000767 if self.islambda: # lambdas always end at the first NEWLINE
768 raise EndOfBlock
Johannes Gijsbers1542f342004-12-12 16:46:28 +0000769 elif self.passline:
770 pass
Tim Peters4efb6e92001-06-29 23:51:08 +0000771 elif type == tokenize.INDENT:
772 self.indent = self.indent + 1
Johannes Gijsbers1542f342004-12-12 16:46:28 +0000773 self.passline = True
Tim Peters4efb6e92001-06-29 23:51:08 +0000774 elif type == tokenize.DEDENT:
775 self.indent = self.indent - 1
Armin Rigodd5c0232005-09-25 11:45:45 +0000776 # the end of matching indent/dedent pairs end a block
777 # (note that this only works for "def"/"class" blocks,
778 # not e.g. for "if: else:" or "try: finally:" blocks)
779 if self.indent <= 0:
780 raise EndOfBlock
781 elif self.indent == 0 and type not in (tokenize.COMMENT, tokenize.NL):
782 # any other token on the same indentation level end the previous
783 # block as well, except the pseudo-tokens COMMENT and NL.
784 raise EndOfBlock
Tim Peters4efb6e92001-06-29 23:51:08 +0000785
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000786def getblock(lines):
787 """Extract the block of code at the top of the given list of lines."""
Armin Rigodd5c0232005-09-25 11:45:45 +0000788 blockfinder = BlockFinder()
Tim Peters4efb6e92001-06-29 23:51:08 +0000789 try:
Trent Nelson428de652008-03-18 22:41:35 +0000790 tokens = tokenize.generate_tokens(iter(lines).__next__)
791 for _token in tokens:
792 blockfinder.tokeneater(*_token)
Armin Rigodd5c0232005-09-25 11:45:45 +0000793 except (EndOfBlock, IndentationError):
794 pass
795 return lines[:blockfinder.last]
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000796
797def getsourcelines(object):
798 """Return a list of source lines and starting line number for an object.
799
800 The argument may be a module, class, method, function, traceback, frame,
801 or code object. The source code is returned as a list of the lines
802 corresponding to the object and the line number indicates where in the
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200803 original source file the first line of code was found. An OSError is
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000804 raised if the source code cannot be retrieved."""
805 lines, lnum = findsource(object)
806
807 if ismodule(object): return lines, 0
808 else: return getblock(lines[lnum:]), lnum + 1
809
810def getsource(object):
811 """Return the text of the source code for an object.
812
813 The argument may be a module, class, method, function, traceback, frame,
814 or code object. The source code is returned as a single string. An
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200815 OSError is raised if the source code cannot be retrieved."""
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000816 lines, lnum = getsourcelines(object)
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000817 return ''.join(lines)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000818
819# --------------------------------------------------- class tree extraction
820def walktree(classes, children, parent):
821 """Recursive helper function for getclasstree()."""
822 results = []
Raymond Hettingera1a992c2005-03-11 06:46:45 +0000823 classes.sort(key=attrgetter('__module__', '__name__'))
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000824 for c in classes:
825 results.append((c, c.__bases__))
Raymond Hettinger54f02222002-06-01 14:18:47 +0000826 if c in children:
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000827 results.append(walktree(children[c], children, c))
828 return results
829
Georg Brandl5ce83a02009-06-01 17:23:51 +0000830def getclasstree(classes, unique=False):
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000831 """Arrange the given list of classes into a hierarchy of nested lists.
832
833 Where a nested list appears, it contains classes derived from the class
834 whose entry immediately precedes the list. Each entry is a 2-tuple
835 containing a class and a tuple of its base classes. If the 'unique'
836 argument is true, exactly one entry appears in the returned structure
837 for each class in the given list. Otherwise, classes using multiple
838 inheritance and their descendants will appear multiple times."""
839 children = {}
840 roots = []
841 for c in classes:
842 if c.__bases__:
843 for parent in c.__bases__:
Raymond Hettinger54f02222002-06-01 14:18:47 +0000844 if not parent in children:
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000845 children[parent] = []
Serhiy Storchaka362c1b52013-09-05 17:14:32 +0300846 if c not in children[parent]:
847 children[parent].append(c)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000848 if unique and parent in classes: break
849 elif c not in roots:
850 roots.append(c)
Raymond Hettingere0d49722002-06-02 18:55:56 +0000851 for parent in children:
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000852 if parent not in classes:
853 roots.append(parent)
854 return walktree(roots, children, None)
855
856# ------------------------------------------------ argument list extraction
Christian Heimes25bb7832008-01-11 16:17:00 +0000857Arguments = namedtuple('Arguments', 'args, varargs, varkw')
858
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000859def getargs(co):
860 """Get information about the arguments accepted by a code object.
861
Guido van Rossum2e65f892007-02-28 22:03:49 +0000862 Three things are returned: (args, varargs, varkw), where
Georg Brandlc1c4bf82010-10-15 16:07:41 +0000863 'args' is the list of argument names. Keyword-only arguments are
864 appended. 'varargs' and 'varkw' are the names of the * and **
865 arguments or None."""
Guido van Rossum2e65f892007-02-28 22:03:49 +0000866 args, varargs, kwonlyargs, varkw = _getfullargs(co)
Christian Heimes25bb7832008-01-11 16:17:00 +0000867 return Arguments(args + kwonlyargs, varargs, varkw)
Guido van Rossum2e65f892007-02-28 22:03:49 +0000868
869def _getfullargs(co):
870 """Get information about the arguments accepted by a code object.
871
872 Four things are returned: (args, varargs, kwonlyargs, varkw), where
Georg Brandlc1c4bf82010-10-15 16:07:41 +0000873 'args' and 'kwonlyargs' are lists of argument names, and 'varargs'
874 and 'varkw' are the names of the * and ** arguments or None."""
Jeremy Hylton64967882003-06-27 18:14:39 +0000875
876 if not iscode(co):
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +0000877 raise TypeError('{!r} is not a code object'.format(co))
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000878
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000879 nargs = co.co_argcount
880 names = co.co_varnames
Guido van Rossum2e65f892007-02-28 22:03:49 +0000881 nkwargs = co.co_kwonlyargcount
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000882 args = list(names[:nargs])
Guido van Rossum2e65f892007-02-28 22:03:49 +0000883 kwonlyargs = list(names[nargs:nargs+nkwargs])
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000884 step = 0
885
Guido van Rossum2e65f892007-02-28 22:03:49 +0000886 nargs += nkwargs
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000887 varargs = None
888 if co.co_flags & CO_VARARGS:
889 varargs = co.co_varnames[nargs]
890 nargs = nargs + 1
891 varkw = None
892 if co.co_flags & CO_VARKEYWORDS:
893 varkw = co.co_varnames[nargs]
Guido van Rossum2e65f892007-02-28 22:03:49 +0000894 return args, varargs, kwonlyargs, varkw
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000895
Christian Heimes25bb7832008-01-11 16:17:00 +0000896
897ArgSpec = namedtuple('ArgSpec', 'args varargs keywords defaults')
898
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000899def getargspec(func):
900 """Get the names and default values of a function's arguments.
901
902 A tuple of four things is returned: (args, varargs, varkw, defaults).
Georg Brandlc1c4bf82010-10-15 16:07:41 +0000903 'args' is a list of the argument names.
Guido van Rossum2e65f892007-02-28 22:03:49 +0000904 'args' will include keyword-only argument names.
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000905 'varargs' and 'varkw' are the names of the * and ** arguments or None.
Jeremy Hylton64967882003-06-27 18:14:39 +0000906 'defaults' is an n-tuple of the default values of the last n arguments.
Guido van Rossuma8add0e2007-05-14 22:03:55 +0000907
Guido van Rossum2e65f892007-02-28 22:03:49 +0000908 Use the getfullargspec() API for Python-3000 code, as annotations
909 and keyword arguments are supported. getargspec() will raise ValueError
910 if the func has either annotations or keyword arguments.
911 """
912
913 args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults, ann = \
914 getfullargspec(func)
915 if kwonlyargs or ann:
Collin Winterce36ad82007-08-30 01:19:48 +0000916 raise ValueError("Function has keyword-only arguments or annotations"
917 ", use getfullargspec() API which can support them")
Christian Heimes25bb7832008-01-11 16:17:00 +0000918 return ArgSpec(args, varargs, varkw, defaults)
919
920FullArgSpec = namedtuple('FullArgSpec',
Benjamin Peterson3d4ca742008-11-12 21:39:01 +0000921 'args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults, annotations')
Guido van Rossum2e65f892007-02-28 22:03:49 +0000922
923def getfullargspec(func):
924 """Get the names and default values of a function's arguments.
925
Brett Cannon504d8852007-09-07 02:12:14 +0000926 A tuple of seven things is returned:
927 (args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults annotations).
Georg Brandlc1c4bf82010-10-15 16:07:41 +0000928 'args' is a list of the argument names.
Guido van Rossum2e65f892007-02-28 22:03:49 +0000929 'varargs' and 'varkw' are the names of the * and ** arguments or None.
930 'defaults' is an n-tuple of the default values of the last n arguments.
931 'kwonlyargs' is a list of keyword-only argument names.
932 'kwonlydefaults' is a dictionary mapping names from kwonlyargs to defaults.
933 'annotations' is a dictionary mapping argument names to annotations.
Guido van Rossuma8add0e2007-05-14 22:03:55 +0000934
Guido van Rossum2e65f892007-02-28 22:03:49 +0000935 The first four items in the tuple correspond to getargspec().
Jeremy Hylton64967882003-06-27 18:14:39 +0000936 """
937
938 if ismethod(func):
Christian Heimesff737952007-11-27 10:40:20 +0000939 func = func.__func__
Jeremy Hylton64967882003-06-27 18:14:39 +0000940 if not isfunction(func):
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +0000941 raise TypeError('{!r} is not a Python function'.format(func))
Guido van Rossum2e65f892007-02-28 22:03:49 +0000942 args, varargs, kwonlyargs, varkw = _getfullargs(func.__code__)
Christian Heimes25bb7832008-01-11 16:17:00 +0000943 return FullArgSpec(args, varargs, varkw, func.__defaults__,
Guido van Rossum2e65f892007-02-28 22:03:49 +0000944 kwonlyargs, func.__kwdefaults__, func.__annotations__)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000945
Christian Heimes25bb7832008-01-11 16:17:00 +0000946ArgInfo = namedtuple('ArgInfo', 'args varargs keywords locals')
947
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000948def getargvalues(frame):
949 """Get information about arguments passed into a particular frame.
950
951 A tuple of four things is returned: (args, varargs, varkw, locals).
Georg Brandlc1c4bf82010-10-15 16:07:41 +0000952 'args' is a list of the argument names.
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000953 'varargs' and 'varkw' are the names of the * and ** arguments or None.
954 'locals' is the locals dictionary of the given frame."""
955 args, varargs, varkw = getargs(frame.f_code)
Benjamin Peterson1a6e0d02008-10-25 15:49:17 +0000956 return ArgInfo(args, varargs, varkw, frame.f_locals)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000957
Guido van Rossum2e65f892007-02-28 22:03:49 +0000958def formatannotation(annotation, base_module=None):
959 if isinstance(annotation, type):
Georg Brandl1a3284e2007-12-02 09:40:06 +0000960 if annotation.__module__ in ('builtins', base_module):
Guido van Rossum2e65f892007-02-28 22:03:49 +0000961 return annotation.__name__
962 return annotation.__module__+'.'+annotation.__name__
963 return repr(annotation)
Guido van Rossuma8add0e2007-05-14 22:03:55 +0000964
Guido van Rossum2e65f892007-02-28 22:03:49 +0000965def formatannotationrelativeto(object):
Guido van Rossuma8add0e2007-05-14 22:03:55 +0000966 module = getattr(object, '__module__', None)
967 def _formatannotation(annotation):
968 return formatannotation(annotation, module)
969 return _formatannotation
Guido van Rossum2e65f892007-02-28 22:03:49 +0000970
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000971def formatargspec(args, varargs=None, varkw=None, defaults=None,
Guido van Rossum2e65f892007-02-28 22:03:49 +0000972 kwonlyargs=(), kwonlydefaults={}, annotations={},
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000973 formatarg=str,
974 formatvarargs=lambda name: '*' + name,
975 formatvarkw=lambda name: '**' + name,
976 formatvalue=lambda value: '=' + repr(value),
Guido van Rossum2e65f892007-02-28 22:03:49 +0000977 formatreturns=lambda text: ' -> ' + text,
Georg Brandlc1c4bf82010-10-15 16:07:41 +0000978 formatannotation=formatannotation):
Guido van Rossuma8add0e2007-05-14 22:03:55 +0000979 """Format an argument spec from the values returned by getargspec
Guido van Rossum2e65f892007-02-28 22:03:49 +0000980 or getfullargspec.
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000981
Guido van Rossum2e65f892007-02-28 22:03:49 +0000982 The first seven arguments are (args, varargs, varkw, defaults,
983 kwonlyargs, kwonlydefaults, annotations). The other five arguments
984 are the corresponding optional formatting functions that are called to
985 turn names and values into strings. The last argument is an optional
986 function to format the sequence of arguments."""
987 def formatargandannotation(arg):
988 result = formatarg(arg)
989 if arg in annotations:
990 result += ': ' + formatannotation(annotations[arg])
991 return result
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000992 specs = []
993 if defaults:
994 firstdefault = len(args) - len(defaults)
Benjamin Petersonb58dda72009-01-18 22:27:04 +0000995 for i, arg in enumerate(args):
Georg Brandlc1c4bf82010-10-15 16:07:41 +0000996 spec = formatargandannotation(arg)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000997 if defaults and i >= firstdefault:
998 spec = spec + formatvalue(defaults[i - firstdefault])
999 specs.append(spec)
Raymond Hettinger936654b2002-06-01 03:06:31 +00001000 if varargs is not None:
Guido van Rossum2e65f892007-02-28 22:03:49 +00001001 specs.append(formatvarargs(formatargandannotation(varargs)))
1002 else:
1003 if kwonlyargs:
1004 specs.append('*')
1005 if kwonlyargs:
1006 for kwonlyarg in kwonlyargs:
1007 spec = formatargandannotation(kwonlyarg)
Benjamin Peterson9953a8d2009-01-17 04:15:01 +00001008 if kwonlydefaults and kwonlyarg in kwonlydefaults:
Guido van Rossum2e65f892007-02-28 22:03:49 +00001009 spec += formatvalue(kwonlydefaults[kwonlyarg])
1010 specs.append(spec)
Raymond Hettinger936654b2002-06-01 03:06:31 +00001011 if varkw is not None:
Guido van Rossum2e65f892007-02-28 22:03:49 +00001012 specs.append(formatvarkw(formatargandannotation(varkw)))
Neal Norwitz9d72bb42007-04-17 08:48:32 +00001013 result = '(' + ', '.join(specs) + ')'
Guido van Rossum2e65f892007-02-28 22:03:49 +00001014 if 'return' in annotations:
1015 result += formatreturns(formatannotation(annotations['return']))
1016 return result
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001017
1018def formatargvalues(args, varargs, varkw, locals,
1019 formatarg=str,
1020 formatvarargs=lambda name: '*' + name,
1021 formatvarkw=lambda name: '**' + name,
Georg Brandlc1c4bf82010-10-15 16:07:41 +00001022 formatvalue=lambda value: '=' + repr(value)):
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001023 """Format an argument spec from the 4 values returned by getargvalues.
1024
1025 The first four arguments are (args, varargs, varkw, locals). The
1026 next four arguments are the corresponding optional formatting functions
1027 that are called to turn names and values into strings. The ninth
1028 argument is an optional function to format the sequence of arguments."""
1029 def convert(name, locals=locals,
1030 formatarg=formatarg, formatvalue=formatvalue):
1031 return formatarg(name) + formatvalue(locals[name])
1032 specs = []
1033 for i in range(len(args)):
Georg Brandlc1c4bf82010-10-15 16:07:41 +00001034 specs.append(convert(args[i]))
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001035 if varargs:
1036 specs.append(formatvarargs(varargs) + formatvalue(locals[varargs]))
1037 if varkw:
1038 specs.append(formatvarkw(varkw) + formatvalue(locals[varkw]))
Neal Norwitz9d72bb42007-04-17 08:48:32 +00001039 return '(' + ', '.join(specs) + ')'
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001040
Benjamin Petersone109c702011-06-24 09:37:26 -05001041def _missing_arguments(f_name, argnames, pos, values):
1042 names = [repr(name) for name in argnames if name not in values]
1043 missing = len(names)
1044 if missing == 1:
1045 s = names[0]
1046 elif missing == 2:
1047 s = "{} and {}".format(*names)
1048 else:
1049 tail = ", {} and {}".format(names[-2:])
1050 del names[-2:]
1051 s = ", ".join(names) + tail
1052 raise TypeError("%s() missing %i required %s argument%s: %s" %
1053 (f_name, missing,
1054 "positional" if pos else "keyword-only",
1055 "" if missing == 1 else "s", s))
1056
1057def _too_many(f_name, args, kwonly, varargs, defcount, given, values):
Benjamin Petersonb204a422011-06-05 22:04:07 -05001058 atleast = len(args) - defcount
Benjamin Petersonb204a422011-06-05 22:04:07 -05001059 kwonly_given = len([arg for arg in kwonly if arg in values])
1060 if varargs:
1061 plural = atleast != 1
1062 sig = "at least %d" % (atleast,)
1063 elif defcount:
1064 plural = True
1065 sig = "from %d to %d" % (atleast, len(args))
1066 else:
1067 plural = len(args) != 1
1068 sig = str(len(args))
1069 kwonly_sig = ""
1070 if kwonly_given:
1071 msg = " positional argument%s (and %d keyword-only argument%s)"
1072 kwonly_sig = (msg % ("s" if given != 1 else "", kwonly_given,
1073 "s" if kwonly_given != 1 else ""))
1074 raise TypeError("%s() takes %s positional argument%s but %d%s %s given" %
1075 (f_name, sig, "s" if plural else "", given, kwonly_sig,
1076 "was" if given == 1 and not kwonly_given else "were"))
1077
Benjamin Peterson25cd7eb2010-03-30 18:42:32 +00001078def getcallargs(func, *positional, **named):
1079 """Get the mapping of arguments to values.
1080
1081 A dict is returned, with keys the function argument names (including the
1082 names of the * and ** arguments, if any), and values the respective bound
1083 values from 'positional' and 'named'."""
1084 spec = getfullargspec(func)
1085 args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults, ann = spec
1086 f_name = func.__name__
1087 arg2value = {}
1088
Benjamin Petersonb204a422011-06-05 22:04:07 -05001089
Benjamin Peterson25cd7eb2010-03-30 18:42:32 +00001090 if ismethod(func) and func.__self__ is not None:
1091 # implicit 'self' (or 'cls' for classmethods) argument
1092 positional = (func.__self__,) + positional
1093 num_pos = len(positional)
Benjamin Peterson25cd7eb2010-03-30 18:42:32 +00001094 num_args = len(args)
1095 num_defaults = len(defaults) if defaults else 0
Benjamin Peterson25cd7eb2010-03-30 18:42:32 +00001096
Benjamin Petersonb204a422011-06-05 22:04:07 -05001097 n = min(num_pos, num_args)
1098 for i in range(n):
1099 arg2value[args[i]] = positional[i]
1100 if varargs:
1101 arg2value[varargs] = tuple(positional[n:])
1102 possible_kwargs = set(args + kwonlyargs)
Benjamin Peterson25cd7eb2010-03-30 18:42:32 +00001103 if varkw:
Benjamin Petersonb204a422011-06-05 22:04:07 -05001104 arg2value[varkw] = {}
1105 for kw, value in named.items():
1106 if kw not in possible_kwargs:
1107 if not varkw:
1108 raise TypeError("%s() got an unexpected keyword argument %r" %
1109 (f_name, kw))
1110 arg2value[varkw][kw] = value
1111 continue
1112 if kw in arg2value:
1113 raise TypeError("%s() got multiple values for argument %r" %
1114 (f_name, kw))
1115 arg2value[kw] = value
1116 if num_pos > num_args and not varargs:
Benjamin Petersone109c702011-06-24 09:37:26 -05001117 _too_many(f_name, args, kwonlyargs, varargs, num_defaults,
1118 num_pos, arg2value)
Benjamin Petersonb204a422011-06-05 22:04:07 -05001119 if num_pos < num_args:
Benjamin Petersone109c702011-06-24 09:37:26 -05001120 req = args[:num_args - num_defaults]
1121 for arg in req:
Benjamin Petersonb204a422011-06-05 22:04:07 -05001122 if arg not in arg2value:
Benjamin Petersone109c702011-06-24 09:37:26 -05001123 _missing_arguments(f_name, req, True, arg2value)
Benjamin Petersonb204a422011-06-05 22:04:07 -05001124 for i, arg in enumerate(args[num_args - num_defaults:]):
1125 if arg not in arg2value:
1126 arg2value[arg] = defaults[i]
Benjamin Petersone109c702011-06-24 09:37:26 -05001127 missing = 0
Benjamin Petersonb204a422011-06-05 22:04:07 -05001128 for kwarg in kwonlyargs:
1129 if kwarg not in arg2value:
Benjamin Petersone109c702011-06-24 09:37:26 -05001130 if kwarg in kwonlydefaults:
1131 arg2value[kwarg] = kwonlydefaults[kwarg]
1132 else:
1133 missing += 1
1134 if missing:
1135 _missing_arguments(f_name, kwonlyargs, False, arg2value)
Benjamin Peterson25cd7eb2010-03-30 18:42:32 +00001136 return arg2value
1137
Nick Coghlan2f92e542012-06-23 19:39:55 +10001138ClosureVars = namedtuple('ClosureVars', 'nonlocals globals builtins unbound')
1139
1140def getclosurevars(func):
1141 """
1142 Get the mapping of free variables to their current values.
1143
Meador Inge8fda3592012-07-19 21:33:21 -05001144 Returns a named tuple of dicts mapping the current nonlocal, global
Nick Coghlan2f92e542012-06-23 19:39:55 +10001145 and builtin references as seen by the body of the function. A final
1146 set of unbound names that could not be resolved is also provided.
1147 """
1148
1149 if ismethod(func):
1150 func = func.__func__
1151
1152 if not isfunction(func):
1153 raise TypeError("'{!r}' is not a Python function".format(func))
1154
1155 code = func.__code__
1156 # Nonlocal references are named in co_freevars and resolved
1157 # by looking them up in __closure__ by positional index
1158 if func.__closure__ is None:
1159 nonlocal_vars = {}
1160 else:
1161 nonlocal_vars = {
1162 var : cell.cell_contents
1163 for var, cell in zip(code.co_freevars, func.__closure__)
1164 }
1165
1166 # Global and builtin references are named in co_names and resolved
1167 # by looking them up in __globals__ or __builtins__
1168 global_ns = func.__globals__
1169 builtin_ns = global_ns.get("__builtins__", builtins.__dict__)
1170 if ismodule(builtin_ns):
1171 builtin_ns = builtin_ns.__dict__
1172 global_vars = {}
1173 builtin_vars = {}
1174 unbound_names = set()
1175 for name in code.co_names:
1176 if name in ("None", "True", "False"):
1177 # Because these used to be builtins instead of keywords, they
1178 # may still show up as name references. We ignore them.
1179 continue
1180 try:
1181 global_vars[name] = global_ns[name]
1182 except KeyError:
1183 try:
1184 builtin_vars[name] = builtin_ns[name]
1185 except KeyError:
1186 unbound_names.add(name)
1187
1188 return ClosureVars(nonlocal_vars, global_vars,
1189 builtin_vars, unbound_names)
1190
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001191# -------------------------------------------------- stack frame extraction
Christian Heimes25bb7832008-01-11 16:17:00 +00001192
1193Traceback = namedtuple('Traceback', 'filename lineno function code_context index')
1194
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001195def getframeinfo(frame, context=1):
1196 """Get information about a frame or traceback object.
1197
1198 A tuple of five things is returned: the filename, the line number of
1199 the current line, the function name, a list of lines of context from
1200 the source code, and the index of the current line within that list.
1201 The optional second argument specifies the number of lines of context
1202 to return, which are centered around the current line."""
1203 if istraceback(frame):
Andrew M. Kuchlingba8b6bc2004-06-05 14:11:59 +00001204 lineno = frame.tb_lineno
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001205 frame = frame.tb_frame
Andrew M. Kuchlingba8b6bc2004-06-05 14:11:59 +00001206 else:
1207 lineno = frame.f_lineno
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001208 if not isframe(frame):
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00001209 raise TypeError('{!r} is not a frame or traceback object'.format(frame))
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001210
Neil Schemenauerf06f8532002-03-23 23:51:04 +00001211 filename = getsourcefile(frame) or getfile(frame)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001212 if context > 0:
Guido van Rossum54e54c62001-09-04 19:14:14 +00001213 start = lineno - 1 - context//2
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001214 try:
1215 lines, lnum = findsource(frame)
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02001216 except OSError:
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +00001217 lines = index = None
1218 else:
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001219 start = max(start, 1)
Raymond Hettingera0501712004-06-15 11:22:53 +00001220 start = max(0, min(start, len(lines) - context))
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001221 lines = lines[start:start+context]
Ka-Ping Yee59ade082001-03-01 03:55:35 +00001222 index = lineno - 1 - start
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001223 else:
1224 lines = index = None
1225
Christian Heimes25bb7832008-01-11 16:17:00 +00001226 return Traceback(filename, lineno, frame.f_code.co_name, lines, index)
Ka-Ping Yee59ade082001-03-01 03:55:35 +00001227
1228def getlineno(frame):
1229 """Get the line number from a frame object, allowing for optimization."""
Michael W. Hudsondd32a912002-08-15 14:59:02 +00001230 # FrameType.f_lineno is now a descriptor that grovels co_lnotab
1231 return frame.f_lineno
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001232
1233def getouterframes(frame, context=1):
1234 """Get a list of records for a frame and all higher (calling) frames.
1235
1236 Each record contains a frame object, filename, line number, function
1237 name, a list of lines of context, and index within the context."""
1238 framelist = []
1239 while frame:
1240 framelist.append((frame,) + getframeinfo(frame, context))
1241 frame = frame.f_back
1242 return framelist
1243
1244def getinnerframes(tb, context=1):
1245 """Get a list of records for a traceback's frame and all lower 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."""
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001249 framelist = []
1250 while tb:
1251 framelist.append((tb.tb_frame,) + getframeinfo(tb, context))
1252 tb = tb.tb_next
1253 return framelist
1254
Benjamin Peterson42ac4752010-08-09 13:05:35 +00001255def currentframe():
Benjamin Petersona3a3fc62010-08-09 15:49:56 +00001256 """Return the frame of the caller or None if this is not possible."""
Benjamin Peterson42ac4752010-08-09 13:05:35 +00001257 return sys._getframe(1) if hasattr(sys, "_getframe") else None
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001258
1259def stack(context=1):
1260 """Return a list of records for the stack above the caller's frame."""
Jeremy Hyltonab919022003-06-27 18:41:20 +00001261 return getouterframes(sys._getframe(1), context)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001262
1263def trace(context=1):
Tim Peters85ba6732001-02-28 08:26:44 +00001264 """Return a list of records for the stack below the current exception."""
Fred Draked451ec12002-04-26 02:29:55 +00001265 return getinnerframes(sys.exc_info()[2], context)
Michael Foord95fc51d2010-11-20 15:07:30 +00001266
1267
1268# ------------------------------------------------ static version of getattr
1269
1270_sentinel = object()
1271
Michael Foorde5162652010-11-20 16:40:44 +00001272def _static_getmro(klass):
1273 return type.__dict__['__mro__'].__get__(klass)
1274
Michael Foord95fc51d2010-11-20 15:07:30 +00001275def _check_instance(obj, attr):
1276 instance_dict = {}
1277 try:
1278 instance_dict = object.__getattribute__(obj, "__dict__")
1279 except AttributeError:
1280 pass
Michael Foorddcebe0f2011-03-15 19:20:44 -04001281 return dict.get(instance_dict, attr, _sentinel)
Michael Foord95fc51d2010-11-20 15:07:30 +00001282
1283
1284def _check_class(klass, attr):
Michael Foorde5162652010-11-20 16:40:44 +00001285 for entry in _static_getmro(klass):
Michael Foorda51623b2011-12-18 22:01:40 +00001286 if _shadowed_dict(type(entry)) is _sentinel:
Michael Foorddcebe0f2011-03-15 19:20:44 -04001287 try:
1288 return entry.__dict__[attr]
1289 except KeyError:
1290 pass
Michael Foord95fc51d2010-11-20 15:07:30 +00001291 return _sentinel
1292
Michael Foord35184ed2010-11-20 16:58:30 +00001293def _is_type(obj):
1294 try:
1295 _static_getmro(obj)
1296 except TypeError:
1297 return False
1298 return True
1299
Michael Foorddcebe0f2011-03-15 19:20:44 -04001300def _shadowed_dict(klass):
1301 dict_attr = type.__dict__["__dict__"]
1302 for entry in _static_getmro(klass):
1303 try:
1304 class_dict = dict_attr.__get__(entry)["__dict__"]
1305 except KeyError:
1306 pass
1307 else:
1308 if not (type(class_dict) is types.GetSetDescriptorType and
1309 class_dict.__name__ == "__dict__" and
1310 class_dict.__objclass__ is entry):
Michael Foorda51623b2011-12-18 22:01:40 +00001311 return class_dict
1312 return _sentinel
Michael Foord95fc51d2010-11-20 15:07:30 +00001313
1314def getattr_static(obj, attr, default=_sentinel):
1315 """Retrieve attributes without triggering dynamic lookup via the
1316 descriptor protocol, __getattr__ or __getattribute__.
1317
1318 Note: this function may not be able to retrieve all attributes
1319 that getattr can fetch (like dynamically created attributes)
1320 and may find attributes that getattr can't (like descriptors
1321 that raise AttributeError). It can also return descriptor objects
1322 instead of instance members in some cases. See the
1323 documentation for details.
1324 """
1325 instance_result = _sentinel
Michael Foord35184ed2010-11-20 16:58:30 +00001326 if not _is_type(obj):
Michael Foordcc7ebb82010-11-20 16:20:16 +00001327 klass = type(obj)
Michael Foorda51623b2011-12-18 22:01:40 +00001328 dict_attr = _shadowed_dict(klass)
1329 if (dict_attr is _sentinel or
1330 type(dict_attr) is types.MemberDescriptorType):
Michael Foorddcebe0f2011-03-15 19:20:44 -04001331 instance_result = _check_instance(obj, attr)
Michael Foord95fc51d2010-11-20 15:07:30 +00001332 else:
1333 klass = obj
1334
1335 klass_result = _check_class(klass, attr)
1336
1337 if instance_result is not _sentinel and klass_result is not _sentinel:
1338 if (_check_class(type(klass_result), '__get__') is not _sentinel and
1339 _check_class(type(klass_result), '__set__') is not _sentinel):
1340 return klass_result
1341
1342 if instance_result is not _sentinel:
1343 return instance_result
1344 if klass_result is not _sentinel:
1345 return klass_result
1346
1347 if obj is klass:
1348 # for types we check the metaclass too
Michael Foorde5162652010-11-20 16:40:44 +00001349 for entry in _static_getmro(type(klass)):
Michael Foord3ba95f82011-12-22 01:13:37 +00001350 if _shadowed_dict(type(entry)) is _sentinel:
1351 try:
1352 return entry.__dict__[attr]
1353 except KeyError:
1354 pass
Michael Foord95fc51d2010-11-20 15:07:30 +00001355 if default is not _sentinel:
1356 return default
1357 raise AttributeError(attr)
Nick Coghlane0f04652010-11-21 03:44:04 +00001358
1359
Nick Coghlan04e2e3f2012-06-23 19:52:05 +10001360# ------------------------------------------------ generator introspection
1361
Nick Coghlan7921b9f2010-11-30 06:36:04 +00001362GEN_CREATED = 'GEN_CREATED'
1363GEN_RUNNING = 'GEN_RUNNING'
1364GEN_SUSPENDED = 'GEN_SUSPENDED'
1365GEN_CLOSED = 'GEN_CLOSED'
Nick Coghlane0f04652010-11-21 03:44:04 +00001366
1367def getgeneratorstate(generator):
1368 """Get current state of a generator-iterator.
1369
1370 Possible states are:
1371 GEN_CREATED: Waiting to start execution.
1372 GEN_RUNNING: Currently being executed by the interpreter.
1373 GEN_SUSPENDED: Currently suspended at a yield expression.
1374 GEN_CLOSED: Execution has completed.
1375 """
1376 if generator.gi_running:
1377 return GEN_RUNNING
1378 if generator.gi_frame is None:
1379 return GEN_CLOSED
1380 if generator.gi_frame.f_lasti == -1:
1381 return GEN_CREATED
1382 return GEN_SUSPENDED
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07001383
1384
Nick Coghlan04e2e3f2012-06-23 19:52:05 +10001385def getgeneratorlocals(generator):
1386 """
1387 Get the mapping of generator local variables to their current values.
1388
1389 A dict is returned, with the keys the local variable names and values the
1390 bound values."""
1391
1392 if not isgenerator(generator):
1393 raise TypeError("'{!r}' is not a Python generator".format(generator))
1394
1395 frame = getattr(generator, "gi_frame", None)
1396 if frame is not None:
1397 return generator.gi_frame.f_locals
1398 else:
1399 return {}
1400
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07001401###############################################################################
1402### Function Signature Object (PEP 362)
1403###############################################################################
1404
1405
1406_WrapperDescriptor = type(type.__call__)
1407_MethodWrapper = type(all.__call__)
1408
1409_NonUserDefinedCallables = (_WrapperDescriptor,
1410 _MethodWrapper,
1411 types.BuiltinFunctionType)
1412
1413
1414def _get_user_defined_method(cls, method_name):
1415 try:
1416 meth = getattr(cls, method_name)
1417 except AttributeError:
1418 return
1419 else:
1420 if not isinstance(meth, _NonUserDefinedCallables):
1421 # Once '__signature__' will be added to 'C'-level
1422 # callables, this check won't be necessary
1423 return meth
1424
1425
1426def signature(obj):
1427 '''Get a signature object for the passed callable.'''
1428
1429 if not callable(obj):
1430 raise TypeError('{!r} is not a callable object'.format(obj))
1431
1432 if isinstance(obj, types.MethodType):
1433 # In this case we skip the first parameter of the underlying
1434 # function (usually `self` or `cls`).
1435 sig = signature(obj.__func__)
1436 return sig.replace(parameters=tuple(sig.parameters.values())[1:])
1437
Nick Coghlane8c45d62013-07-28 20:00:01 +10001438 # Was this function wrapped by a decorator?
1439 obj = unwrap(obj, stop=(lambda f: hasattr(f, "__signature__")))
1440
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07001441 try:
1442 sig = obj.__signature__
1443 except AttributeError:
1444 pass
1445 else:
1446 if sig is not None:
1447 return sig
1448
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07001449
1450 if isinstance(obj, types.FunctionType):
1451 return Signature.from_function(obj)
1452
1453 if isinstance(obj, functools.partial):
1454 sig = signature(obj.func)
1455
1456 new_params = OrderedDict(sig.parameters.items())
1457
1458 partial_args = obj.args or ()
1459 partial_keywords = obj.keywords or {}
1460 try:
1461 ba = sig.bind_partial(*partial_args, **partial_keywords)
1462 except TypeError as ex:
1463 msg = 'partial object {!r} has incorrect arguments'.format(obj)
1464 raise ValueError(msg) from ex
1465
1466 for arg_name, arg_value in ba.arguments.items():
1467 param = new_params[arg_name]
1468 if arg_name in partial_keywords:
1469 # We set a new default value, because the following code
1470 # is correct:
1471 #
1472 # >>> def foo(a): print(a)
1473 # >>> print(partial(partial(foo, a=10), a=20)())
1474 # 20
1475 # >>> print(partial(partial(foo, a=10), a=20)(a=30))
1476 # 30
1477 #
1478 # So, with 'partial' objects, passing a keyword argument is
1479 # like setting a new default value for the corresponding
1480 # parameter
1481 #
1482 # We also mark this parameter with '_partial_kwarg'
1483 # flag. Later, in '_bind', the 'default' value of this
1484 # parameter will be added to 'kwargs', to simulate
1485 # the 'functools.partial' real call.
1486 new_params[arg_name] = param.replace(default=arg_value,
1487 _partial_kwarg=True)
1488
1489 elif (param.kind not in (_VAR_KEYWORD, _VAR_POSITIONAL) and
1490 not param._partial_kwarg):
1491 new_params.pop(arg_name)
1492
1493 return sig.replace(parameters=new_params.values())
1494
1495 sig = None
1496 if isinstance(obj, type):
1497 # obj is a class or a metaclass
1498
1499 # First, let's see if it has an overloaded __call__ defined
1500 # in its metaclass
1501 call = _get_user_defined_method(type(obj), '__call__')
1502 if call is not None:
1503 sig = signature(call)
1504 else:
1505 # Now we check if the 'obj' class has a '__new__' method
1506 new = _get_user_defined_method(obj, '__new__')
1507 if new is not None:
1508 sig = signature(new)
1509 else:
1510 # Finally, we should have at least __init__ implemented
1511 init = _get_user_defined_method(obj, '__init__')
1512 if init is not None:
1513 sig = signature(init)
1514 elif not isinstance(obj, _NonUserDefinedCallables):
1515 # An object with __call__
1516 # We also check that the 'obj' is not an instance of
1517 # _WrapperDescriptor or _MethodWrapper to avoid
1518 # infinite recursion (and even potential segfault)
1519 call = _get_user_defined_method(type(obj), '__call__')
1520 if call is not None:
1521 sig = signature(call)
1522
1523 if sig is not None:
1524 # For classes and objects we skip the first parameter of their
1525 # __call__, __new__, or __init__ methods
1526 return sig.replace(parameters=tuple(sig.parameters.values())[1:])
1527
1528 if isinstance(obj, types.BuiltinFunctionType):
1529 # Raise a nicer error message for builtins
1530 msg = 'no signature found for builtin function {!r}'.format(obj)
1531 raise ValueError(msg)
1532
1533 raise ValueError('callable {!r} is not supported by signature'.format(obj))
1534
1535
1536class _void:
1537 '''A private marker - used in Parameter & Signature'''
1538
1539
1540class _empty:
1541 pass
1542
1543
1544class _ParameterKind(int):
1545 def __new__(self, *args, name):
1546 obj = int.__new__(self, *args)
1547 obj._name = name
1548 return obj
1549
1550 def __str__(self):
1551 return self._name
1552
1553 def __repr__(self):
1554 return '<_ParameterKind: {!r}>'.format(self._name)
1555
1556
1557_POSITIONAL_ONLY = _ParameterKind(0, name='POSITIONAL_ONLY')
1558_POSITIONAL_OR_KEYWORD = _ParameterKind(1, name='POSITIONAL_OR_KEYWORD')
1559_VAR_POSITIONAL = _ParameterKind(2, name='VAR_POSITIONAL')
1560_KEYWORD_ONLY = _ParameterKind(3, name='KEYWORD_ONLY')
1561_VAR_KEYWORD = _ParameterKind(4, name='VAR_KEYWORD')
1562
1563
1564class Parameter:
1565 '''Represents a parameter in a function signature.
1566
1567 Has the following public attributes:
1568
1569 * name : str
1570 The name of the parameter as a string.
1571 * default : object
1572 The default value for the parameter if specified. If the
1573 parameter has no default value, this attribute is not set.
1574 * annotation
1575 The annotation for the parameter if specified. If the
1576 parameter has no annotation, this attribute is not set.
1577 * kind : str
1578 Describes how argument values are bound to the parameter.
1579 Possible values: `Parameter.POSITIONAL_ONLY`,
1580 `Parameter.POSITIONAL_OR_KEYWORD`, `Parameter.VAR_POSITIONAL`,
1581 `Parameter.KEYWORD_ONLY`, `Parameter.VAR_KEYWORD`.
1582 '''
1583
1584 __slots__ = ('_name', '_kind', '_default', '_annotation', '_partial_kwarg')
1585
1586 POSITIONAL_ONLY = _POSITIONAL_ONLY
1587 POSITIONAL_OR_KEYWORD = _POSITIONAL_OR_KEYWORD
1588 VAR_POSITIONAL = _VAR_POSITIONAL
1589 KEYWORD_ONLY = _KEYWORD_ONLY
1590 VAR_KEYWORD = _VAR_KEYWORD
1591
1592 empty = _empty
1593
1594 def __init__(self, name, kind, *, default=_empty, annotation=_empty,
1595 _partial_kwarg=False):
1596
1597 if kind not in (_POSITIONAL_ONLY, _POSITIONAL_OR_KEYWORD,
1598 _VAR_POSITIONAL, _KEYWORD_ONLY, _VAR_KEYWORD):
1599 raise ValueError("invalid value for 'Parameter.kind' attribute")
1600 self._kind = kind
1601
1602 if default is not _empty:
1603 if kind in (_VAR_POSITIONAL, _VAR_KEYWORD):
1604 msg = '{} parameters cannot have default values'.format(kind)
1605 raise ValueError(msg)
1606 self._default = default
1607 self._annotation = annotation
1608
1609 if name is None:
1610 if kind != _POSITIONAL_ONLY:
1611 raise ValueError("None is not a valid name for a "
1612 "non-positional-only parameter")
1613 self._name = name
1614 else:
1615 name = str(name)
1616 if kind != _POSITIONAL_ONLY and not name.isidentifier():
1617 msg = '{!r} is not a valid parameter name'.format(name)
1618 raise ValueError(msg)
1619 self._name = name
1620
1621 self._partial_kwarg = _partial_kwarg
1622
1623 @property
1624 def name(self):
1625 return self._name
1626
1627 @property
1628 def default(self):
1629 return self._default
1630
1631 @property
1632 def annotation(self):
1633 return self._annotation
1634
1635 @property
1636 def kind(self):
1637 return self._kind
1638
1639 def replace(self, *, name=_void, kind=_void, annotation=_void,
1640 default=_void, _partial_kwarg=_void):
1641 '''Creates a customized copy of the Parameter.'''
1642
1643 if name is _void:
1644 name = self._name
1645
1646 if kind is _void:
1647 kind = self._kind
1648
1649 if annotation is _void:
1650 annotation = self._annotation
1651
1652 if default is _void:
1653 default = self._default
1654
1655 if _partial_kwarg is _void:
1656 _partial_kwarg = self._partial_kwarg
1657
1658 return type(self)(name, kind, default=default, annotation=annotation,
1659 _partial_kwarg=_partial_kwarg)
1660
1661 def __str__(self):
1662 kind = self.kind
1663
1664 formatted = self._name
1665 if kind == _POSITIONAL_ONLY:
1666 if formatted is None:
1667 formatted = ''
1668 formatted = '<{}>'.format(formatted)
1669
1670 # Add annotation and default value
1671 if self._annotation is not _empty:
1672 formatted = '{}:{}'.format(formatted,
1673 formatannotation(self._annotation))
1674
1675 if self._default is not _empty:
1676 formatted = '{}={}'.format(formatted, repr(self._default))
1677
1678 if kind == _VAR_POSITIONAL:
1679 formatted = '*' + formatted
1680 elif kind == _VAR_KEYWORD:
1681 formatted = '**' + formatted
1682
1683 return formatted
1684
1685 def __repr__(self):
1686 return '<{} at {:#x} {!r}>'.format(self.__class__.__name__,
1687 id(self), self.name)
1688
1689 def __eq__(self, other):
1690 return (issubclass(other.__class__, Parameter) and
1691 self._name == other._name and
1692 self._kind == other._kind and
1693 self._default == other._default and
1694 self._annotation == other._annotation)
1695
1696 def __ne__(self, other):
1697 return not self.__eq__(other)
1698
1699
1700class BoundArguments:
1701 '''Result of `Signature.bind` call. Holds the mapping of arguments
1702 to the function's parameters.
1703
1704 Has the following public attributes:
1705
1706 * arguments : OrderedDict
1707 An ordered mutable mapping of parameters' names to arguments' values.
1708 Does not contain arguments' default values.
1709 * signature : Signature
1710 The Signature object that created this instance.
1711 * args : tuple
1712 Tuple of positional arguments values.
1713 * kwargs : dict
1714 Dict of keyword arguments values.
1715 '''
1716
1717 def __init__(self, signature, arguments):
1718 self.arguments = arguments
1719 self._signature = signature
1720
1721 @property
1722 def signature(self):
1723 return self._signature
1724
1725 @property
1726 def args(self):
1727 args = []
1728 for param_name, param in self._signature.parameters.items():
1729 if (param.kind in (_VAR_KEYWORD, _KEYWORD_ONLY) or
1730 param._partial_kwarg):
1731 # Keyword arguments mapped by 'functools.partial'
1732 # (Parameter._partial_kwarg is True) are mapped
1733 # in 'BoundArguments.kwargs', along with VAR_KEYWORD &
1734 # KEYWORD_ONLY
1735 break
1736
1737 try:
1738 arg = self.arguments[param_name]
1739 except KeyError:
1740 # We're done here. Other arguments
1741 # will be mapped in 'BoundArguments.kwargs'
1742 break
1743 else:
1744 if param.kind == _VAR_POSITIONAL:
1745 # *args
1746 args.extend(arg)
1747 else:
1748 # plain argument
1749 args.append(arg)
1750
1751 return tuple(args)
1752
1753 @property
1754 def kwargs(self):
1755 kwargs = {}
1756 kwargs_started = False
1757 for param_name, param in self._signature.parameters.items():
1758 if not kwargs_started:
1759 if (param.kind in (_VAR_KEYWORD, _KEYWORD_ONLY) or
1760 param._partial_kwarg):
1761 kwargs_started = True
1762 else:
1763 if param_name not in self.arguments:
1764 kwargs_started = True
1765 continue
1766
1767 if not kwargs_started:
1768 continue
1769
1770 try:
1771 arg = self.arguments[param_name]
1772 except KeyError:
1773 pass
1774 else:
1775 if param.kind == _VAR_KEYWORD:
1776 # **kwargs
1777 kwargs.update(arg)
1778 else:
1779 # plain keyword argument
1780 kwargs[param_name] = arg
1781
1782 return kwargs
1783
1784 def __eq__(self, other):
1785 return (issubclass(other.__class__, BoundArguments) and
1786 self.signature == other.signature and
1787 self.arguments == other.arguments)
1788
1789 def __ne__(self, other):
1790 return not self.__eq__(other)
1791
1792
1793class Signature:
1794 '''A Signature object represents the overall signature of a function.
1795 It stores a Parameter object for each parameter accepted by the
1796 function, as well as information specific to the function itself.
1797
1798 A Signature object has the following public attributes and methods:
1799
1800 * parameters : OrderedDict
1801 An ordered mapping of parameters' names to the corresponding
1802 Parameter objects (keyword-only arguments are in the same order
1803 as listed in `code.co_varnames`).
1804 * return_annotation : object
1805 The annotation for the return type of the function if specified.
1806 If the function has no annotation for its return type, this
1807 attribute is not set.
1808 * bind(*args, **kwargs) -> BoundArguments
1809 Creates a mapping from positional and keyword arguments to
1810 parameters.
1811 * bind_partial(*args, **kwargs) -> BoundArguments
1812 Creates a partial mapping from positional and keyword arguments
1813 to parameters (simulating 'functools.partial' behavior.)
1814 '''
1815
1816 __slots__ = ('_return_annotation', '_parameters')
1817
1818 _parameter_cls = Parameter
1819 _bound_arguments_cls = BoundArguments
1820
1821 empty = _empty
1822
1823 def __init__(self, parameters=None, *, return_annotation=_empty,
1824 __validate_parameters__=True):
1825 '''Constructs Signature from the given list of Parameter
1826 objects and 'return_annotation'. All arguments are optional.
1827 '''
1828
1829 if parameters is None:
1830 params = OrderedDict()
1831 else:
1832 if __validate_parameters__:
1833 params = OrderedDict()
1834 top_kind = _POSITIONAL_ONLY
1835
1836 for idx, param in enumerate(parameters):
1837 kind = param.kind
1838 if kind < top_kind:
1839 msg = 'wrong parameter order: {} before {}'
1840 msg = msg.format(top_kind, param.kind)
1841 raise ValueError(msg)
1842 else:
1843 top_kind = kind
1844
1845 name = param.name
1846 if name is None:
1847 name = str(idx)
1848 param = param.replace(name=name)
1849
1850 if name in params:
1851 msg = 'duplicate parameter name: {!r}'.format(name)
1852 raise ValueError(msg)
1853 params[name] = param
1854 else:
1855 params = OrderedDict(((param.name, param)
1856 for param in parameters))
1857
1858 self._parameters = types.MappingProxyType(params)
1859 self._return_annotation = return_annotation
1860
1861 @classmethod
1862 def from_function(cls, func):
1863 '''Constructs Signature for the given python function'''
1864
1865 if not isinstance(func, types.FunctionType):
1866 raise TypeError('{!r} is not a Python function'.format(func))
1867
1868 Parameter = cls._parameter_cls
1869
1870 # Parameter information.
1871 func_code = func.__code__
1872 pos_count = func_code.co_argcount
1873 arg_names = func_code.co_varnames
1874 positional = tuple(arg_names[:pos_count])
1875 keyword_only_count = func_code.co_kwonlyargcount
1876 keyword_only = arg_names[pos_count:(pos_count + keyword_only_count)]
1877 annotations = func.__annotations__
1878 defaults = func.__defaults__
1879 kwdefaults = func.__kwdefaults__
1880
1881 if defaults:
1882 pos_default_count = len(defaults)
1883 else:
1884 pos_default_count = 0
1885
1886 parameters = []
1887
1888 # Non-keyword-only parameters w/o defaults.
1889 non_default_count = pos_count - pos_default_count
1890 for name in positional[:non_default_count]:
1891 annotation = annotations.get(name, _empty)
1892 parameters.append(Parameter(name, annotation=annotation,
1893 kind=_POSITIONAL_OR_KEYWORD))
1894
1895 # ... w/ defaults.
1896 for offset, name in enumerate(positional[non_default_count:]):
1897 annotation = annotations.get(name, _empty)
1898 parameters.append(Parameter(name, annotation=annotation,
1899 kind=_POSITIONAL_OR_KEYWORD,
1900 default=defaults[offset]))
1901
1902 # *args
1903 if func_code.co_flags & 0x04:
1904 name = arg_names[pos_count + keyword_only_count]
1905 annotation = annotations.get(name, _empty)
1906 parameters.append(Parameter(name, annotation=annotation,
1907 kind=_VAR_POSITIONAL))
1908
1909 # Keyword-only parameters.
1910 for name in keyword_only:
1911 default = _empty
1912 if kwdefaults is not None:
1913 default = kwdefaults.get(name, _empty)
1914
1915 annotation = annotations.get(name, _empty)
1916 parameters.append(Parameter(name, annotation=annotation,
1917 kind=_KEYWORD_ONLY,
1918 default=default))
1919 # **kwargs
1920 if func_code.co_flags & 0x08:
1921 index = pos_count + keyword_only_count
1922 if func_code.co_flags & 0x04:
1923 index += 1
1924
1925 name = arg_names[index]
1926 annotation = annotations.get(name, _empty)
1927 parameters.append(Parameter(name, annotation=annotation,
1928 kind=_VAR_KEYWORD))
1929
1930 return cls(parameters,
1931 return_annotation=annotations.get('return', _empty),
1932 __validate_parameters__=False)
1933
1934 @property
1935 def parameters(self):
1936 return self._parameters
1937
1938 @property
1939 def return_annotation(self):
1940 return self._return_annotation
1941
1942 def replace(self, *, parameters=_void, return_annotation=_void):
1943 '''Creates a customized copy of the Signature.
1944 Pass 'parameters' and/or 'return_annotation' arguments
1945 to override them in the new copy.
1946 '''
1947
1948 if parameters is _void:
1949 parameters = self.parameters.values()
1950
1951 if return_annotation is _void:
1952 return_annotation = self._return_annotation
1953
1954 return type(self)(parameters,
1955 return_annotation=return_annotation)
1956
1957 def __eq__(self, other):
1958 if (not issubclass(type(other), Signature) or
1959 self.return_annotation != other.return_annotation or
1960 len(self.parameters) != len(other.parameters)):
1961 return False
1962
1963 other_positions = {param: idx
1964 for idx, param in enumerate(other.parameters.keys())}
1965
1966 for idx, (param_name, param) in enumerate(self.parameters.items()):
1967 if param.kind == _KEYWORD_ONLY:
1968 try:
1969 other_param = other.parameters[param_name]
1970 except KeyError:
1971 return False
1972 else:
1973 if param != other_param:
1974 return False
1975 else:
1976 try:
1977 other_idx = other_positions[param_name]
1978 except KeyError:
1979 return False
1980 else:
1981 if (idx != other_idx or
1982 param != other.parameters[param_name]):
1983 return False
1984
1985 return True
1986
1987 def __ne__(self, other):
1988 return not self.__eq__(other)
1989
1990 def _bind(self, args, kwargs, *, partial=False):
1991 '''Private method. Don't use directly.'''
1992
1993 arguments = OrderedDict()
1994
1995 parameters = iter(self.parameters.values())
1996 parameters_ex = ()
1997 arg_vals = iter(args)
1998
1999 if partial:
2000 # Support for binding arguments to 'functools.partial' objects.
2001 # See 'functools.partial' case in 'signature()' implementation
2002 # for details.
2003 for param_name, param in self.parameters.items():
2004 if (param._partial_kwarg and param_name not in kwargs):
2005 # Simulating 'functools.partial' behavior
2006 kwargs[param_name] = param.default
2007
2008 while True:
2009 # Let's iterate through the positional arguments and corresponding
2010 # parameters
2011 try:
2012 arg_val = next(arg_vals)
2013 except StopIteration:
2014 # No more positional arguments
2015 try:
2016 param = next(parameters)
2017 except StopIteration:
2018 # No more parameters. That's it. Just need to check that
2019 # we have no `kwargs` after this while loop
2020 break
2021 else:
2022 if param.kind == _VAR_POSITIONAL:
2023 # That's OK, just empty *args. Let's start parsing
2024 # kwargs
2025 break
2026 elif param.name in kwargs:
2027 if param.kind == _POSITIONAL_ONLY:
2028 msg = '{arg!r} parameter is positional only, ' \
2029 'but was passed as a keyword'
2030 msg = msg.format(arg=param.name)
2031 raise TypeError(msg) from None
2032 parameters_ex = (param,)
2033 break
2034 elif (param.kind == _VAR_KEYWORD or
2035 param.default is not _empty):
2036 # That's fine too - we have a default value for this
2037 # parameter. So, lets start parsing `kwargs`, starting
2038 # with the current parameter
2039 parameters_ex = (param,)
2040 break
2041 else:
2042 if partial:
2043 parameters_ex = (param,)
2044 break
2045 else:
2046 msg = '{arg!r} parameter lacking default value'
2047 msg = msg.format(arg=param.name)
2048 raise TypeError(msg) from None
2049 else:
2050 # We have a positional argument to process
2051 try:
2052 param = next(parameters)
2053 except StopIteration:
2054 raise TypeError('too many positional arguments') from None
2055 else:
2056 if param.kind in (_VAR_KEYWORD, _KEYWORD_ONLY):
2057 # Looks like we have no parameter for this positional
2058 # argument
2059 raise TypeError('too many positional arguments')
2060
2061 if param.kind == _VAR_POSITIONAL:
2062 # We have an '*args'-like argument, let's fill it with
2063 # all positional arguments we have left and move on to
2064 # the next phase
2065 values = [arg_val]
2066 values.extend(arg_vals)
2067 arguments[param.name] = tuple(values)
2068 break
2069
2070 if param.name in kwargs:
2071 raise TypeError('multiple values for argument '
2072 '{arg!r}'.format(arg=param.name))
2073
2074 arguments[param.name] = arg_val
2075
2076 # Now, we iterate through the remaining parameters to process
2077 # keyword arguments
2078 kwargs_param = None
2079 for param in itertools.chain(parameters_ex, parameters):
2080 if param.kind == _POSITIONAL_ONLY:
2081 # This should never happen in case of a properly built
2082 # Signature object (but let's have this check here
2083 # to ensure correct behaviour just in case)
2084 raise TypeError('{arg!r} parameter is positional only, '
2085 'but was passed as a keyword'. \
2086 format(arg=param.name))
2087
2088 if param.kind == _VAR_KEYWORD:
2089 # Memorize that we have a '**kwargs'-like parameter
2090 kwargs_param = param
2091 continue
2092
2093 param_name = param.name
2094 try:
2095 arg_val = kwargs.pop(param_name)
2096 except KeyError:
2097 # We have no value for this parameter. It's fine though,
2098 # if it has a default value, or it is an '*args'-like
2099 # parameter, left alone by the processing of positional
2100 # arguments.
2101 if (not partial and param.kind != _VAR_POSITIONAL and
2102 param.default is _empty):
2103 raise TypeError('{arg!r} parameter lacking default value'. \
2104 format(arg=param_name)) from None
2105
2106 else:
2107 arguments[param_name] = arg_val
2108
2109 if kwargs:
2110 if kwargs_param is not None:
2111 # Process our '**kwargs'-like parameter
2112 arguments[kwargs_param.name] = kwargs
2113 else:
2114 raise TypeError('too many keyword arguments')
2115
2116 return self._bound_arguments_cls(self, arguments)
2117
Antoine Pitroubd41d1b2013-01-29 21:20:57 +01002118 def bind(__bind_self, *args, **kwargs):
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002119 '''Get a BoundArguments object, that maps the passed `args`
2120 and `kwargs` to the function's signature. Raises `TypeError`
2121 if the passed arguments can not be bound.
2122 '''
Antoine Pitroubd41d1b2013-01-29 21:20:57 +01002123 return __bind_self._bind(args, kwargs)
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002124
Antoine Pitroubd41d1b2013-01-29 21:20:57 +01002125 def bind_partial(__bind_self, *args, **kwargs):
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002126 '''Get a BoundArguments object, that partially maps the
2127 passed `args` and `kwargs` to the function's signature.
2128 Raises `TypeError` if the passed arguments can not be bound.
2129 '''
Antoine Pitroubd41d1b2013-01-29 21:20:57 +01002130 return __bind_self._bind(args, kwargs, partial=True)
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002131
2132 def __str__(self):
2133 result = []
2134 render_kw_only_separator = True
2135 for idx, param in enumerate(self.parameters.values()):
2136 formatted = str(param)
2137
2138 kind = param.kind
2139 if kind == _VAR_POSITIONAL:
2140 # OK, we have an '*args'-like parameter, so we won't need
2141 # a '*' to separate keyword-only arguments
2142 render_kw_only_separator = False
2143 elif kind == _KEYWORD_ONLY and render_kw_only_separator:
2144 # We have a keyword-only parameter to render and we haven't
2145 # rendered an '*args'-like parameter before, so add a '*'
2146 # separator to the parameters list ("foo(arg1, *, arg2)" case)
2147 result.append('*')
2148 # This condition should be only triggered once, so
2149 # reset the flag
2150 render_kw_only_separator = False
2151
2152 result.append(formatted)
2153
2154 rendered = '({})'.format(', '.join(result))
2155
2156 if self.return_annotation is not _empty:
2157 anno = formatannotation(self.return_annotation)
2158 rendered += ' -> {}'.format(anno)
2159
2160 return rendered
Nick Coghlanf94a16b2013-09-22 22:46:49 +10002161
2162def _main():
2163 """ Logic for inspecting an object given at command line """
2164 import argparse
2165 import importlib
2166
2167 parser = argparse.ArgumentParser()
2168 parser.add_argument(
2169 'object',
2170 help="The object to be analysed. "
2171 "It supports the 'module:qualname' syntax")
2172 parser.add_argument(
2173 '-d', '--details', action='store_true',
2174 help='Display info about the module rather than its source code')
2175
2176 args = parser.parse_args()
2177
2178 target = args.object
2179 mod_name, has_attrs, attrs = target.partition(":")
2180 try:
2181 obj = module = importlib.import_module(mod_name)
2182 except Exception as exc:
2183 msg = "Failed to import {} ({}: {})".format(mod_name,
2184 type(exc).__name__,
2185 exc)
2186 print(msg, file=sys.stderr)
2187 exit(2)
2188
2189 if has_attrs:
2190 parts = attrs.split(".")
2191 obj = module
2192 for part in parts:
2193 obj = getattr(obj, part)
2194
2195 if module.__name__ in sys.builtin_module_names:
2196 print("Can't get info for builtin modules.", file=sys.stderr)
2197 exit(1)
2198
2199 if args.details:
2200 print('Target: {}'.format(target))
2201 print('Origin: {}'.format(getsourcefile(module)))
2202 print('Cached: {}'.format(module.__cached__))
2203 if obj is module:
2204 print('Loader: {}'.format(repr(module.__loader__)))
2205 if hasattr(module, '__path__'):
2206 print('Submodule search path: {}'.format(module.__path__))
2207 else:
2208 try:
2209 __, lineno = findsource(obj)
2210 except Exception:
2211 pass
2212 else:
2213 print('Line: {}'.format(lineno))
2214
2215 print('\n')
2216 else:
2217 print(getsource(obj))
2218
2219
2220if __name__ == "__main__":
2221 _main()