blob: d03edd9566555ae1acf5ceed5b177f99fdbd62d5 [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:
Antoine Pitrou86a8a9a2011-12-21 09:57:40 +0100283 # First try to get the value via __dict__. Some descriptors don't
284 # like calling their __get__ (see bug #1785).
285 for base in mro:
Ethan Furmane03ea372013-09-25 07:14:41 -0700286 if key in base.__dict__ and key not in processed:
287 # handle the normal case first; if duplicate entries exist
288 # they will be handled second
Antoine Pitrou86a8a9a2011-12-21 09:57:40 +0100289 value = base.__dict__[key]
290 break
291 else:
292 try:
293 value = getattr(object, key)
294 except AttributeError:
295 continue
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000296 if not predicate or predicate(value):
297 results.append((key, value))
Ethan Furmane03ea372013-09-25 07:14:41 -0700298 processed.add(key)
299 results.sort(key=lambda pair: pair[0])
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000300 return results
301
Christian Heimes25bb7832008-01-11 16:17:00 +0000302Attribute = namedtuple('Attribute', 'name kind defining_class object')
303
Tim Peters13b49d32001-09-23 02:00:29 +0000304def classify_class_attrs(cls):
305 """Return list of attribute-descriptor tuples.
306
307 For each name in dir(cls), the return list contains a 4-tuple
308 with these elements:
309
310 0. The name (a string).
311
312 1. The kind of attribute this is, one of these strings:
313 'class method' created via classmethod()
314 'static method' created via staticmethod()
315 'property' created via property()
Ethan Furmane03ea372013-09-25 07:14:41 -0700316 'method' any other flavor of method or descriptor
Tim Peters13b49d32001-09-23 02:00:29 +0000317 'data' not a method
318
319 2. The class which defined this attribute (a class).
320
Ethan Furmane03ea372013-09-25 07:14:41 -0700321 3. The object as obtained by calling getattr; if this fails, or if the
322 resulting object does not live anywhere in the class' mro (including
323 metaclasses) then the object is looked up in the defining class's
324 dict (found by walking the mro).
Ethan Furman668dede2013-09-14 18:53:26 -0700325
326 If one of the items in dir(cls) is stored in the metaclass it will now
327 be discovered and not have None be listed as the class in which it was
328 defined.
Tim Peters13b49d32001-09-23 02:00:29 +0000329 """
330
331 mro = getmro(cls)
Ethan Furman668dede2013-09-14 18:53:26 -0700332 metamro = getmro(type(cls)) # for attributes stored in the metaclass
Ethan Furmane03ea372013-09-25 07:14:41 -0700333 metamro = tuple([cls for cls in metamro if cls not in (type, object)])
334 possible_bases = (cls,) + mro + metamro
Tim Peters13b49d32001-09-23 02:00:29 +0000335 names = dir(cls)
Ethan Furmane03ea372013-09-25 07:14:41 -0700336 # add any virtual attributes to the list of names
337 # this may result in duplicate entries if, for example, a virtual
338 # attribute with the same name as a member property exists
339 for base in cls.__bases__:
340 for k, v in base.__dict__.items():
341 if isinstance(v, types.DynamicClassAttribute):
342 names.append(k)
Tim Peters13b49d32001-09-23 02:00:29 +0000343 result = []
Ethan Furmane03ea372013-09-25 07:14:41 -0700344 processed = set()
345 sentinel = object()
Tim Peters13b49d32001-09-23 02:00:29 +0000346 for name in names:
Antoine Pitrou86a8a9a2011-12-21 09:57:40 +0100347 # Get the object associated with the name, and where it was defined.
Ethan Furmane03ea372013-09-25 07:14:41 -0700348 # Normal objects will be looked up with both getattr and directly in
349 # its class' dict (in case getattr fails [bug #1785], and also to look
350 # for a docstring).
351 # For VirtualAttributes on the second pass we only look in the
352 # class's dict.
353 #
Tim Peters13b49d32001-09-23 02:00:29 +0000354 # Getting an obj from the __dict__ sometimes reveals more than
355 # using getattr. Static and class methods are dramatic examples.
Antoine Pitrou86a8a9a2011-12-21 09:57:40 +0100356 homecls = None
Ethan Furmane03ea372013-09-25 07:14:41 -0700357 get_obj = sentinel
358 dict_obj = sentinel
Tim Peters13b49d32001-09-23 02:00:29 +0000359
Ethan Furmane03ea372013-09-25 07:14:41 -0700360
361 if name not in processed:
362 try:
363 get_obj = getattr(cls, name)
364 except Exception as exc:
365 pass
366 else:
367 homecls = getattr(get_obj, "__class__")
368 homecls = getattr(get_obj, "__objclass__", homecls)
369 if homecls not in possible_bases:
370 # if the resulting object does not live somewhere in the
371 # mro, drop it and go with the dict_obj version only
372 homecls = None
373 get_obj = sentinel
374
375 for base in possible_bases:
376 if name in base.__dict__:
377 dict_obj = base.__dict__[name]
378 homecls = homecls or base
379 break
380
381 # Classify the object or its descriptor.
382 if get_obj is not sentinel:
383 obj = get_obj
384 else:
385 obj = dict_obj
Tim Peters13b49d32001-09-23 02:00:29 +0000386 if isinstance(obj, staticmethod):
387 kind = "static method"
388 elif isinstance(obj, classmethod):
389 kind = "class method"
390 elif isinstance(obj, property):
391 kind = "property"
Ethan Furmane03ea372013-09-25 07:14:41 -0700392 elif isfunction(obj) or ismethoddescriptor(obj):
Tim Peters13b49d32001-09-23 02:00:29 +0000393 kind = "method"
Antoine Pitrou86a8a9a2011-12-21 09:57:40 +0100394 else:
Ethan Furmane03ea372013-09-25 07:14:41 -0700395 kind = "data"
Tim Peters13b49d32001-09-23 02:00:29 +0000396
Christian Heimes25bb7832008-01-11 16:17:00 +0000397 result.append(Attribute(name, kind, homecls, obj))
Ethan Furmane03ea372013-09-25 07:14:41 -0700398 processed.add(name)
Tim Peters13b49d32001-09-23 02:00:29 +0000399
400 return result
401
Tim Peterse0b2d7a2001-09-22 06:10:55 +0000402# ----------------------------------------------------------- class helpers
Tim Peterse0b2d7a2001-09-22 06:10:55 +0000403
404def getmro(cls):
405 "Return tuple of base classes (including cls) in method resolution order."
Benjamin Petersonb82c8e52010-11-04 00:38:49 +0000406 return cls.__mro__
Tim Peterse0b2d7a2001-09-22 06:10:55 +0000407
Nick Coghlane8c45d62013-07-28 20:00:01 +1000408# -------------------------------------------------------- function helpers
409
410def unwrap(func, *, stop=None):
411 """Get the object wrapped by *func*.
412
413 Follows the chain of :attr:`__wrapped__` attributes returning the last
414 object in the chain.
415
416 *stop* is an optional callback accepting an object in the wrapper chain
417 as its sole argument that allows the unwrapping to be terminated early if
418 the callback returns a true value. If the callback never returns a true
419 value, the last object in the chain is returned as usual. For example,
420 :func:`signature` uses this to stop unwrapping if any object in the
421 chain has a ``__signature__`` attribute defined.
422
423 :exc:`ValueError` is raised if a cycle is encountered.
424
425 """
426 if stop is None:
427 def _is_wrapper(f):
428 return hasattr(f, '__wrapped__')
429 else:
430 def _is_wrapper(f):
431 return hasattr(f, '__wrapped__') and not stop(f)
432 f = func # remember the original func for error reporting
433 memo = {id(f)} # Memoise by id to tolerate non-hashable objects
434 while _is_wrapper(func):
435 func = func.__wrapped__
436 id_func = id(func)
437 if id_func in memo:
438 raise ValueError('wrapper loop when unwrapping {!r}'.format(f))
439 memo.add(id_func)
440 return func
441
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000442# -------------------------------------------------- source code extraction
443def indentsize(line):
444 """Return the indent size, in spaces, at the start of a line of text."""
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000445 expline = line.expandtabs()
446 return len(expline) - len(expline.lstrip())
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000447
448def getdoc(object):
449 """Get the documentation string for an object.
450
451 All tabs are expanded to spaces. To clean up docstrings that are
452 indented to line up with blocks of code, any whitespace than can be
453 uniformly removed from the second line onwards is removed."""
Tim Peters24008312002-03-17 18:56:20 +0000454 try:
455 doc = object.__doc__
456 except AttributeError:
457 return None
Guido van Rossum3172c5d2007-10-16 18:12:55 +0000458 if not isinstance(doc, str):
Tim Peters24008312002-03-17 18:56:20 +0000459 return None
Georg Brandl0c77a822008-06-10 16:37:50 +0000460 return cleandoc(doc)
461
462def cleandoc(doc):
463 """Clean up indentation from docstrings.
464
465 Any whitespace that can be uniformly removed from the second line
466 onwards is removed."""
Tim Peters24008312002-03-17 18:56:20 +0000467 try:
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000468 lines = doc.expandtabs().split('\n')
Tim Peters24008312002-03-17 18:56:20 +0000469 except UnicodeError:
470 return None
471 else:
Ka-Ping Yeea59ef7b2002-11-30 03:53:15 +0000472 # Find minimum indentation of any non-blank lines after first line.
Christian Heimesa37d4c62007-12-04 23:02:19 +0000473 margin = sys.maxsize
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000474 for line in lines[1:]:
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000475 content = len(line.lstrip())
Ka-Ping Yeea59ef7b2002-11-30 03:53:15 +0000476 if content:
477 indent = len(line) - content
478 margin = min(margin, indent)
479 # Remove indentation.
480 if lines:
481 lines[0] = lines[0].lstrip()
Christian Heimesa37d4c62007-12-04 23:02:19 +0000482 if margin < sys.maxsize:
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000483 for i in range(1, len(lines)): lines[i] = lines[i][margin:]
Ka-Ping Yeea59ef7b2002-11-30 03:53:15 +0000484 # Remove any trailing or leading blank lines.
485 while lines and not lines[-1]:
486 lines.pop()
487 while lines and not lines[0]:
488 lines.pop(0)
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000489 return '\n'.join(lines)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000490
491def getfile(object):
Ka-Ping Yeec113c242001-03-02 02:08:53 +0000492 """Work out which source or compiled file an object was defined in."""
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000493 if ismodule(object):
494 if hasattr(object, '__file__'):
495 return object.__file__
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +0000496 raise TypeError('{!r} is a built-in module'.format(object))
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000497 if isclass(object):
Ka-Ping Yeec99e0f12001-04-13 12:10:40 +0000498 object = sys.modules.get(object.__module__)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000499 if hasattr(object, '__file__'):
500 return object.__file__
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +0000501 raise TypeError('{!r} is a built-in class'.format(object))
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000502 if ismethod(object):
Christian Heimesff737952007-11-27 10:40:20 +0000503 object = object.__func__
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000504 if isfunction(object):
Neal Norwitz221085d2007-02-25 20:55:47 +0000505 object = object.__code__
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000506 if istraceback(object):
507 object = object.tb_frame
508 if isframe(object):
509 object = object.f_code
510 if iscode(object):
511 return object.co_filename
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +0000512 raise TypeError('{!r} is not a module, class, method, '
513 'function, traceback, frame, or code object'.format(object))
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000514
Christian Heimes25bb7832008-01-11 16:17:00 +0000515ModuleInfo = namedtuple('ModuleInfo', 'name suffix mode module_type')
516
Ka-Ping Yee4d6fc7f2001-04-10 11:43:00 +0000517def getmoduleinfo(path):
518 """Get the module name, suffix, mode, and module type for a given file."""
Brett Cannoncb66eb02012-05-11 12:58:42 -0400519 warnings.warn('inspect.getmoduleinfo() is deprecated', DeprecationWarning,
520 2)
Brett Cannone4f41de2013-06-16 13:13:40 -0400521 with warnings.catch_warnings():
522 warnings.simplefilter('ignore', PendingDeprecationWarning)
523 import imp
Ka-Ping Yee4d6fc7f2001-04-10 11:43:00 +0000524 filename = os.path.basename(path)
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000525 suffixes = [(-len(suffix), suffix, mode, mtype)
526 for suffix, mode, mtype in imp.get_suffixes()]
Ka-Ping Yee4d6fc7f2001-04-10 11:43:00 +0000527 suffixes.sort() # try longest suffixes first, in case they overlap
528 for neglen, suffix, mode, mtype in suffixes:
529 if filename[neglen:] == suffix:
Christian Heimes25bb7832008-01-11 16:17:00 +0000530 return ModuleInfo(filename[:neglen], suffix, mode, mtype)
Ka-Ping Yee4d6fc7f2001-04-10 11:43:00 +0000531
532def getmodulename(path):
533 """Return the module name for a given file, or None."""
Nick Coghlan76e07702012-07-18 23:14:57 +1000534 fname = os.path.basename(path)
535 # Check for paths that look like an actual module file
536 suffixes = [(-len(suffix), suffix)
537 for suffix in importlib.machinery.all_suffixes()]
538 suffixes.sort() # try longest suffixes first, in case they overlap
539 for neglen, suffix in suffixes:
540 if fname.endswith(suffix):
541 return fname[:neglen]
542 return None
Ka-Ping Yee4d6fc7f2001-04-10 11:43:00 +0000543
Ka-Ping Yeec113c242001-03-02 02:08:53 +0000544def getsourcefile(object):
R. David Murraya1b37402010-06-17 02:04:29 +0000545 """Return the filename that can be used to locate an object's source.
546 Return None if no way can be identified to get the source.
547 """
Ka-Ping Yeec113c242001-03-02 02:08:53 +0000548 filename = getfile(object)
Brett Cannoncb66eb02012-05-11 12:58:42 -0400549 all_bytecode_suffixes = importlib.machinery.DEBUG_BYTECODE_SUFFIXES[:]
550 all_bytecode_suffixes += importlib.machinery.OPTIMIZED_BYTECODE_SUFFIXES[:]
551 if any(filename.endswith(s) for s in all_bytecode_suffixes):
552 filename = (os.path.splitext(filename)[0] +
553 importlib.machinery.SOURCE_SUFFIXES[0])
554 elif any(filename.endswith(s) for s in
555 importlib.machinery.EXTENSION_SUFFIXES):
556 return None
Thomas Wouters477c8d52006-05-27 19:21:47 +0000557 if os.path.exists(filename):
558 return filename
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000559 # only return a non-existent filename if the module has a PEP 302 loader
Brett Cannon4c14b5d2013-05-04 13:56:58 -0400560 if getattr(getmodule(object, filename), '__loader__', None) is not None:
Ka-Ping Yeec113c242001-03-02 02:08:53 +0000561 return filename
R. David Murraya1b37402010-06-17 02:04:29 +0000562 # or it is in the linecache
563 if filename in linecache.cache:
564 return filename
Ka-Ping Yeec113c242001-03-02 02:08:53 +0000565
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000566def getabsfile(object, _filename=None):
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000567 """Return an absolute path to the source or compiled file for an object.
Ka-Ping Yeec113c242001-03-02 02:08:53 +0000568
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000569 The idea is for each object to have a unique origin, so this routine
570 normalizes the result as much as possible."""
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000571 if _filename is None:
572 _filename = getsourcefile(object) or getfile(object)
573 return os.path.normcase(os.path.abspath(_filename))
Ka-Ping Yeec113c242001-03-02 02:08:53 +0000574
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000575modulesbyfile = {}
Thomas Wouters89f507f2006-12-13 04:49:30 +0000576_filesbymodname = {}
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000577
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000578def getmodule(object, _filename=None):
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000579 """Return the module an object was defined in, or None if not found."""
Ka-Ping Yee202c99b2001-04-13 09:15:08 +0000580 if ismodule(object):
581 return object
Johannes Gijsbers93245262004-09-11 15:53:22 +0000582 if hasattr(object, '__module__'):
Ka-Ping Yee8b58b842001-03-01 13:56:16 +0000583 return sys.modules.get(object.__module__)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000584 # Try the filename to modulename cache
585 if _filename is not None and _filename in modulesbyfile:
586 return sys.modules.get(modulesbyfile[_filename])
587 # Try the cache again with the absolute file name
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000588 try:
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000589 file = getabsfile(object, _filename)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000590 except TypeError:
591 return None
Raymond Hettinger54f02222002-06-01 14:18:47 +0000592 if file in modulesbyfile:
Ka-Ping Yeeb38bbbd2003-03-28 16:29:50 +0000593 return sys.modules.get(modulesbyfile[file])
Thomas Wouters89f507f2006-12-13 04:49:30 +0000594 # Update the filename to module name cache and check yet again
595 # Copy sys.modules in order to cope with changes while iterating
Éric Araujoa74f8ef2011-11-29 16:58:53 +0100596 for modname, module in list(sys.modules.items()):
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000597 if ismodule(module) and hasattr(module, '__file__'):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000598 f = module.__file__
599 if f == _filesbymodname.get(modname, None):
600 # Have already mapped this module, so skip it
601 continue
602 _filesbymodname[modname] = f
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000603 f = getabsfile(module)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000604 # Always map to the name the module knows itself by
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000605 modulesbyfile[f] = modulesbyfile[
606 os.path.realpath(f)] = module.__name__
Raymond Hettinger54f02222002-06-01 14:18:47 +0000607 if file in modulesbyfile:
Ka-Ping Yeeb38bbbd2003-03-28 16:29:50 +0000608 return sys.modules.get(modulesbyfile[file])
Thomas Wouters89f507f2006-12-13 04:49:30 +0000609 # Check the main module
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000610 main = sys.modules['__main__']
Brett Cannon4a671fe2003-06-15 22:33:28 +0000611 if not hasattr(object, '__name__'):
612 return None
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000613 if hasattr(main, object.__name__):
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000614 mainobject = getattr(main, object.__name__)
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000615 if mainobject is object:
616 return main
Thomas Wouters89f507f2006-12-13 04:49:30 +0000617 # Check builtins
Georg Brandl1a3284e2007-12-02 09:40:06 +0000618 builtin = sys.modules['builtins']
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000619 if hasattr(builtin, object.__name__):
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000620 builtinobject = getattr(builtin, object.__name__)
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000621 if builtinobject is object:
622 return builtin
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000623
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000624def findsource(object):
625 """Return the entire source file and starting line number for an object.
626
627 The argument may be a module, class, method, function, traceback, frame,
628 or code object. The source code is returned as a list of all the lines
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200629 in the file and the line number indexes a line in that list. An OSError
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000630 is raised if the source code cannot be retrieved."""
Benjamin Peterson9620cc02011-06-11 15:53:11 -0500631
632 file = getfile(object)
633 sourcefile = getsourcefile(object)
Ezio Melotti1b145922013-03-30 05:17:24 +0200634 if not sourcefile and file[:1] + file[-1:] != '<>':
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200635 raise OSError('source code not available')
Benjamin Peterson9620cc02011-06-11 15:53:11 -0500636 file = sourcefile if sourcefile else file
637
Thomas Wouters89f507f2006-12-13 04:49:30 +0000638 module = getmodule(object, file)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000639 if module:
640 lines = linecache.getlines(file, module.__dict__)
641 else:
642 lines = linecache.getlines(file)
Neil Schemenauerf06f8532002-03-23 23:51:04 +0000643 if not lines:
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200644 raise OSError('could not get source code')
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000645
646 if ismodule(object):
647 return lines, 0
648
649 if isclass(object):
650 name = object.__name__
Thomas Wouters89f507f2006-12-13 04:49:30 +0000651 pat = re.compile(r'^(\s*)class\s*' + name + r'\b')
652 # make some effort to find the best matching class definition:
653 # use the one with the least indentation, which is the one
654 # that's most probably not inside a function definition.
655 candidates = []
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000656 for i in range(len(lines)):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000657 match = pat.match(lines[i])
658 if match:
659 # if it's at toplevel, it's already the best one
660 if lines[i][0] == 'c':
661 return lines, i
662 # else add whitespace to candidate list
663 candidates.append((match.group(1), i))
664 if candidates:
665 # this will sort by whitespace, and by line number,
666 # less whitespace first
667 candidates.sort()
668 return lines, candidates[0][1]
Jeremy Hyltonab919022003-06-27 18:41:20 +0000669 else:
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200670 raise OSError('could not find class definition')
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000671
672 if ismethod(object):
Christian Heimesff737952007-11-27 10:40:20 +0000673 object = object.__func__
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000674 if isfunction(object):
Neal Norwitz221085d2007-02-25 20:55:47 +0000675 object = object.__code__
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000676 if istraceback(object):
677 object = object.tb_frame
678 if isframe(object):
679 object = object.f_code
680 if iscode(object):
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000681 if not hasattr(object, 'co_firstlineno'):
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200682 raise OSError('could not find function definition')
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000683 lnum = object.co_firstlineno - 1
Johannes Gijsbers1542f342004-12-12 16:46:28 +0000684 pat = re.compile(r'^(\s*def\s)|(.*(?<!\w)lambda(:|\s))|^(\s*@)')
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000685 while lnum > 0:
Ka-Ping Yeea6e59712001-03-10 09:31:55 +0000686 if pat.match(lines[lnum]): break
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +0000687 lnum = lnum - 1
688 return lines, lnum
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200689 raise OSError('could not find code object')
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000690
691def getcomments(object):
Jeremy Hyltonb4c17c82002-03-28 23:01:56 +0000692 """Get lines of comments immediately preceding an object's source code.
693
694 Returns None when source can't be found.
695 """
696 try:
697 lines, lnum = findsource(object)
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200698 except (OSError, TypeError):
Jeremy Hyltonb4c17c82002-03-28 23:01:56 +0000699 return None
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000700
701 if ismodule(object):
702 # Look for a comment block at the top of the file.
703 start = 0
Ka-Ping Yeeb910efe2001-04-12 13:17:17 +0000704 if lines and lines[0][:2] == '#!': start = 1
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000705 while start < len(lines) and lines[start].strip() in ('', '#'):
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000706 start = start + 1
Ka-Ping Yeeb910efe2001-04-12 13:17:17 +0000707 if start < len(lines) and lines[start][:1] == '#':
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000708 comments = []
709 end = start
710 while end < len(lines) and lines[end][:1] == '#':
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000711 comments.append(lines[end].expandtabs())
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000712 end = end + 1
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000713 return ''.join(comments)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000714
715 # Look for a preceding block of comments at the same indentation.
716 elif lnum > 0:
717 indent = indentsize(lines[lnum])
718 end = lnum - 1
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000719 if end >= 0 and lines[end].lstrip()[:1] == '#' and \
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000720 indentsize(lines[end]) == indent:
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000721 comments = [lines[end].expandtabs().lstrip()]
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000722 if end > 0:
723 end = end - 1
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000724 comment = lines[end].expandtabs().lstrip()
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000725 while comment[:1] == '#' and indentsize(lines[end]) == indent:
726 comments[:0] = [comment]
727 end = end - 1
728 if end < 0: break
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000729 comment = lines[end].expandtabs().lstrip()
730 while comments and comments[0].strip() == '#':
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000731 comments[:1] = []
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000732 while comments and comments[-1].strip() == '#':
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000733 comments[-1:] = []
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000734 return ''.join(comments)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000735
Tim Peters4efb6e92001-06-29 23:51:08 +0000736class EndOfBlock(Exception): pass
737
738class BlockFinder:
739 """Provide a tokeneater() method to detect the end of a code block."""
740 def __init__(self):
741 self.indent = 0
Johannes Gijsbersa5855d52005-03-12 16:37:11 +0000742 self.islambda = False
Johannes Gijsbers1542f342004-12-12 16:46:28 +0000743 self.started = False
744 self.passline = False
Armin Rigodd5c0232005-09-25 11:45:45 +0000745 self.last = 1
Tim Peters4efb6e92001-06-29 23:51:08 +0000746
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000747 def tokeneater(self, type, token, srowcol, erowcol, line):
Tim Peters4efb6e92001-06-29 23:51:08 +0000748 if not self.started:
Armin Rigodd5c0232005-09-25 11:45:45 +0000749 # look for the first "def", "class" or "lambda"
Johannes Gijsbers1542f342004-12-12 16:46:28 +0000750 if token in ("def", "class", "lambda"):
Johannes Gijsbersa5855d52005-03-12 16:37:11 +0000751 if token == "lambda":
752 self.islambda = True
Johannes Gijsbers1542f342004-12-12 16:46:28 +0000753 self.started = True
Armin Rigodd5c0232005-09-25 11:45:45 +0000754 self.passline = True # skip to the end of the line
Tim Peters4efb6e92001-06-29 23:51:08 +0000755 elif type == tokenize.NEWLINE:
Armin Rigodd5c0232005-09-25 11:45:45 +0000756 self.passline = False # stop skipping when a NEWLINE is seen
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000757 self.last = srowcol[0]
Armin Rigodd5c0232005-09-25 11:45:45 +0000758 if self.islambda: # lambdas always end at the first NEWLINE
759 raise EndOfBlock
Johannes Gijsbers1542f342004-12-12 16:46:28 +0000760 elif self.passline:
761 pass
Tim Peters4efb6e92001-06-29 23:51:08 +0000762 elif type == tokenize.INDENT:
763 self.indent = self.indent + 1
Johannes Gijsbers1542f342004-12-12 16:46:28 +0000764 self.passline = True
Tim Peters4efb6e92001-06-29 23:51:08 +0000765 elif type == tokenize.DEDENT:
766 self.indent = self.indent - 1
Armin Rigodd5c0232005-09-25 11:45:45 +0000767 # the end of matching indent/dedent pairs end a block
768 # (note that this only works for "def"/"class" blocks,
769 # not e.g. for "if: else:" or "try: finally:" blocks)
770 if self.indent <= 0:
771 raise EndOfBlock
772 elif self.indent == 0 and type not in (tokenize.COMMENT, tokenize.NL):
773 # any other token on the same indentation level end the previous
774 # block as well, except the pseudo-tokens COMMENT and NL.
775 raise EndOfBlock
Tim Peters4efb6e92001-06-29 23:51:08 +0000776
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000777def getblock(lines):
778 """Extract the block of code at the top of the given list of lines."""
Armin Rigodd5c0232005-09-25 11:45:45 +0000779 blockfinder = BlockFinder()
Tim Peters4efb6e92001-06-29 23:51:08 +0000780 try:
Trent Nelson428de652008-03-18 22:41:35 +0000781 tokens = tokenize.generate_tokens(iter(lines).__next__)
782 for _token in tokens:
783 blockfinder.tokeneater(*_token)
Armin Rigodd5c0232005-09-25 11:45:45 +0000784 except (EndOfBlock, IndentationError):
785 pass
786 return lines[:blockfinder.last]
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000787
788def getsourcelines(object):
789 """Return a list of source lines and starting line number for an object.
790
791 The argument may be a module, class, method, function, traceback, frame,
792 or code object. The source code is returned as a list of the lines
793 corresponding to the object and the line number indicates where in the
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200794 original source file the first line of code was found. An OSError is
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000795 raised if the source code cannot be retrieved."""
796 lines, lnum = findsource(object)
797
798 if ismodule(object): return lines, 0
799 else: return getblock(lines[lnum:]), lnum + 1
800
801def getsource(object):
802 """Return the text of the source code for an object.
803
804 The argument may be a module, class, method, function, traceback, frame,
805 or code object. The source code is returned as a single string. An
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200806 OSError is raised if the source code cannot be retrieved."""
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000807 lines, lnum = getsourcelines(object)
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000808 return ''.join(lines)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000809
810# --------------------------------------------------- class tree extraction
811def walktree(classes, children, parent):
812 """Recursive helper function for getclasstree()."""
813 results = []
Raymond Hettingera1a992c2005-03-11 06:46:45 +0000814 classes.sort(key=attrgetter('__module__', '__name__'))
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000815 for c in classes:
816 results.append((c, c.__bases__))
Raymond Hettinger54f02222002-06-01 14:18:47 +0000817 if c in children:
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000818 results.append(walktree(children[c], children, c))
819 return results
820
Georg Brandl5ce83a02009-06-01 17:23:51 +0000821def getclasstree(classes, unique=False):
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000822 """Arrange the given list of classes into a hierarchy of nested lists.
823
824 Where a nested list appears, it contains classes derived from the class
825 whose entry immediately precedes the list. Each entry is a 2-tuple
826 containing a class and a tuple of its base classes. If the 'unique'
827 argument is true, exactly one entry appears in the returned structure
828 for each class in the given list. Otherwise, classes using multiple
829 inheritance and their descendants will appear multiple times."""
830 children = {}
831 roots = []
832 for c in classes:
833 if c.__bases__:
834 for parent in c.__bases__:
Raymond Hettinger54f02222002-06-01 14:18:47 +0000835 if not parent in children:
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000836 children[parent] = []
Serhiy Storchaka362c1b52013-09-05 17:14:32 +0300837 if c not in children[parent]:
838 children[parent].append(c)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000839 if unique and parent in classes: break
840 elif c not in roots:
841 roots.append(c)
Raymond Hettingere0d49722002-06-02 18:55:56 +0000842 for parent in children:
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000843 if parent not in classes:
844 roots.append(parent)
845 return walktree(roots, children, None)
846
847# ------------------------------------------------ argument list extraction
Christian Heimes25bb7832008-01-11 16:17:00 +0000848Arguments = namedtuple('Arguments', 'args, varargs, varkw')
849
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000850def getargs(co):
851 """Get information about the arguments accepted by a code object.
852
Guido van Rossum2e65f892007-02-28 22:03:49 +0000853 Three things are returned: (args, varargs, varkw), where
Georg Brandlc1c4bf82010-10-15 16:07:41 +0000854 'args' is the list of argument names. Keyword-only arguments are
855 appended. 'varargs' and 'varkw' are the names of the * and **
856 arguments or None."""
Guido van Rossum2e65f892007-02-28 22:03:49 +0000857 args, varargs, kwonlyargs, varkw = _getfullargs(co)
Christian Heimes25bb7832008-01-11 16:17:00 +0000858 return Arguments(args + kwonlyargs, varargs, varkw)
Guido van Rossum2e65f892007-02-28 22:03:49 +0000859
860def _getfullargs(co):
861 """Get information about the arguments accepted by a code object.
862
863 Four things are returned: (args, varargs, kwonlyargs, varkw), where
Georg Brandlc1c4bf82010-10-15 16:07:41 +0000864 'args' and 'kwonlyargs' are lists of argument names, and 'varargs'
865 and 'varkw' are the names of the * and ** arguments or None."""
Jeremy Hylton64967882003-06-27 18:14:39 +0000866
867 if not iscode(co):
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +0000868 raise TypeError('{!r} is not a code object'.format(co))
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000869
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000870 nargs = co.co_argcount
871 names = co.co_varnames
Guido van Rossum2e65f892007-02-28 22:03:49 +0000872 nkwargs = co.co_kwonlyargcount
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000873 args = list(names[:nargs])
Guido van Rossum2e65f892007-02-28 22:03:49 +0000874 kwonlyargs = list(names[nargs:nargs+nkwargs])
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000875 step = 0
876
Guido van Rossum2e65f892007-02-28 22:03:49 +0000877 nargs += nkwargs
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000878 varargs = None
879 if co.co_flags & CO_VARARGS:
880 varargs = co.co_varnames[nargs]
881 nargs = nargs + 1
882 varkw = None
883 if co.co_flags & CO_VARKEYWORDS:
884 varkw = co.co_varnames[nargs]
Guido van Rossum2e65f892007-02-28 22:03:49 +0000885 return args, varargs, kwonlyargs, varkw
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000886
Christian Heimes25bb7832008-01-11 16:17:00 +0000887
888ArgSpec = namedtuple('ArgSpec', 'args varargs keywords defaults')
889
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000890def getargspec(func):
891 """Get the names and default values of a function's arguments.
892
893 A tuple of four things is returned: (args, varargs, varkw, defaults).
Georg Brandlc1c4bf82010-10-15 16:07:41 +0000894 'args' is a list of the argument names.
Guido van Rossum2e65f892007-02-28 22:03:49 +0000895 'args' will include keyword-only argument names.
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000896 'varargs' and 'varkw' are the names of the * and ** arguments or None.
Jeremy Hylton64967882003-06-27 18:14:39 +0000897 'defaults' is an n-tuple of the default values of the last n arguments.
Guido van Rossuma8add0e2007-05-14 22:03:55 +0000898
Guido van Rossum2e65f892007-02-28 22:03:49 +0000899 Use the getfullargspec() API for Python-3000 code, as annotations
900 and keyword arguments are supported. getargspec() will raise ValueError
901 if the func has either annotations or keyword arguments.
902 """
903
904 args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults, ann = \
905 getfullargspec(func)
906 if kwonlyargs or ann:
Collin Winterce36ad82007-08-30 01:19:48 +0000907 raise ValueError("Function has keyword-only arguments or annotations"
908 ", use getfullargspec() API which can support them")
Christian Heimes25bb7832008-01-11 16:17:00 +0000909 return ArgSpec(args, varargs, varkw, defaults)
910
911FullArgSpec = namedtuple('FullArgSpec',
Benjamin Peterson3d4ca742008-11-12 21:39:01 +0000912 'args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults, annotations')
Guido van Rossum2e65f892007-02-28 22:03:49 +0000913
914def getfullargspec(func):
915 """Get the names and default values of a function's arguments.
916
Brett Cannon504d8852007-09-07 02:12:14 +0000917 A tuple of seven things is returned:
918 (args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults annotations).
Georg Brandlc1c4bf82010-10-15 16:07:41 +0000919 'args' is a list of the argument names.
Guido van Rossum2e65f892007-02-28 22:03:49 +0000920 'varargs' and 'varkw' are the names of the * and ** arguments or None.
921 'defaults' is an n-tuple of the default values of the last n arguments.
922 'kwonlyargs' is a list of keyword-only argument names.
923 'kwonlydefaults' is a dictionary mapping names from kwonlyargs to defaults.
924 'annotations' is a dictionary mapping argument names to annotations.
Guido van Rossuma8add0e2007-05-14 22:03:55 +0000925
Guido van Rossum2e65f892007-02-28 22:03:49 +0000926 The first four items in the tuple correspond to getargspec().
Jeremy Hylton64967882003-06-27 18:14:39 +0000927 """
928
929 if ismethod(func):
Christian Heimesff737952007-11-27 10:40:20 +0000930 func = func.__func__
Jeremy Hylton64967882003-06-27 18:14:39 +0000931 if not isfunction(func):
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +0000932 raise TypeError('{!r} is not a Python function'.format(func))
Guido van Rossum2e65f892007-02-28 22:03:49 +0000933 args, varargs, kwonlyargs, varkw = _getfullargs(func.__code__)
Christian Heimes25bb7832008-01-11 16:17:00 +0000934 return FullArgSpec(args, varargs, varkw, func.__defaults__,
Guido van Rossum2e65f892007-02-28 22:03:49 +0000935 kwonlyargs, func.__kwdefaults__, func.__annotations__)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000936
Christian Heimes25bb7832008-01-11 16:17:00 +0000937ArgInfo = namedtuple('ArgInfo', 'args varargs keywords locals')
938
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000939def getargvalues(frame):
940 """Get information about arguments passed into a particular frame.
941
942 A tuple of four things is returned: (args, varargs, varkw, locals).
Georg Brandlc1c4bf82010-10-15 16:07:41 +0000943 'args' is a list of the argument names.
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000944 'varargs' and 'varkw' are the names of the * and ** arguments or None.
945 'locals' is the locals dictionary of the given frame."""
946 args, varargs, varkw = getargs(frame.f_code)
Benjamin Peterson1a6e0d02008-10-25 15:49:17 +0000947 return ArgInfo(args, varargs, varkw, frame.f_locals)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000948
Guido van Rossum2e65f892007-02-28 22:03:49 +0000949def formatannotation(annotation, base_module=None):
950 if isinstance(annotation, type):
Georg Brandl1a3284e2007-12-02 09:40:06 +0000951 if annotation.__module__ in ('builtins', base_module):
Guido van Rossum2e65f892007-02-28 22:03:49 +0000952 return annotation.__name__
953 return annotation.__module__+'.'+annotation.__name__
954 return repr(annotation)
Guido van Rossuma8add0e2007-05-14 22:03:55 +0000955
Guido van Rossum2e65f892007-02-28 22:03:49 +0000956def formatannotationrelativeto(object):
Guido van Rossuma8add0e2007-05-14 22:03:55 +0000957 module = getattr(object, '__module__', None)
958 def _formatannotation(annotation):
959 return formatannotation(annotation, module)
960 return _formatannotation
Guido van Rossum2e65f892007-02-28 22:03:49 +0000961
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000962def formatargspec(args, varargs=None, varkw=None, defaults=None,
Guido van Rossum2e65f892007-02-28 22:03:49 +0000963 kwonlyargs=(), kwonlydefaults={}, annotations={},
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000964 formatarg=str,
965 formatvarargs=lambda name: '*' + name,
966 formatvarkw=lambda name: '**' + name,
967 formatvalue=lambda value: '=' + repr(value),
Guido van Rossum2e65f892007-02-28 22:03:49 +0000968 formatreturns=lambda text: ' -> ' + text,
Georg Brandlc1c4bf82010-10-15 16:07:41 +0000969 formatannotation=formatannotation):
Guido van Rossuma8add0e2007-05-14 22:03:55 +0000970 """Format an argument spec from the values returned by getargspec
Guido van Rossum2e65f892007-02-28 22:03:49 +0000971 or getfullargspec.
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000972
Guido van Rossum2e65f892007-02-28 22:03:49 +0000973 The first seven arguments are (args, varargs, varkw, defaults,
974 kwonlyargs, kwonlydefaults, annotations). The other five arguments
975 are the corresponding optional formatting functions that are called to
976 turn names and values into strings. The last argument is an optional
977 function to format the sequence of arguments."""
978 def formatargandannotation(arg):
979 result = formatarg(arg)
980 if arg in annotations:
981 result += ': ' + formatannotation(annotations[arg])
982 return result
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000983 specs = []
984 if defaults:
985 firstdefault = len(args) - len(defaults)
Benjamin Petersonb58dda72009-01-18 22:27:04 +0000986 for i, arg in enumerate(args):
Georg Brandlc1c4bf82010-10-15 16:07:41 +0000987 spec = formatargandannotation(arg)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000988 if defaults and i >= firstdefault:
989 spec = spec + formatvalue(defaults[i - firstdefault])
990 specs.append(spec)
Raymond Hettinger936654b2002-06-01 03:06:31 +0000991 if varargs is not None:
Guido van Rossum2e65f892007-02-28 22:03:49 +0000992 specs.append(formatvarargs(formatargandannotation(varargs)))
993 else:
994 if kwonlyargs:
995 specs.append('*')
996 if kwonlyargs:
997 for kwonlyarg in kwonlyargs:
998 spec = formatargandannotation(kwonlyarg)
Benjamin Peterson9953a8d2009-01-17 04:15:01 +0000999 if kwonlydefaults and kwonlyarg in kwonlydefaults:
Guido van Rossum2e65f892007-02-28 22:03:49 +00001000 spec += formatvalue(kwonlydefaults[kwonlyarg])
1001 specs.append(spec)
Raymond Hettinger936654b2002-06-01 03:06:31 +00001002 if varkw is not None:
Guido van Rossum2e65f892007-02-28 22:03:49 +00001003 specs.append(formatvarkw(formatargandannotation(varkw)))
Neal Norwitz9d72bb42007-04-17 08:48:32 +00001004 result = '(' + ', '.join(specs) + ')'
Guido van Rossum2e65f892007-02-28 22:03:49 +00001005 if 'return' in annotations:
1006 result += formatreturns(formatannotation(annotations['return']))
1007 return result
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001008
1009def formatargvalues(args, varargs, varkw, locals,
1010 formatarg=str,
1011 formatvarargs=lambda name: '*' + name,
1012 formatvarkw=lambda name: '**' + name,
Georg Brandlc1c4bf82010-10-15 16:07:41 +00001013 formatvalue=lambda value: '=' + repr(value)):
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001014 """Format an argument spec from the 4 values returned by getargvalues.
1015
1016 The first four arguments are (args, varargs, varkw, locals). The
1017 next four arguments are the corresponding optional formatting functions
1018 that are called to turn names and values into strings. The ninth
1019 argument is an optional function to format the sequence of arguments."""
1020 def convert(name, locals=locals,
1021 formatarg=formatarg, formatvalue=formatvalue):
1022 return formatarg(name) + formatvalue(locals[name])
1023 specs = []
1024 for i in range(len(args)):
Georg Brandlc1c4bf82010-10-15 16:07:41 +00001025 specs.append(convert(args[i]))
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001026 if varargs:
1027 specs.append(formatvarargs(varargs) + formatvalue(locals[varargs]))
1028 if varkw:
1029 specs.append(formatvarkw(varkw) + formatvalue(locals[varkw]))
Neal Norwitz9d72bb42007-04-17 08:48:32 +00001030 return '(' + ', '.join(specs) + ')'
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001031
Benjamin Petersone109c702011-06-24 09:37:26 -05001032def _missing_arguments(f_name, argnames, pos, values):
1033 names = [repr(name) for name in argnames if name not in values]
1034 missing = len(names)
1035 if missing == 1:
1036 s = names[0]
1037 elif missing == 2:
1038 s = "{} and {}".format(*names)
1039 else:
1040 tail = ", {} and {}".format(names[-2:])
1041 del names[-2:]
1042 s = ", ".join(names) + tail
1043 raise TypeError("%s() missing %i required %s argument%s: %s" %
1044 (f_name, missing,
1045 "positional" if pos else "keyword-only",
1046 "" if missing == 1 else "s", s))
1047
1048def _too_many(f_name, args, kwonly, varargs, defcount, given, values):
Benjamin Petersonb204a422011-06-05 22:04:07 -05001049 atleast = len(args) - defcount
Benjamin Petersonb204a422011-06-05 22:04:07 -05001050 kwonly_given = len([arg for arg in kwonly if arg in values])
1051 if varargs:
1052 plural = atleast != 1
1053 sig = "at least %d" % (atleast,)
1054 elif defcount:
1055 plural = True
1056 sig = "from %d to %d" % (atleast, len(args))
1057 else:
1058 plural = len(args) != 1
1059 sig = str(len(args))
1060 kwonly_sig = ""
1061 if kwonly_given:
1062 msg = " positional argument%s (and %d keyword-only argument%s)"
1063 kwonly_sig = (msg % ("s" if given != 1 else "", kwonly_given,
1064 "s" if kwonly_given != 1 else ""))
1065 raise TypeError("%s() takes %s positional argument%s but %d%s %s given" %
1066 (f_name, sig, "s" if plural else "", given, kwonly_sig,
1067 "was" if given == 1 and not kwonly_given else "were"))
1068
Benjamin Peterson25cd7eb2010-03-30 18:42:32 +00001069def getcallargs(func, *positional, **named):
1070 """Get the mapping of arguments to values.
1071
1072 A dict is returned, with keys the function argument names (including the
1073 names of the * and ** arguments, if any), and values the respective bound
1074 values from 'positional' and 'named'."""
1075 spec = getfullargspec(func)
1076 args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults, ann = spec
1077 f_name = func.__name__
1078 arg2value = {}
1079
Benjamin Petersonb204a422011-06-05 22:04:07 -05001080
Benjamin Peterson25cd7eb2010-03-30 18:42:32 +00001081 if ismethod(func) and func.__self__ is not None:
1082 # implicit 'self' (or 'cls' for classmethods) argument
1083 positional = (func.__self__,) + positional
1084 num_pos = len(positional)
Benjamin Peterson25cd7eb2010-03-30 18:42:32 +00001085 num_args = len(args)
1086 num_defaults = len(defaults) if defaults else 0
Benjamin Peterson25cd7eb2010-03-30 18:42:32 +00001087
Benjamin Petersonb204a422011-06-05 22:04:07 -05001088 n = min(num_pos, num_args)
1089 for i in range(n):
1090 arg2value[args[i]] = positional[i]
1091 if varargs:
1092 arg2value[varargs] = tuple(positional[n:])
1093 possible_kwargs = set(args + kwonlyargs)
Benjamin Peterson25cd7eb2010-03-30 18:42:32 +00001094 if varkw:
Benjamin Petersonb204a422011-06-05 22:04:07 -05001095 arg2value[varkw] = {}
1096 for kw, value in named.items():
1097 if kw not in possible_kwargs:
1098 if not varkw:
1099 raise TypeError("%s() got an unexpected keyword argument %r" %
1100 (f_name, kw))
1101 arg2value[varkw][kw] = value
1102 continue
1103 if kw in arg2value:
1104 raise TypeError("%s() got multiple values for argument %r" %
1105 (f_name, kw))
1106 arg2value[kw] = value
1107 if num_pos > num_args and not varargs:
Benjamin Petersone109c702011-06-24 09:37:26 -05001108 _too_many(f_name, args, kwonlyargs, varargs, num_defaults,
1109 num_pos, arg2value)
Benjamin Petersonb204a422011-06-05 22:04:07 -05001110 if num_pos < num_args:
Benjamin Petersone109c702011-06-24 09:37:26 -05001111 req = args[:num_args - num_defaults]
1112 for arg in req:
Benjamin Petersonb204a422011-06-05 22:04:07 -05001113 if arg not in arg2value:
Benjamin Petersone109c702011-06-24 09:37:26 -05001114 _missing_arguments(f_name, req, True, arg2value)
Benjamin Petersonb204a422011-06-05 22:04:07 -05001115 for i, arg in enumerate(args[num_args - num_defaults:]):
1116 if arg not in arg2value:
1117 arg2value[arg] = defaults[i]
Benjamin Petersone109c702011-06-24 09:37:26 -05001118 missing = 0
Benjamin Petersonb204a422011-06-05 22:04:07 -05001119 for kwarg in kwonlyargs:
1120 if kwarg not in arg2value:
Benjamin Petersone109c702011-06-24 09:37:26 -05001121 if kwarg in kwonlydefaults:
1122 arg2value[kwarg] = kwonlydefaults[kwarg]
1123 else:
1124 missing += 1
1125 if missing:
1126 _missing_arguments(f_name, kwonlyargs, False, arg2value)
Benjamin Peterson25cd7eb2010-03-30 18:42:32 +00001127 return arg2value
1128
Nick Coghlan2f92e542012-06-23 19:39:55 +10001129ClosureVars = namedtuple('ClosureVars', 'nonlocals globals builtins unbound')
1130
1131def getclosurevars(func):
1132 """
1133 Get the mapping of free variables to their current values.
1134
Meador Inge8fda3592012-07-19 21:33:21 -05001135 Returns a named tuple of dicts mapping the current nonlocal, global
Nick Coghlan2f92e542012-06-23 19:39:55 +10001136 and builtin references as seen by the body of the function. A final
1137 set of unbound names that could not be resolved is also provided.
1138 """
1139
1140 if ismethod(func):
1141 func = func.__func__
1142
1143 if not isfunction(func):
1144 raise TypeError("'{!r}' is not a Python function".format(func))
1145
1146 code = func.__code__
1147 # Nonlocal references are named in co_freevars and resolved
1148 # by looking them up in __closure__ by positional index
1149 if func.__closure__ is None:
1150 nonlocal_vars = {}
1151 else:
1152 nonlocal_vars = {
1153 var : cell.cell_contents
1154 for var, cell in zip(code.co_freevars, func.__closure__)
1155 }
1156
1157 # Global and builtin references are named in co_names and resolved
1158 # by looking them up in __globals__ or __builtins__
1159 global_ns = func.__globals__
1160 builtin_ns = global_ns.get("__builtins__", builtins.__dict__)
1161 if ismodule(builtin_ns):
1162 builtin_ns = builtin_ns.__dict__
1163 global_vars = {}
1164 builtin_vars = {}
1165 unbound_names = set()
1166 for name in code.co_names:
1167 if name in ("None", "True", "False"):
1168 # Because these used to be builtins instead of keywords, they
1169 # may still show up as name references. We ignore them.
1170 continue
1171 try:
1172 global_vars[name] = global_ns[name]
1173 except KeyError:
1174 try:
1175 builtin_vars[name] = builtin_ns[name]
1176 except KeyError:
1177 unbound_names.add(name)
1178
1179 return ClosureVars(nonlocal_vars, global_vars,
1180 builtin_vars, unbound_names)
1181
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001182# -------------------------------------------------- stack frame extraction
Christian Heimes25bb7832008-01-11 16:17:00 +00001183
1184Traceback = namedtuple('Traceback', 'filename lineno function code_context index')
1185
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001186def getframeinfo(frame, context=1):
1187 """Get information about a frame or traceback object.
1188
1189 A tuple of five things is returned: the filename, the line number of
1190 the current line, the function name, a list of lines of context from
1191 the source code, and the index of the current line within that list.
1192 The optional second argument specifies the number of lines of context
1193 to return, which are centered around the current line."""
1194 if istraceback(frame):
Andrew M. Kuchlingba8b6bc2004-06-05 14:11:59 +00001195 lineno = frame.tb_lineno
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001196 frame = frame.tb_frame
Andrew M. Kuchlingba8b6bc2004-06-05 14:11:59 +00001197 else:
1198 lineno = frame.f_lineno
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001199 if not isframe(frame):
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00001200 raise TypeError('{!r} is not a frame or traceback object'.format(frame))
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001201
Neil Schemenauerf06f8532002-03-23 23:51:04 +00001202 filename = getsourcefile(frame) or getfile(frame)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001203 if context > 0:
Guido van Rossum54e54c62001-09-04 19:14:14 +00001204 start = lineno - 1 - context//2
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001205 try:
1206 lines, lnum = findsource(frame)
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02001207 except OSError:
Ka-Ping Yee4eb0c002001-03-02 05:50:34 +00001208 lines = index = None
1209 else:
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001210 start = max(start, 1)
Raymond Hettingera0501712004-06-15 11:22:53 +00001211 start = max(0, min(start, len(lines) - context))
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001212 lines = lines[start:start+context]
Ka-Ping Yee59ade082001-03-01 03:55:35 +00001213 index = lineno - 1 - start
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001214 else:
1215 lines = index = None
1216
Christian Heimes25bb7832008-01-11 16:17:00 +00001217 return Traceback(filename, lineno, frame.f_code.co_name, lines, index)
Ka-Ping Yee59ade082001-03-01 03:55:35 +00001218
1219def getlineno(frame):
1220 """Get the line number from a frame object, allowing for optimization."""
Michael W. Hudsondd32a912002-08-15 14:59:02 +00001221 # FrameType.f_lineno is now a descriptor that grovels co_lnotab
1222 return frame.f_lineno
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001223
1224def getouterframes(frame, context=1):
1225 """Get a list of records for a frame and all higher (calling) frames.
1226
1227 Each record contains a frame object, filename, line number, function
1228 name, a list of lines of context, and index within the context."""
1229 framelist = []
1230 while frame:
1231 framelist.append((frame,) + getframeinfo(frame, context))
1232 frame = frame.f_back
1233 return framelist
1234
1235def getinnerframes(tb, context=1):
1236 """Get a list of records for a traceback's frame and all lower frames.
1237
1238 Each record contains a frame object, filename, line number, function
1239 name, a list of lines of context, and index within the context."""
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001240 framelist = []
1241 while tb:
1242 framelist.append((tb.tb_frame,) + getframeinfo(tb, context))
1243 tb = tb.tb_next
1244 return framelist
1245
Benjamin Peterson42ac4752010-08-09 13:05:35 +00001246def currentframe():
Benjamin Petersona3a3fc62010-08-09 15:49:56 +00001247 """Return the frame of the caller or None if this is not possible."""
Benjamin Peterson42ac4752010-08-09 13:05:35 +00001248 return sys._getframe(1) if hasattr(sys, "_getframe") else None
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001249
1250def stack(context=1):
1251 """Return a list of records for the stack above the caller's frame."""
Jeremy Hyltonab919022003-06-27 18:41:20 +00001252 return getouterframes(sys._getframe(1), context)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001253
1254def trace(context=1):
Tim Peters85ba6732001-02-28 08:26:44 +00001255 """Return a list of records for the stack below the current exception."""
Fred Draked451ec12002-04-26 02:29:55 +00001256 return getinnerframes(sys.exc_info()[2], context)
Michael Foord95fc51d2010-11-20 15:07:30 +00001257
1258
1259# ------------------------------------------------ static version of getattr
1260
1261_sentinel = object()
1262
Michael Foorde5162652010-11-20 16:40:44 +00001263def _static_getmro(klass):
1264 return type.__dict__['__mro__'].__get__(klass)
1265
Michael Foord95fc51d2010-11-20 15:07:30 +00001266def _check_instance(obj, attr):
1267 instance_dict = {}
1268 try:
1269 instance_dict = object.__getattribute__(obj, "__dict__")
1270 except AttributeError:
1271 pass
Michael Foorddcebe0f2011-03-15 19:20:44 -04001272 return dict.get(instance_dict, attr, _sentinel)
Michael Foord95fc51d2010-11-20 15:07:30 +00001273
1274
1275def _check_class(klass, attr):
Michael Foorde5162652010-11-20 16:40:44 +00001276 for entry in _static_getmro(klass):
Michael Foorda51623b2011-12-18 22:01:40 +00001277 if _shadowed_dict(type(entry)) is _sentinel:
Michael Foorddcebe0f2011-03-15 19:20:44 -04001278 try:
1279 return entry.__dict__[attr]
1280 except KeyError:
1281 pass
Michael Foord95fc51d2010-11-20 15:07:30 +00001282 return _sentinel
1283
Michael Foord35184ed2010-11-20 16:58:30 +00001284def _is_type(obj):
1285 try:
1286 _static_getmro(obj)
1287 except TypeError:
1288 return False
1289 return True
1290
Michael Foorddcebe0f2011-03-15 19:20:44 -04001291def _shadowed_dict(klass):
1292 dict_attr = type.__dict__["__dict__"]
1293 for entry in _static_getmro(klass):
1294 try:
1295 class_dict = dict_attr.__get__(entry)["__dict__"]
1296 except KeyError:
1297 pass
1298 else:
1299 if not (type(class_dict) is types.GetSetDescriptorType and
1300 class_dict.__name__ == "__dict__" and
1301 class_dict.__objclass__ is entry):
Michael Foorda51623b2011-12-18 22:01:40 +00001302 return class_dict
1303 return _sentinel
Michael Foord95fc51d2010-11-20 15:07:30 +00001304
1305def getattr_static(obj, attr, default=_sentinel):
1306 """Retrieve attributes without triggering dynamic lookup via the
1307 descriptor protocol, __getattr__ or __getattribute__.
1308
1309 Note: this function may not be able to retrieve all attributes
1310 that getattr can fetch (like dynamically created attributes)
1311 and may find attributes that getattr can't (like descriptors
1312 that raise AttributeError). It can also return descriptor objects
1313 instead of instance members in some cases. See the
1314 documentation for details.
1315 """
1316 instance_result = _sentinel
Michael Foord35184ed2010-11-20 16:58:30 +00001317 if not _is_type(obj):
Michael Foordcc7ebb82010-11-20 16:20:16 +00001318 klass = type(obj)
Michael Foorda51623b2011-12-18 22:01:40 +00001319 dict_attr = _shadowed_dict(klass)
1320 if (dict_attr is _sentinel or
1321 type(dict_attr) is types.MemberDescriptorType):
Michael Foorddcebe0f2011-03-15 19:20:44 -04001322 instance_result = _check_instance(obj, attr)
Michael Foord95fc51d2010-11-20 15:07:30 +00001323 else:
1324 klass = obj
1325
1326 klass_result = _check_class(klass, attr)
1327
1328 if instance_result is not _sentinel and klass_result is not _sentinel:
1329 if (_check_class(type(klass_result), '__get__') is not _sentinel and
1330 _check_class(type(klass_result), '__set__') is not _sentinel):
1331 return klass_result
1332
1333 if instance_result is not _sentinel:
1334 return instance_result
1335 if klass_result is not _sentinel:
1336 return klass_result
1337
1338 if obj is klass:
1339 # for types we check the metaclass too
Michael Foorde5162652010-11-20 16:40:44 +00001340 for entry in _static_getmro(type(klass)):
Michael Foord3ba95f82011-12-22 01:13:37 +00001341 if _shadowed_dict(type(entry)) is _sentinel:
1342 try:
1343 return entry.__dict__[attr]
1344 except KeyError:
1345 pass
Michael Foord95fc51d2010-11-20 15:07:30 +00001346 if default is not _sentinel:
1347 return default
1348 raise AttributeError(attr)
Nick Coghlane0f04652010-11-21 03:44:04 +00001349
1350
Nick Coghlan04e2e3f2012-06-23 19:52:05 +10001351# ------------------------------------------------ generator introspection
1352
Nick Coghlan7921b9f2010-11-30 06:36:04 +00001353GEN_CREATED = 'GEN_CREATED'
1354GEN_RUNNING = 'GEN_RUNNING'
1355GEN_SUSPENDED = 'GEN_SUSPENDED'
1356GEN_CLOSED = 'GEN_CLOSED'
Nick Coghlane0f04652010-11-21 03:44:04 +00001357
1358def getgeneratorstate(generator):
1359 """Get current state of a generator-iterator.
1360
1361 Possible states are:
1362 GEN_CREATED: Waiting to start execution.
1363 GEN_RUNNING: Currently being executed by the interpreter.
1364 GEN_SUSPENDED: Currently suspended at a yield expression.
1365 GEN_CLOSED: Execution has completed.
1366 """
1367 if generator.gi_running:
1368 return GEN_RUNNING
1369 if generator.gi_frame is None:
1370 return GEN_CLOSED
1371 if generator.gi_frame.f_lasti == -1:
1372 return GEN_CREATED
1373 return GEN_SUSPENDED
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07001374
1375
Nick Coghlan04e2e3f2012-06-23 19:52:05 +10001376def getgeneratorlocals(generator):
1377 """
1378 Get the mapping of generator local variables to their current values.
1379
1380 A dict is returned, with the keys the local variable names and values the
1381 bound values."""
1382
1383 if not isgenerator(generator):
1384 raise TypeError("'{!r}' is not a Python generator".format(generator))
1385
1386 frame = getattr(generator, "gi_frame", None)
1387 if frame is not None:
1388 return generator.gi_frame.f_locals
1389 else:
1390 return {}
1391
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07001392###############################################################################
1393### Function Signature Object (PEP 362)
1394###############################################################################
1395
1396
1397_WrapperDescriptor = type(type.__call__)
1398_MethodWrapper = type(all.__call__)
1399
1400_NonUserDefinedCallables = (_WrapperDescriptor,
1401 _MethodWrapper,
1402 types.BuiltinFunctionType)
1403
1404
1405def _get_user_defined_method(cls, method_name):
1406 try:
1407 meth = getattr(cls, method_name)
1408 except AttributeError:
1409 return
1410 else:
1411 if not isinstance(meth, _NonUserDefinedCallables):
1412 # Once '__signature__' will be added to 'C'-level
1413 # callables, this check won't be necessary
1414 return meth
1415
1416
1417def signature(obj):
1418 '''Get a signature object for the passed callable.'''
1419
1420 if not callable(obj):
1421 raise TypeError('{!r} is not a callable object'.format(obj))
1422
1423 if isinstance(obj, types.MethodType):
1424 # In this case we skip the first parameter of the underlying
1425 # function (usually `self` or `cls`).
1426 sig = signature(obj.__func__)
1427 return sig.replace(parameters=tuple(sig.parameters.values())[1:])
1428
Nick Coghlane8c45d62013-07-28 20:00:01 +10001429 # Was this function wrapped by a decorator?
1430 obj = unwrap(obj, stop=(lambda f: hasattr(f, "__signature__")))
1431
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07001432 try:
1433 sig = obj.__signature__
1434 except AttributeError:
1435 pass
1436 else:
1437 if sig is not None:
1438 return sig
1439
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07001440
1441 if isinstance(obj, types.FunctionType):
1442 return Signature.from_function(obj)
1443
1444 if isinstance(obj, functools.partial):
1445 sig = signature(obj.func)
1446
1447 new_params = OrderedDict(sig.parameters.items())
1448
1449 partial_args = obj.args or ()
1450 partial_keywords = obj.keywords or {}
1451 try:
1452 ba = sig.bind_partial(*partial_args, **partial_keywords)
1453 except TypeError as ex:
1454 msg = 'partial object {!r} has incorrect arguments'.format(obj)
1455 raise ValueError(msg) from ex
1456
1457 for arg_name, arg_value in ba.arguments.items():
1458 param = new_params[arg_name]
1459 if arg_name in partial_keywords:
1460 # We set a new default value, because the following code
1461 # is correct:
1462 #
1463 # >>> def foo(a): print(a)
1464 # >>> print(partial(partial(foo, a=10), a=20)())
1465 # 20
1466 # >>> print(partial(partial(foo, a=10), a=20)(a=30))
1467 # 30
1468 #
1469 # So, with 'partial' objects, passing a keyword argument is
1470 # like setting a new default value for the corresponding
1471 # parameter
1472 #
1473 # We also mark this parameter with '_partial_kwarg'
1474 # flag. Later, in '_bind', the 'default' value of this
1475 # parameter will be added to 'kwargs', to simulate
1476 # the 'functools.partial' real call.
1477 new_params[arg_name] = param.replace(default=arg_value,
1478 _partial_kwarg=True)
1479
1480 elif (param.kind not in (_VAR_KEYWORD, _VAR_POSITIONAL) and
1481 not param._partial_kwarg):
1482 new_params.pop(arg_name)
1483
1484 return sig.replace(parameters=new_params.values())
1485
1486 sig = None
1487 if isinstance(obj, type):
1488 # obj is a class or a metaclass
1489
1490 # First, let's see if it has an overloaded __call__ defined
1491 # in its metaclass
1492 call = _get_user_defined_method(type(obj), '__call__')
1493 if call is not None:
1494 sig = signature(call)
1495 else:
1496 # Now we check if the 'obj' class has a '__new__' method
1497 new = _get_user_defined_method(obj, '__new__')
1498 if new is not None:
1499 sig = signature(new)
1500 else:
1501 # Finally, we should have at least __init__ implemented
1502 init = _get_user_defined_method(obj, '__init__')
1503 if init is not None:
1504 sig = signature(init)
1505 elif not isinstance(obj, _NonUserDefinedCallables):
1506 # An object with __call__
1507 # We also check that the 'obj' is not an instance of
1508 # _WrapperDescriptor or _MethodWrapper to avoid
1509 # infinite recursion (and even potential segfault)
1510 call = _get_user_defined_method(type(obj), '__call__')
1511 if call is not None:
1512 sig = signature(call)
1513
1514 if sig is not None:
1515 # For classes and objects we skip the first parameter of their
1516 # __call__, __new__, or __init__ methods
1517 return sig.replace(parameters=tuple(sig.parameters.values())[1:])
1518
1519 if isinstance(obj, types.BuiltinFunctionType):
1520 # Raise a nicer error message for builtins
1521 msg = 'no signature found for builtin function {!r}'.format(obj)
1522 raise ValueError(msg)
1523
1524 raise ValueError('callable {!r} is not supported by signature'.format(obj))
1525
1526
1527class _void:
1528 '''A private marker - used in Parameter & Signature'''
1529
1530
1531class _empty:
1532 pass
1533
1534
1535class _ParameterKind(int):
1536 def __new__(self, *args, name):
1537 obj = int.__new__(self, *args)
1538 obj._name = name
1539 return obj
1540
1541 def __str__(self):
1542 return self._name
1543
1544 def __repr__(self):
1545 return '<_ParameterKind: {!r}>'.format(self._name)
1546
1547
1548_POSITIONAL_ONLY = _ParameterKind(0, name='POSITIONAL_ONLY')
1549_POSITIONAL_OR_KEYWORD = _ParameterKind(1, name='POSITIONAL_OR_KEYWORD')
1550_VAR_POSITIONAL = _ParameterKind(2, name='VAR_POSITIONAL')
1551_KEYWORD_ONLY = _ParameterKind(3, name='KEYWORD_ONLY')
1552_VAR_KEYWORD = _ParameterKind(4, name='VAR_KEYWORD')
1553
1554
1555class Parameter:
1556 '''Represents a parameter in a function signature.
1557
1558 Has the following public attributes:
1559
1560 * name : str
1561 The name of the parameter as a string.
1562 * default : object
1563 The default value for the parameter if specified. If the
1564 parameter has no default value, this attribute is not set.
1565 * annotation
1566 The annotation for the parameter if specified. If the
1567 parameter has no annotation, this attribute is not set.
1568 * kind : str
1569 Describes how argument values are bound to the parameter.
1570 Possible values: `Parameter.POSITIONAL_ONLY`,
1571 `Parameter.POSITIONAL_OR_KEYWORD`, `Parameter.VAR_POSITIONAL`,
1572 `Parameter.KEYWORD_ONLY`, `Parameter.VAR_KEYWORD`.
1573 '''
1574
1575 __slots__ = ('_name', '_kind', '_default', '_annotation', '_partial_kwarg')
1576
1577 POSITIONAL_ONLY = _POSITIONAL_ONLY
1578 POSITIONAL_OR_KEYWORD = _POSITIONAL_OR_KEYWORD
1579 VAR_POSITIONAL = _VAR_POSITIONAL
1580 KEYWORD_ONLY = _KEYWORD_ONLY
1581 VAR_KEYWORD = _VAR_KEYWORD
1582
1583 empty = _empty
1584
1585 def __init__(self, name, kind, *, default=_empty, annotation=_empty,
1586 _partial_kwarg=False):
1587
1588 if kind not in (_POSITIONAL_ONLY, _POSITIONAL_OR_KEYWORD,
1589 _VAR_POSITIONAL, _KEYWORD_ONLY, _VAR_KEYWORD):
1590 raise ValueError("invalid value for 'Parameter.kind' attribute")
1591 self._kind = kind
1592
1593 if default is not _empty:
1594 if kind in (_VAR_POSITIONAL, _VAR_KEYWORD):
1595 msg = '{} parameters cannot have default values'.format(kind)
1596 raise ValueError(msg)
1597 self._default = default
1598 self._annotation = annotation
1599
1600 if name is None:
1601 if kind != _POSITIONAL_ONLY:
1602 raise ValueError("None is not a valid name for a "
1603 "non-positional-only parameter")
1604 self._name = name
1605 else:
1606 name = str(name)
1607 if kind != _POSITIONAL_ONLY and not name.isidentifier():
1608 msg = '{!r} is not a valid parameter name'.format(name)
1609 raise ValueError(msg)
1610 self._name = name
1611
1612 self._partial_kwarg = _partial_kwarg
1613
1614 @property
1615 def name(self):
1616 return self._name
1617
1618 @property
1619 def default(self):
1620 return self._default
1621
1622 @property
1623 def annotation(self):
1624 return self._annotation
1625
1626 @property
1627 def kind(self):
1628 return self._kind
1629
1630 def replace(self, *, name=_void, kind=_void, annotation=_void,
1631 default=_void, _partial_kwarg=_void):
1632 '''Creates a customized copy of the Parameter.'''
1633
1634 if name is _void:
1635 name = self._name
1636
1637 if kind is _void:
1638 kind = self._kind
1639
1640 if annotation is _void:
1641 annotation = self._annotation
1642
1643 if default is _void:
1644 default = self._default
1645
1646 if _partial_kwarg is _void:
1647 _partial_kwarg = self._partial_kwarg
1648
1649 return type(self)(name, kind, default=default, annotation=annotation,
1650 _partial_kwarg=_partial_kwarg)
1651
1652 def __str__(self):
1653 kind = self.kind
1654
1655 formatted = self._name
1656 if kind == _POSITIONAL_ONLY:
1657 if formatted is None:
1658 formatted = ''
1659 formatted = '<{}>'.format(formatted)
1660
1661 # Add annotation and default value
1662 if self._annotation is not _empty:
1663 formatted = '{}:{}'.format(formatted,
1664 formatannotation(self._annotation))
1665
1666 if self._default is not _empty:
1667 formatted = '{}={}'.format(formatted, repr(self._default))
1668
1669 if kind == _VAR_POSITIONAL:
1670 formatted = '*' + formatted
1671 elif kind == _VAR_KEYWORD:
1672 formatted = '**' + formatted
1673
1674 return formatted
1675
1676 def __repr__(self):
1677 return '<{} at {:#x} {!r}>'.format(self.__class__.__name__,
1678 id(self), self.name)
1679
1680 def __eq__(self, other):
1681 return (issubclass(other.__class__, Parameter) and
1682 self._name == other._name and
1683 self._kind == other._kind and
1684 self._default == other._default and
1685 self._annotation == other._annotation)
1686
1687 def __ne__(self, other):
1688 return not self.__eq__(other)
1689
1690
1691class BoundArguments:
1692 '''Result of `Signature.bind` call. Holds the mapping of arguments
1693 to the function's parameters.
1694
1695 Has the following public attributes:
1696
1697 * arguments : OrderedDict
1698 An ordered mutable mapping of parameters' names to arguments' values.
1699 Does not contain arguments' default values.
1700 * signature : Signature
1701 The Signature object that created this instance.
1702 * args : tuple
1703 Tuple of positional arguments values.
1704 * kwargs : dict
1705 Dict of keyword arguments values.
1706 '''
1707
1708 def __init__(self, signature, arguments):
1709 self.arguments = arguments
1710 self._signature = signature
1711
1712 @property
1713 def signature(self):
1714 return self._signature
1715
1716 @property
1717 def args(self):
1718 args = []
1719 for param_name, param in self._signature.parameters.items():
1720 if (param.kind in (_VAR_KEYWORD, _KEYWORD_ONLY) or
1721 param._partial_kwarg):
1722 # Keyword arguments mapped by 'functools.partial'
1723 # (Parameter._partial_kwarg is True) are mapped
1724 # in 'BoundArguments.kwargs', along with VAR_KEYWORD &
1725 # KEYWORD_ONLY
1726 break
1727
1728 try:
1729 arg = self.arguments[param_name]
1730 except KeyError:
1731 # We're done here. Other arguments
1732 # will be mapped in 'BoundArguments.kwargs'
1733 break
1734 else:
1735 if param.kind == _VAR_POSITIONAL:
1736 # *args
1737 args.extend(arg)
1738 else:
1739 # plain argument
1740 args.append(arg)
1741
1742 return tuple(args)
1743
1744 @property
1745 def kwargs(self):
1746 kwargs = {}
1747 kwargs_started = False
1748 for param_name, param in self._signature.parameters.items():
1749 if not kwargs_started:
1750 if (param.kind in (_VAR_KEYWORD, _KEYWORD_ONLY) or
1751 param._partial_kwarg):
1752 kwargs_started = True
1753 else:
1754 if param_name not in self.arguments:
1755 kwargs_started = True
1756 continue
1757
1758 if not kwargs_started:
1759 continue
1760
1761 try:
1762 arg = self.arguments[param_name]
1763 except KeyError:
1764 pass
1765 else:
1766 if param.kind == _VAR_KEYWORD:
1767 # **kwargs
1768 kwargs.update(arg)
1769 else:
1770 # plain keyword argument
1771 kwargs[param_name] = arg
1772
1773 return kwargs
1774
1775 def __eq__(self, other):
1776 return (issubclass(other.__class__, BoundArguments) and
1777 self.signature == other.signature and
1778 self.arguments == other.arguments)
1779
1780 def __ne__(self, other):
1781 return not self.__eq__(other)
1782
1783
1784class Signature:
1785 '''A Signature object represents the overall signature of a function.
1786 It stores a Parameter object for each parameter accepted by the
1787 function, as well as information specific to the function itself.
1788
1789 A Signature object has the following public attributes and methods:
1790
1791 * parameters : OrderedDict
1792 An ordered mapping of parameters' names to the corresponding
1793 Parameter objects (keyword-only arguments are in the same order
1794 as listed in `code.co_varnames`).
1795 * return_annotation : object
1796 The annotation for the return type of the function if specified.
1797 If the function has no annotation for its return type, this
1798 attribute is not set.
1799 * bind(*args, **kwargs) -> BoundArguments
1800 Creates a mapping from positional and keyword arguments to
1801 parameters.
1802 * bind_partial(*args, **kwargs) -> BoundArguments
1803 Creates a partial mapping from positional and keyword arguments
1804 to parameters (simulating 'functools.partial' behavior.)
1805 '''
1806
1807 __slots__ = ('_return_annotation', '_parameters')
1808
1809 _parameter_cls = Parameter
1810 _bound_arguments_cls = BoundArguments
1811
1812 empty = _empty
1813
1814 def __init__(self, parameters=None, *, return_annotation=_empty,
1815 __validate_parameters__=True):
1816 '''Constructs Signature from the given list of Parameter
1817 objects and 'return_annotation'. All arguments are optional.
1818 '''
1819
1820 if parameters is None:
1821 params = OrderedDict()
1822 else:
1823 if __validate_parameters__:
1824 params = OrderedDict()
1825 top_kind = _POSITIONAL_ONLY
1826
1827 for idx, param in enumerate(parameters):
1828 kind = param.kind
1829 if kind < top_kind:
1830 msg = 'wrong parameter order: {} before {}'
1831 msg = msg.format(top_kind, param.kind)
1832 raise ValueError(msg)
1833 else:
1834 top_kind = kind
1835
1836 name = param.name
1837 if name is None:
1838 name = str(idx)
1839 param = param.replace(name=name)
1840
1841 if name in params:
1842 msg = 'duplicate parameter name: {!r}'.format(name)
1843 raise ValueError(msg)
1844 params[name] = param
1845 else:
1846 params = OrderedDict(((param.name, param)
1847 for param in parameters))
1848
1849 self._parameters = types.MappingProxyType(params)
1850 self._return_annotation = return_annotation
1851
1852 @classmethod
1853 def from_function(cls, func):
1854 '''Constructs Signature for the given python function'''
1855
1856 if not isinstance(func, types.FunctionType):
1857 raise TypeError('{!r} is not a Python function'.format(func))
1858
1859 Parameter = cls._parameter_cls
1860
1861 # Parameter information.
1862 func_code = func.__code__
1863 pos_count = func_code.co_argcount
1864 arg_names = func_code.co_varnames
1865 positional = tuple(arg_names[:pos_count])
1866 keyword_only_count = func_code.co_kwonlyargcount
1867 keyword_only = arg_names[pos_count:(pos_count + keyword_only_count)]
1868 annotations = func.__annotations__
1869 defaults = func.__defaults__
1870 kwdefaults = func.__kwdefaults__
1871
1872 if defaults:
1873 pos_default_count = len(defaults)
1874 else:
1875 pos_default_count = 0
1876
1877 parameters = []
1878
1879 # Non-keyword-only parameters w/o defaults.
1880 non_default_count = pos_count - pos_default_count
1881 for name in positional[:non_default_count]:
1882 annotation = annotations.get(name, _empty)
1883 parameters.append(Parameter(name, annotation=annotation,
1884 kind=_POSITIONAL_OR_KEYWORD))
1885
1886 # ... w/ defaults.
1887 for offset, name in enumerate(positional[non_default_count:]):
1888 annotation = annotations.get(name, _empty)
1889 parameters.append(Parameter(name, annotation=annotation,
1890 kind=_POSITIONAL_OR_KEYWORD,
1891 default=defaults[offset]))
1892
1893 # *args
1894 if func_code.co_flags & 0x04:
1895 name = arg_names[pos_count + keyword_only_count]
1896 annotation = annotations.get(name, _empty)
1897 parameters.append(Parameter(name, annotation=annotation,
1898 kind=_VAR_POSITIONAL))
1899
1900 # Keyword-only parameters.
1901 for name in keyword_only:
1902 default = _empty
1903 if kwdefaults is not None:
1904 default = kwdefaults.get(name, _empty)
1905
1906 annotation = annotations.get(name, _empty)
1907 parameters.append(Parameter(name, annotation=annotation,
1908 kind=_KEYWORD_ONLY,
1909 default=default))
1910 # **kwargs
1911 if func_code.co_flags & 0x08:
1912 index = pos_count + keyword_only_count
1913 if func_code.co_flags & 0x04:
1914 index += 1
1915
1916 name = arg_names[index]
1917 annotation = annotations.get(name, _empty)
1918 parameters.append(Parameter(name, annotation=annotation,
1919 kind=_VAR_KEYWORD))
1920
1921 return cls(parameters,
1922 return_annotation=annotations.get('return', _empty),
1923 __validate_parameters__=False)
1924
1925 @property
1926 def parameters(self):
1927 return self._parameters
1928
1929 @property
1930 def return_annotation(self):
1931 return self._return_annotation
1932
1933 def replace(self, *, parameters=_void, return_annotation=_void):
1934 '''Creates a customized copy of the Signature.
1935 Pass 'parameters' and/or 'return_annotation' arguments
1936 to override them in the new copy.
1937 '''
1938
1939 if parameters is _void:
1940 parameters = self.parameters.values()
1941
1942 if return_annotation is _void:
1943 return_annotation = self._return_annotation
1944
1945 return type(self)(parameters,
1946 return_annotation=return_annotation)
1947
1948 def __eq__(self, other):
1949 if (not issubclass(type(other), Signature) or
1950 self.return_annotation != other.return_annotation or
1951 len(self.parameters) != len(other.parameters)):
1952 return False
1953
1954 other_positions = {param: idx
1955 for idx, param in enumerate(other.parameters.keys())}
1956
1957 for idx, (param_name, param) in enumerate(self.parameters.items()):
1958 if param.kind == _KEYWORD_ONLY:
1959 try:
1960 other_param = other.parameters[param_name]
1961 except KeyError:
1962 return False
1963 else:
1964 if param != other_param:
1965 return False
1966 else:
1967 try:
1968 other_idx = other_positions[param_name]
1969 except KeyError:
1970 return False
1971 else:
1972 if (idx != other_idx or
1973 param != other.parameters[param_name]):
1974 return False
1975
1976 return True
1977
1978 def __ne__(self, other):
1979 return not self.__eq__(other)
1980
1981 def _bind(self, args, kwargs, *, partial=False):
1982 '''Private method. Don't use directly.'''
1983
1984 arguments = OrderedDict()
1985
1986 parameters = iter(self.parameters.values())
1987 parameters_ex = ()
1988 arg_vals = iter(args)
1989
1990 if partial:
1991 # Support for binding arguments to 'functools.partial' objects.
1992 # See 'functools.partial' case in 'signature()' implementation
1993 # for details.
1994 for param_name, param in self.parameters.items():
1995 if (param._partial_kwarg and param_name not in kwargs):
1996 # Simulating 'functools.partial' behavior
1997 kwargs[param_name] = param.default
1998
1999 while True:
2000 # Let's iterate through the positional arguments and corresponding
2001 # parameters
2002 try:
2003 arg_val = next(arg_vals)
2004 except StopIteration:
2005 # No more positional arguments
2006 try:
2007 param = next(parameters)
2008 except StopIteration:
2009 # No more parameters. That's it. Just need to check that
2010 # we have no `kwargs` after this while loop
2011 break
2012 else:
2013 if param.kind == _VAR_POSITIONAL:
2014 # That's OK, just empty *args. Let's start parsing
2015 # kwargs
2016 break
2017 elif param.name in kwargs:
2018 if param.kind == _POSITIONAL_ONLY:
2019 msg = '{arg!r} parameter is positional only, ' \
2020 'but was passed as a keyword'
2021 msg = msg.format(arg=param.name)
2022 raise TypeError(msg) from None
2023 parameters_ex = (param,)
2024 break
2025 elif (param.kind == _VAR_KEYWORD or
2026 param.default is not _empty):
2027 # That's fine too - we have a default value for this
2028 # parameter. So, lets start parsing `kwargs`, starting
2029 # with the current parameter
2030 parameters_ex = (param,)
2031 break
2032 else:
2033 if partial:
2034 parameters_ex = (param,)
2035 break
2036 else:
2037 msg = '{arg!r} parameter lacking default value'
2038 msg = msg.format(arg=param.name)
2039 raise TypeError(msg) from None
2040 else:
2041 # We have a positional argument to process
2042 try:
2043 param = next(parameters)
2044 except StopIteration:
2045 raise TypeError('too many positional arguments') from None
2046 else:
2047 if param.kind in (_VAR_KEYWORD, _KEYWORD_ONLY):
2048 # Looks like we have no parameter for this positional
2049 # argument
2050 raise TypeError('too many positional arguments')
2051
2052 if param.kind == _VAR_POSITIONAL:
2053 # We have an '*args'-like argument, let's fill it with
2054 # all positional arguments we have left and move on to
2055 # the next phase
2056 values = [arg_val]
2057 values.extend(arg_vals)
2058 arguments[param.name] = tuple(values)
2059 break
2060
2061 if param.name in kwargs:
2062 raise TypeError('multiple values for argument '
2063 '{arg!r}'.format(arg=param.name))
2064
2065 arguments[param.name] = arg_val
2066
2067 # Now, we iterate through the remaining parameters to process
2068 # keyword arguments
2069 kwargs_param = None
2070 for param in itertools.chain(parameters_ex, parameters):
2071 if param.kind == _POSITIONAL_ONLY:
2072 # This should never happen in case of a properly built
2073 # Signature object (but let's have this check here
2074 # to ensure correct behaviour just in case)
2075 raise TypeError('{arg!r} parameter is positional only, '
2076 'but was passed as a keyword'. \
2077 format(arg=param.name))
2078
2079 if param.kind == _VAR_KEYWORD:
2080 # Memorize that we have a '**kwargs'-like parameter
2081 kwargs_param = param
2082 continue
2083
2084 param_name = param.name
2085 try:
2086 arg_val = kwargs.pop(param_name)
2087 except KeyError:
2088 # We have no value for this parameter. It's fine though,
2089 # if it has a default value, or it is an '*args'-like
2090 # parameter, left alone by the processing of positional
2091 # arguments.
2092 if (not partial and param.kind != _VAR_POSITIONAL and
2093 param.default is _empty):
2094 raise TypeError('{arg!r} parameter lacking default value'. \
2095 format(arg=param_name)) from None
2096
2097 else:
2098 arguments[param_name] = arg_val
2099
2100 if kwargs:
2101 if kwargs_param is not None:
2102 # Process our '**kwargs'-like parameter
2103 arguments[kwargs_param.name] = kwargs
2104 else:
2105 raise TypeError('too many keyword arguments')
2106
2107 return self._bound_arguments_cls(self, arguments)
2108
Antoine Pitroubd41d1b2013-01-29 21:20:57 +01002109 def bind(__bind_self, *args, **kwargs):
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002110 '''Get a BoundArguments object, that maps the passed `args`
2111 and `kwargs` to the function's signature. Raises `TypeError`
2112 if the passed arguments can not be bound.
2113 '''
Antoine Pitroubd41d1b2013-01-29 21:20:57 +01002114 return __bind_self._bind(args, kwargs)
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002115
Antoine Pitroubd41d1b2013-01-29 21:20:57 +01002116 def bind_partial(__bind_self, *args, **kwargs):
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002117 '''Get a BoundArguments object, that partially maps the
2118 passed `args` and `kwargs` to the function's signature.
2119 Raises `TypeError` if the passed arguments can not be bound.
2120 '''
Antoine Pitroubd41d1b2013-01-29 21:20:57 +01002121 return __bind_self._bind(args, kwargs, partial=True)
Larry Hastings7c7cbfc2012-06-22 15:19:35 -07002122
2123 def __str__(self):
2124 result = []
2125 render_kw_only_separator = True
2126 for idx, param in enumerate(self.parameters.values()):
2127 formatted = str(param)
2128
2129 kind = param.kind
2130 if kind == _VAR_POSITIONAL:
2131 # OK, we have an '*args'-like parameter, so we won't need
2132 # a '*' to separate keyword-only arguments
2133 render_kw_only_separator = False
2134 elif kind == _KEYWORD_ONLY and render_kw_only_separator:
2135 # We have a keyword-only parameter to render and we haven't
2136 # rendered an '*args'-like parameter before, so add a '*'
2137 # separator to the parameters list ("foo(arg1, *, arg2)" case)
2138 result.append('*')
2139 # This condition should be only triggered once, so
2140 # reset the flag
2141 render_kw_only_separator = False
2142
2143 result.append(formatted)
2144
2145 rendered = '({})'.format(', '.join(result))
2146
2147 if self.return_annotation is not _empty:
2148 anno = formatannotation(self.return_annotation)
2149 rendered += ' -> {}'.format(anno)
2150
2151 return rendered
Nick Coghlanf94a16b2013-09-22 22:46:49 +10002152
2153def _main():
2154 """ Logic for inspecting an object given at command line """
2155 import argparse
2156 import importlib
2157
2158 parser = argparse.ArgumentParser()
2159 parser.add_argument(
2160 'object',
2161 help="The object to be analysed. "
2162 "It supports the 'module:qualname' syntax")
2163 parser.add_argument(
2164 '-d', '--details', action='store_true',
2165 help='Display info about the module rather than its source code')
2166
2167 args = parser.parse_args()
2168
2169 target = args.object
2170 mod_name, has_attrs, attrs = target.partition(":")
2171 try:
2172 obj = module = importlib.import_module(mod_name)
2173 except Exception as exc:
2174 msg = "Failed to import {} ({}: {})".format(mod_name,
2175 type(exc).__name__,
2176 exc)
2177 print(msg, file=sys.stderr)
2178 exit(2)
2179
2180 if has_attrs:
2181 parts = attrs.split(".")
2182 obj = module
2183 for part in parts:
2184 obj = getattr(obj, part)
2185
2186 if module.__name__ in sys.builtin_module_names:
2187 print("Can't get info for builtin modules.", file=sys.stderr)
2188 exit(1)
2189
2190 if args.details:
2191 print('Target: {}'.format(target))
2192 print('Origin: {}'.format(getsourcefile(module)))
2193 print('Cached: {}'.format(module.__cached__))
2194 if obj is module:
2195 print('Loader: {}'.format(repr(module.__loader__)))
2196 if hasattr(module, '__path__'):
2197 print('Submodule search path: {}'.format(module.__path__))
2198 else:
2199 try:
2200 __, lineno = findsource(obj)
2201 except Exception:
2202 pass
2203 else:
2204 print('Line: {}'.format(lineno))
2205
2206 print('\n')
2207 else:
2208 print(getsource(obj))
2209
2210
2211if __name__ == "__main__":
2212 _main()