2002-08-04 14:22:59 -03:00
|
|
|
# -*- coding: iso-8859-1 -*-
|
2001-02-27 10:43:21 -04:00
|
|
|
"""Get useful information from live Python objects.
|
|
|
|
|
|
|
|
This module encapsulates the interface provided by the internal special
|
|
|
|
attributes (func_*, co_*, im_*, tb_*, etc.) in a friendlier fashion.
|
|
|
|
It also provides some help for examining source code and class layout.
|
|
|
|
|
|
|
|
Here are some of the useful functions provided by this module:
|
|
|
|
|
2008-02-17 23:43:43 -04:00
|
|
|
ismodule(), isclass(), ismethod(), isfunction(), isgeneratorfunction(),
|
|
|
|
isgenerator(), istraceback(), isframe(), iscode(), isbuiltin(),
|
|
|
|
isroutine() - check object types
|
2001-02-27 10:43:21 -04:00
|
|
|
getmembers() - get members of an object that satisfy a given condition
|
|
|
|
|
|
|
|
getfile(), getsourcefile(), getsource() - find an object's source code
|
|
|
|
getdoc(), getcomments() - get documentation on an object
|
|
|
|
getmodule() - determine the module that an object came from
|
|
|
|
getclasstree() - arrange classes so as to represent their hierarchy
|
|
|
|
|
|
|
|
getargspec(), getargvalues() - get info about function arguments
|
|
|
|
formatargspec(), formatargvalues() - format an argument spec
|
|
|
|
getouterframes(), getinnerframes() - get info about frames
|
|
|
|
currentframe() - get the current stack frame
|
|
|
|
stack(), trace() - get info about frames on the stack or in a traceback
|
|
|
|
"""
|
|
|
|
|
|
|
|
# This module is in the public domain. No warranties.
|
|
|
|
|
2001-03-01 09:56:16 -04:00
|
|
|
__author__ = 'Ka-Ping Yee <ping@lfw.org>'
|
|
|
|
__date__ = '1 Jan 2001'
|
2001-02-27 10:43:21 -04:00
|
|
|
|
2008-02-17 23:43:43 -04:00
|
|
|
import sys
|
|
|
|
import os
|
|
|
|
import types
|
|
|
|
import string
|
|
|
|
import re
|
|
|
|
import dis
|
|
|
|
import imp
|
|
|
|
import tokenize
|
|
|
|
import linecache
|
2005-03-11 02:46:45 -04:00
|
|
|
from operator import attrgetter
|
2008-01-10 23:04:50 -04:00
|
|
|
from collections import namedtuple
|
2001-02-27 10:43:21 -04:00
|
|
|
|
2008-07-31 22:40:24 -03:00
|
|
|
# These constants are from Include/code.h.
|
|
|
|
CO_OPTIMIZED, CO_NEWLOCALS, CO_VARARGS, CO_VARKEYWORDS = 0x1, 0x2, 0x4, 0x8
|
|
|
|
CO_NESTED, CO_GENERATOR, CO_NOFREE = 0x10, 0x20, 0x40
|
2008-03-03 14:28:04 -04:00
|
|
|
# See Include/object.h
|
|
|
|
TPFLAGS_IS_ABSTRACT = 1 << 20
|
|
|
|
|
2001-02-27 10:43:21 -04:00
|
|
|
# ----------------------------------------------------------- type-checking
|
|
|
|
def ismodule(object):
|
|
|
|
"""Return true if the object is a module.
|
|
|
|
|
|
|
|
Module objects provide these attributes:
|
|
|
|
__doc__ documentation string
|
|
|
|
__file__ filename (missing for built-in modules)"""
|
2001-09-16 05:40:16 -03:00
|
|
|
return isinstance(object, types.ModuleType)
|
2001-02-27 10:43:21 -04:00
|
|
|
|
|
|
|
def isclass(object):
|
|
|
|
"""Return true if the object is a class.
|
|
|
|
|
|
|
|
Class objects provide these attributes:
|
|
|
|
__doc__ documentation string
|
|
|
|
__module__ name of module in which this class was defined"""
|
2001-09-16 05:40:16 -03:00
|
|
|
return isinstance(object, types.ClassType) or hasattr(object, '__bases__')
|
2001-02-27 10:43:21 -04:00
|
|
|
|
|
|
|
def ismethod(object):
|
|
|
|
"""Return true if the object is an instance method.
|
|
|
|
|
|
|
|
Instance method objects provide these attributes:
|
|
|
|
__doc__ documentation string
|
|
|
|
__name__ name with which this method was defined
|
|
|
|
im_class class object in which this method belongs
|
|
|
|
im_func function object containing implementation of method
|
|
|
|
im_self instance to which this method is bound, or None"""
|
2001-09-16 05:40:16 -03:00
|
|
|
return isinstance(object, types.MethodType)
|
2001-02-27 10:43:21 -04:00
|
|
|
|
2001-09-20 02:13:38 -03:00
|
|
|
def ismethoddescriptor(object):
|
2001-09-20 02:47:55 -03:00
|
|
|
"""Return true if the object is a method descriptor.
|
|
|
|
|
|
|
|
But not if ismethod() or isclass() or isfunction() are true.
|
2001-09-20 02:13:38 -03:00
|
|
|
|
|
|
|
This is new in Python 2.2, and, for example, is true of int.__add__.
|
|
|
|
An object passing this test has a __get__ attribute but not a __set__
|
|
|
|
attribute, but beyond that the set of attributes varies. __name__ is
|
|
|
|
usually sensible, and __doc__ often is.
|
|
|
|
|
2001-09-20 02:47:55 -03:00
|
|
|
Methods implemented via descriptors that also pass one of the other
|
|
|
|
tests return false from the ismethoddescriptor() test, simply because
|
|
|
|
the other tests promise more -- you can, e.g., count on having the
|
|
|
|
im_func attribute (etc) when an object passes ismethod()."""
|
2001-09-20 02:13:38 -03:00
|
|
|
return (hasattr(object, "__get__")
|
|
|
|
and not hasattr(object, "__set__") # else it's a data descriptor
|
|
|
|
and not ismethod(object) # mutual exclusion
|
2001-09-20 02:47:55 -03:00
|
|
|
and not isfunction(object)
|
2001-09-20 02:13:38 -03:00
|
|
|
and not isclass(object))
|
|
|
|
|
2003-05-03 06:09:02 -03:00
|
|
|
def isdatadescriptor(object):
|
|
|
|
"""Return true if the object is a data descriptor.
|
|
|
|
|
|
|
|
Data descriptors have both a __get__ and a __set__ attribute. Examples are
|
|
|
|
properties (defined in Python) and getsets and members (defined in C).
|
|
|
|
Typically, data descriptors will also have __name__ and __doc__ attributes
|
|
|
|
(properties, getsets, and members have both of these attributes), but this
|
|
|
|
is not guaranteed."""
|
|
|
|
return (hasattr(object, "__set__") and hasattr(object, "__get__"))
|
|
|
|
|
2006-07-27 20:43:15 -03:00
|
|
|
if hasattr(types, 'MemberDescriptorType'):
|
|
|
|
# CPython and equivalent
|
|
|
|
def ismemberdescriptor(object):
|
|
|
|
"""Return true if the object is a member descriptor.
|
|
|
|
|
|
|
|
Member descriptors are specialized descriptors defined in extension
|
|
|
|
modules."""
|
|
|
|
return isinstance(object, types.MemberDescriptorType)
|
|
|
|
else:
|
|
|
|
# Other implementations
|
|
|
|
def ismemberdescriptor(object):
|
|
|
|
"""Return true if the object is a member descriptor.
|
|
|
|
|
|
|
|
Member descriptors are specialized descriptors defined in extension
|
|
|
|
modules."""
|
|
|
|
return False
|
|
|
|
|
|
|
|
if hasattr(types, 'GetSetDescriptorType'):
|
|
|
|
# CPython and equivalent
|
|
|
|
def isgetsetdescriptor(object):
|
|
|
|
"""Return true if the object is a getset descriptor.
|
|
|
|
|
|
|
|
getset descriptors are specialized descriptors defined in extension
|
|
|
|
modules."""
|
|
|
|
return isinstance(object, types.GetSetDescriptorType)
|
|
|
|
else:
|
|
|
|
# Other implementations
|
|
|
|
def isgetsetdescriptor(object):
|
|
|
|
"""Return true if the object is a getset descriptor.
|
|
|
|
|
|
|
|
getset descriptors are specialized descriptors defined in extension
|
|
|
|
modules."""
|
|
|
|
return False
|
2006-07-27 20:45:48 -03:00
|
|
|
|
2001-02-27 10:43:21 -04:00
|
|
|
def isfunction(object):
|
|
|
|
"""Return true if the object is a user-defined function.
|
|
|
|
|
|
|
|
Function objects provide these attributes:
|
|
|
|
__doc__ documentation string
|
|
|
|
__name__ name with which this function was defined
|
|
|
|
func_code code object containing compiled function bytecode
|
|
|
|
func_defaults tuple of any default values for arguments
|
|
|
|
func_doc (same as __doc__)
|
|
|
|
func_globals global namespace in which this function was defined
|
|
|
|
func_name (same as __name__)"""
|
2001-09-16 05:40:16 -03:00
|
|
|
return isinstance(object, types.FunctionType)
|
2001-02-27 10:43:21 -04:00
|
|
|
|
2008-02-17 23:43:43 -04:00
|
|
|
def isgeneratorfunction(object):
|
|
|
|
"""Return true if the object is a user-defined generator function.
|
|
|
|
|
|
|
|
Generator function objects provides same attributes as functions.
|
|
|
|
|
|
|
|
See isfunction.__doc__ for attributes listing."""
|
Merged revisions 67952-67953,67955,67957-67958,67960-67961,67963,67965,67967,67970-67971,67973,67982,67988,67990,67995,68014,68016,68030,68057,68061,68112,68115-68118,68120-68121,68123-68128 via svnmerge from
svn+ssh://pythondev@svn.python.org/python/trunk
........
r67952 | georg.brandl | 2008-12-27 18:42:40 +0100 (Sat, 27 Dec 2008) | 2 lines
#4752: actually use custom handler in example.
........
r67953 | georg.brandl | 2008-12-27 19:20:04 +0100 (Sat, 27 Dec 2008) | 3 lines
Patch #4739 by David Laban: add symbols to pydoc help topics,
so that ``help('@')`` works as expected.
........
r67955 | georg.brandl | 2008-12-27 19:27:53 +0100 (Sat, 27 Dec 2008) | 3 lines
Follow-up to r67746 in order to restore backwards-compatibility for
those who (monkey-)patch TextWrapper.wordsep_re with a custom RE.
........
r67957 | georg.brandl | 2008-12-27 19:49:19 +0100 (Sat, 27 Dec 2008) | 2 lines
#4754: improve winsound documentation.
........
r67958 | georg.brandl | 2008-12-27 20:02:59 +0100 (Sat, 27 Dec 2008) | 2 lines
#4682: 'b' is actually unsigned char.
........
r67960 | georg.brandl | 2008-12-27 20:04:44 +0100 (Sat, 27 Dec 2008) | 2 lines
#4695: fix backslashery.
........
r67961 | georg.brandl | 2008-12-27 20:06:04 +0100 (Sat, 27 Dec 2008) | 2 lines
Use :samp: role.
........
r67963 | georg.brandl | 2008-12-27 20:11:15 +0100 (Sat, 27 Dec 2008) | 2 lines
#4671: document that pydoc imports modules.
........
r67965 | antoine.pitrou | 2008-12-27 21:34:52 +0100 (Sat, 27 Dec 2008) | 3 lines
Issue #4677: add two list comprehension tests to pybench.
........
r67967 | benjamin.peterson | 2008-12-27 23:18:58 +0100 (Sat, 27 Dec 2008) | 1 line
fix markup
........
r67970 | alexandre.vassalotti | 2008-12-28 02:52:58 +0100 (Sun, 28 Dec 2008) | 2 lines
Fix name mangling of PyUnicode_ClearFreeList.
........
r67971 | alexandre.vassalotti | 2008-12-28 03:10:35 +0100 (Sun, 28 Dec 2008) | 2 lines
Sort UCS-2/UCS-4 name mangling list.
........
r67973 | alexandre.vassalotti | 2008-12-28 03:58:22 +0100 (Sun, 28 Dec 2008) | 2 lines
Document Py_VaBuildValue.
........
r67982 | benjamin.peterson | 2008-12-28 16:37:31 +0100 (Sun, 28 Dec 2008) | 1 line
fix WORD_BIGEDIAN declaration in Universal builds; fixes #4060 and #4728
........
r67988 | ronald.oussoren | 2008-12-28 20:40:56 +0100 (Sun, 28 Dec 2008) | 1 line
Issue4064: architecture string for universal builds on OSX
........
r67990 | ronald.oussoren | 2008-12-28 20:50:40 +0100 (Sun, 28 Dec 2008) | 3 lines
Update the fix for issue4064 to deal correctly with all three variants of
universal builds that are presented by the configure script.
........
r67995 | benjamin.peterson | 2008-12-28 22:16:07 +0100 (Sun, 28 Dec 2008) | 1 line
#4763 PyErr_ExceptionMatches won't blow up with NULL arguments
........
r68014 | benjamin.peterson | 2008-12-29 18:47:42 +0100 (Mon, 29 Dec 2008) | 1 line
#4764 set IOError.filename when trying to open a directory on POSIX platforms
........
r68016 | benjamin.peterson | 2008-12-29 18:56:58 +0100 (Mon, 29 Dec 2008) | 1 line
#4764 in io.open, set IOError.filename when trying to open a directory on POSIX platforms
........
r68030 | benjamin.peterson | 2008-12-29 22:38:14 +0100 (Mon, 29 Dec 2008) | 1 line
fix French
........
r68057 | vinay.sajip | 2008-12-30 08:01:25 +0100 (Tue, 30 Dec 2008) | 1 line
Minor documentation change relating to NullHandler.
........
r68061 | georg.brandl | 2008-12-30 11:15:49 +0100 (Tue, 30 Dec 2008) | 2 lines
#4778: attributes can't be called.
........
r68112 | benjamin.peterson | 2009-01-01 00:48:39 +0100 (Thu, 01 Jan 2009) | 1 line
#4795 inspect.isgeneratorfunction() should return False instead of None
........
r68115 | benjamin.peterson | 2009-01-01 05:04:41 +0100 (Thu, 01 Jan 2009) | 1 line
simplfy code
........
r68116 | georg.brandl | 2009-01-01 12:46:51 +0100 (Thu, 01 Jan 2009) | 2 lines
#4100: note that element children are not necessarily present on "start" events.
........
r68117 | georg.brandl | 2009-01-01 12:53:55 +0100 (Thu, 01 Jan 2009) | 2 lines
#4156: make clear that "protocol" is to be replaced with the protocol name.
........
r68118 | georg.brandl | 2009-01-01 13:00:19 +0100 (Thu, 01 Jan 2009) | 2 lines
#4185: clarify escape behavior of replacement strings.
........
r68120 | georg.brandl | 2009-01-01 13:15:31 +0100 (Thu, 01 Jan 2009) | 4 lines
#4228: Pack negative values the same way as 2.4
in struct's L format.
........
r68121 | georg.brandl | 2009-01-01 13:43:33 +0100 (Thu, 01 Jan 2009) | 2 lines
Point to types module in new module deprecation notice.
........
r68123 | georg.brandl | 2009-01-01 13:52:29 +0100 (Thu, 01 Jan 2009) | 2 lines
#4784: ... on three counts ...
........
r68124 | georg.brandl | 2009-01-01 13:53:19 +0100 (Thu, 01 Jan 2009) | 2 lines
#4782: Fix markup error that hid load() and loads().
........
r68125 | georg.brandl | 2009-01-01 14:02:09 +0100 (Thu, 01 Jan 2009) | 2 lines
#4776: add data_files and package_dir arguments.
........
r68126 | georg.brandl | 2009-01-01 14:05:13 +0100 (Thu, 01 Jan 2009) | 2 lines
Handlers are in the `logging.handlers` module.
........
r68127 | georg.brandl | 2009-01-01 14:14:49 +0100 (Thu, 01 Jan 2009) | 2 lines
#4767: Use correct submodules for all MIME classes.
........
r68128 | antoine.pitrou | 2009-01-01 15:11:22 +0100 (Thu, 01 Jan 2009) | 3 lines
Issue #3680: Reference cycles created through a dict, set or deque iterator did not get collected.
........
2009-01-01 11:46:10 -04:00
|
|
|
return bool((isfunction(object) or ismethod(object)) and
|
|
|
|
object.func_code.co_flags & CO_GENERATOR)
|
2008-02-17 23:43:43 -04:00
|
|
|
|
|
|
|
def isgenerator(object):
|
|
|
|
"""Return true if the object is a generator.
|
|
|
|
|
|
|
|
Generator objects provide these attributes:
|
|
|
|
__iter__ defined to support interation over container
|
|
|
|
close raises a new GeneratorExit exception inside the
|
|
|
|
generator to terminate the iteration
|
|
|
|
gi_code code object
|
|
|
|
gi_frame frame object or possibly None once the generator has
|
|
|
|
been exhausted
|
|
|
|
gi_running set to 1 when generator is executing, 0 otherwise
|
|
|
|
next return the next item from the container
|
|
|
|
send resumes the generator and "sends" a value that becomes
|
|
|
|
the result of the current yield-expression
|
|
|
|
throw used to raise an exception inside the generator"""
|
|
|
|
return isinstance(object, types.GeneratorType)
|
|
|
|
|
2001-02-27 10:43:21 -04:00
|
|
|
def istraceback(object):
|
|
|
|
"""Return true if the object is a traceback.
|
|
|
|
|
|
|
|
Traceback objects provide these attributes:
|
|
|
|
tb_frame frame object at this level
|
|
|
|
tb_lasti index of last attempted instruction in bytecode
|
|
|
|
tb_lineno current line number in Python source code
|
|
|
|
tb_next next inner traceback object (called by this level)"""
|
2001-09-16 05:40:16 -03:00
|
|
|
return isinstance(object, types.TracebackType)
|
2001-02-27 10:43:21 -04:00
|
|
|
|
|
|
|
def isframe(object):
|
|
|
|
"""Return true if the object is a frame object.
|
|
|
|
|
|
|
|
Frame objects provide these attributes:
|
|
|
|
f_back next outer frame object (this frame's caller)
|
|
|
|
f_builtins built-in namespace seen by this frame
|
|
|
|
f_code code object being executed in this frame
|
|
|
|
f_exc_traceback traceback if raised in this frame, or None
|
|
|
|
f_exc_type exception type if raised in this frame, or None
|
|
|
|
f_exc_value exception value if raised in this frame, or None
|
|
|
|
f_globals global namespace seen by this frame
|
|
|
|
f_lasti index of last attempted instruction in bytecode
|
|
|
|
f_lineno current line number in Python source code
|
|
|
|
f_locals local namespace seen by this frame
|
|
|
|
f_restricted 0 or 1 if frame is in restricted execution mode
|
|
|
|
f_trace tracing function for this frame, or None"""
|
2001-09-16 05:40:16 -03:00
|
|
|
return isinstance(object, types.FrameType)
|
2001-02-27 10:43:21 -04:00
|
|
|
|
|
|
|
def iscode(object):
|
|
|
|
"""Return true if the object is a code object.
|
|
|
|
|
|
|
|
Code objects provide these attributes:
|
|
|
|
co_argcount number of arguments (not including * or ** args)
|
|
|
|
co_code string of raw compiled bytecode
|
|
|
|
co_consts tuple of constants used in the bytecode
|
|
|
|
co_filename name of file in which this code object was created
|
|
|
|
co_firstlineno number of first line in Python source code
|
|
|
|
co_flags bitmap: 1=optimized | 2=newlocals | 4=*arg | 8=**arg
|
|
|
|
co_lnotab encoded mapping of line numbers to bytecode indices
|
|
|
|
co_name name with which this code object was defined
|
|
|
|
co_names tuple of names of local variables
|
|
|
|
co_nlocals number of local variables
|
|
|
|
co_stacksize virtual machine stack space required
|
|
|
|
co_varnames tuple of names of arguments and local variables"""
|
2001-09-16 05:40:16 -03:00
|
|
|
return isinstance(object, types.CodeType)
|
2001-02-27 10:43:21 -04:00
|
|
|
|
|
|
|
def isbuiltin(object):
|
|
|
|
"""Return true if the object is a built-in function or method.
|
|
|
|
|
|
|
|
Built-in functions and methods provide these attributes:
|
|
|
|
__doc__ documentation string
|
|
|
|
__name__ original name of this function or method
|
|
|
|
__self__ instance to which a method is bound, or None"""
|
2001-09-16 05:40:16 -03:00
|
|
|
return isinstance(object, types.BuiltinFunctionType)
|
2001-02-27 10:43:21 -04:00
|
|
|
|
|
|
|
def isroutine(object):
|
|
|
|
"""Return true if the object is any kind of function or method."""
|
2001-09-20 02:13:38 -03:00
|
|
|
return (isbuiltin(object)
|
|
|
|
or isfunction(object)
|
|
|
|
or ismethod(object)
|
|
|
|
or ismethoddescriptor(object))
|
2001-02-27 10:43:21 -04:00
|
|
|
|
2008-02-17 23:43:43 -04:00
|
|
|
def isgenerator(object):
|
|
|
|
"""Return true if the object is a generator object."""
|
|
|
|
return isinstance(object, types.GeneratorType)
|
|
|
|
|
2008-03-03 14:28:04 -04:00
|
|
|
def isabstract(object):
|
|
|
|
"""Return true if the object is an abstract base class (ABC)."""
|
2008-04-08 18:51:57 -03:00
|
|
|
return isinstance(object, type) and object.__flags__ & TPFLAGS_IS_ABSTRACT
|
2008-03-03 14:28:04 -04:00
|
|
|
|
2001-02-27 10:43:21 -04:00
|
|
|
def getmembers(object, predicate=None):
|
|
|
|
"""Return all members of an object as (name, value) pairs sorted by name.
|
|
|
|
Optionally, only return members that satisfy a given predicate."""
|
|
|
|
results = []
|
|
|
|
for key in dir(object):
|
|
|
|
value = getattr(object, key)
|
|
|
|
if not predicate or predicate(value):
|
|
|
|
results.append((key, value))
|
|
|
|
results.sort()
|
|
|
|
return results
|
|
|
|
|
2008-01-10 23:04:50 -04:00
|
|
|
Attribute = namedtuple('Attribute', 'name kind defining_class object')
|
|
|
|
|
New function classify_class_attrs(). As a number of SF bug reports
point out, pydoc doesn't tell you where class attributes were defined,
gets several new 2.2 features wrong, and isn't aware of some new features
checked in on Thursday <wink>. pydoc is hampered in part because
inspect.py has the same limitations. Alas, I can't think of a way to
fix this within the current architecture of inspect/pydoc: it's simply
not possible in 2.2 to figure out everything needed just from examining
the object you get back from class.attr. You also need the class
context, and the method resolution order, and tests against various things
that simply didn't exist before. OTOH, knowledge of how to do that is
getting quite complex, so doesn't belong in pydoc.
classify_class_attrs takes a different approach, analyzing all
the class attrs "at once", and returning the most interesting stuff for
each, all in one gulp. pydoc needs to be reworked to use this for
classes (instead of the current "filter dir(class) umpteen times against
assorted predicates" approach).
2001-09-22 23:00:29 -03:00
|
|
|
def classify_class_attrs(cls):
|
|
|
|
"""Return list of attribute-descriptor tuples.
|
|
|
|
|
|
|
|
For each name in dir(cls), the return list contains a 4-tuple
|
|
|
|
with these elements:
|
|
|
|
|
|
|
|
0. The name (a string).
|
|
|
|
|
|
|
|
1. The kind of attribute this is, one of these strings:
|
|
|
|
'class method' created via classmethod()
|
|
|
|
'static method' created via staticmethod()
|
|
|
|
'property' created via property()
|
|
|
|
'method' any other flavor of method
|
|
|
|
'data' not a method
|
|
|
|
|
|
|
|
2. The class which defined this attribute (a class).
|
|
|
|
|
|
|
|
3. The object as obtained directly from the defining class's
|
|
|
|
__dict__, not via getattr. This is especially important for
|
|
|
|
data attributes: C.data is just a data object, but
|
|
|
|
C.__dict__['data'] may be a data descriptor with additional
|
|
|
|
info, like a __doc__ string.
|
|
|
|
"""
|
|
|
|
|
|
|
|
mro = getmro(cls)
|
|
|
|
names = dir(cls)
|
|
|
|
result = []
|
|
|
|
for name in names:
|
|
|
|
# Get the object associated with the name.
|
|
|
|
# Getting an obj from the __dict__ sometimes reveals more than
|
|
|
|
# using getattr. Static and class methods are dramatic examples.
|
|
|
|
if name in cls.__dict__:
|
|
|
|
obj = cls.__dict__[name]
|
|
|
|
else:
|
|
|
|
obj = getattr(cls, name)
|
|
|
|
|
|
|
|
# Figure out where it was defined.
|
|
|
|
homecls = getattr(obj, "__objclass__", None)
|
|
|
|
if homecls is None:
|
2001-10-15 19:03:32 -03:00
|
|
|
# search the dicts.
|
New function classify_class_attrs(). As a number of SF bug reports
point out, pydoc doesn't tell you where class attributes were defined,
gets several new 2.2 features wrong, and isn't aware of some new features
checked in on Thursday <wink>. pydoc is hampered in part because
inspect.py has the same limitations. Alas, I can't think of a way to
fix this within the current architecture of inspect/pydoc: it's simply
not possible in 2.2 to figure out everything needed just from examining
the object you get back from class.attr. You also need the class
context, and the method resolution order, and tests against various things
that simply didn't exist before. OTOH, knowledge of how to do that is
getting quite complex, so doesn't belong in pydoc.
classify_class_attrs takes a different approach, analyzing all
the class attrs "at once", and returning the most interesting stuff for
each, all in one gulp. pydoc needs to be reworked to use this for
classes (instead of the current "filter dir(class) umpteen times against
assorted predicates" approach).
2001-09-22 23:00:29 -03:00
|
|
|
for base in mro:
|
|
|
|
if name in base.__dict__:
|
|
|
|
homecls = base
|
|
|
|
break
|
|
|
|
|
|
|
|
# Get the object again, in order to get it from the defining
|
|
|
|
# __dict__ instead of via getattr (if possible).
|
|
|
|
if homecls is not None and name in homecls.__dict__:
|
|
|
|
obj = homecls.__dict__[name]
|
|
|
|
|
|
|
|
# Also get the object via getattr.
|
|
|
|
obj_via_getattr = getattr(cls, name)
|
|
|
|
|
|
|
|
# Classify the object.
|
|
|
|
if isinstance(obj, staticmethod):
|
|
|
|
kind = "static method"
|
|
|
|
elif isinstance(obj, classmethod):
|
|
|
|
kind = "class method"
|
|
|
|
elif isinstance(obj, property):
|
|
|
|
kind = "property"
|
|
|
|
elif (ismethod(obj_via_getattr) or
|
|
|
|
ismethoddescriptor(obj_via_getattr)):
|
|
|
|
kind = "method"
|
|
|
|
else:
|
|
|
|
kind = "data"
|
|
|
|
|
2008-01-10 23:04:50 -04:00
|
|
|
result.append(Attribute(name, kind, homecls, obj))
|
New function classify_class_attrs(). As a number of SF bug reports
point out, pydoc doesn't tell you where class attributes were defined,
gets several new 2.2 features wrong, and isn't aware of some new features
checked in on Thursday <wink>. pydoc is hampered in part because
inspect.py has the same limitations. Alas, I can't think of a way to
fix this within the current architecture of inspect/pydoc: it's simply
not possible in 2.2 to figure out everything needed just from examining
the object you get back from class.attr. You also need the class
context, and the method resolution order, and tests against various things
that simply didn't exist before. OTOH, knowledge of how to do that is
getting quite complex, so doesn't belong in pydoc.
classify_class_attrs takes a different approach, analyzing all
the class attrs "at once", and returning the most interesting stuff for
each, all in one gulp. pydoc needs to be reworked to use this for
classes (instead of the current "filter dir(class) umpteen times against
assorted predicates" approach).
2001-09-22 23:00:29 -03:00
|
|
|
|
|
|
|
return result
|
|
|
|
|
2001-09-22 03:10:55 -03:00
|
|
|
# ----------------------------------------------------------- class helpers
|
|
|
|
def _searchbases(cls, accum):
|
|
|
|
# Simulate the "classic class" search order.
|
|
|
|
if cls in accum:
|
|
|
|
return
|
|
|
|
accum.append(cls)
|
|
|
|
for base in cls.__bases__:
|
|
|
|
_searchbases(base, accum)
|
|
|
|
|
|
|
|
def getmro(cls):
|
|
|
|
"Return tuple of base classes (including cls) in method resolution order."
|
|
|
|
if hasattr(cls, "__mro__"):
|
|
|
|
return cls.__mro__
|
|
|
|
else:
|
|
|
|
result = []
|
|
|
|
_searchbases(cls, result)
|
|
|
|
return tuple(result)
|
|
|
|
|
2001-02-27 10:43:21 -04:00
|
|
|
# -------------------------------------------------- source code extraction
|
|
|
|
def indentsize(line):
|
|
|
|
"""Return the indent size, in spaces, at the start of a line of text."""
|
|
|
|
expline = string.expandtabs(line)
|
|
|
|
return len(expline) - len(string.lstrip(expline))
|
|
|
|
|
|
|
|
def getdoc(object):
|
|
|
|
"""Get the documentation string for an object.
|
|
|
|
|
|
|
|
All tabs are expanded to spaces. To clean up docstrings that are
|
|
|
|
indented to line up with blocks of code, any whitespace than can be
|
|
|
|
uniformly removed from the second line onwards is removed."""
|
2002-03-17 14:56:20 -04:00
|
|
|
try:
|
|
|
|
doc = object.__doc__
|
|
|
|
except AttributeError:
|
|
|
|
return None
|
2002-05-20 14:29:46 -03:00
|
|
|
if not isinstance(doc, types.StringTypes):
|
2002-03-17 14:56:20 -04:00
|
|
|
return None
|
2008-06-07 12:59:10 -03:00
|
|
|
return cleandoc(doc)
|
|
|
|
|
|
|
|
def cleandoc(doc):
|
|
|
|
"""Clean up indentation from docstrings.
|
|
|
|
|
|
|
|
Any whitespace that can be uniformly removed from the second line
|
|
|
|
onwards is removed."""
|
2002-03-17 14:56:20 -04:00
|
|
|
try:
|
|
|
|
lines = string.split(string.expandtabs(doc), '\n')
|
|
|
|
except UnicodeError:
|
|
|
|
return None
|
|
|
|
else:
|
2002-11-29 23:53:15 -04:00
|
|
|
# Find minimum indentation of any non-blank lines after first line.
|
|
|
|
margin = sys.maxint
|
2001-02-27 10:43:21 -04:00
|
|
|
for line in lines[1:]:
|
|
|
|
content = len(string.lstrip(line))
|
2002-11-29 23:53:15 -04:00
|
|
|
if content:
|
|
|
|
indent = len(line) - content
|
|
|
|
margin = min(margin, indent)
|
|
|
|
# Remove indentation.
|
|
|
|
if lines:
|
|
|
|
lines[0] = lines[0].lstrip()
|
|
|
|
if margin < sys.maxint:
|
2001-02-27 10:43:21 -04:00
|
|
|
for i in range(1, len(lines)): lines[i] = lines[i][margin:]
|
2002-11-29 23:53:15 -04:00
|
|
|
# Remove any trailing or leading blank lines.
|
|
|
|
while lines and not lines[-1]:
|
|
|
|
lines.pop()
|
|
|
|
while lines and not lines[0]:
|
|
|
|
lines.pop(0)
|
2001-02-27 10:43:21 -04:00
|
|
|
return string.join(lines, '\n')
|
|
|
|
|
|
|
|
def getfile(object):
|
2001-03-01 22:08:53 -04:00
|
|
|
"""Work out which source or compiled file an object was defined in."""
|
2001-02-27 10:43:21 -04:00
|
|
|
if ismodule(object):
|
|
|
|
if hasattr(object, '__file__'):
|
|
|
|
return object.__file__
|
2003-06-27 15:41:20 -03:00
|
|
|
raise TypeError('arg is a built-in module')
|
2001-02-27 10:43:21 -04:00
|
|
|
if isclass(object):
|
2001-04-13 09:10:40 -03:00
|
|
|
object = sys.modules.get(object.__module__)
|
2001-02-27 10:43:21 -04:00
|
|
|
if hasattr(object, '__file__'):
|
|
|
|
return object.__file__
|
2003-06-27 15:41:20 -03:00
|
|
|
raise TypeError('arg is a built-in class')
|
2001-02-27 10:43:21 -04:00
|
|
|
if ismethod(object):
|
|
|
|
object = object.im_func
|
|
|
|
if isfunction(object):
|
|
|
|
object = object.func_code
|
|
|
|
if istraceback(object):
|
|
|
|
object = object.tb_frame
|
|
|
|
if isframe(object):
|
|
|
|
object = object.f_code
|
|
|
|
if iscode(object):
|
|
|
|
return object.co_filename
|
2003-06-29 02:46:54 -03:00
|
|
|
raise TypeError('arg is not a module, class, method, '
|
2003-06-27 15:41:20 -03:00
|
|
|
'function, traceback, frame, or code object')
|
2001-02-27 10:43:21 -04:00
|
|
|
|
2008-01-10 23:04:50 -04:00
|
|
|
ModuleInfo = namedtuple('ModuleInfo', 'name suffix mode module_type')
|
|
|
|
|
2001-04-10 08:43:00 -03:00
|
|
|
def getmoduleinfo(path):
|
|
|
|
"""Get the module name, suffix, mode, and module type for a given file."""
|
|
|
|
filename = os.path.basename(path)
|
2008-07-31 22:40:24 -03:00
|
|
|
suffixes = map(lambda info:
|
|
|
|
(-len(info[0]), info[0], info[1], info[2]),
|
|
|
|
imp.get_suffixes())
|
2001-04-10 08:43:00 -03:00
|
|
|
suffixes.sort() # try longest suffixes first, in case they overlap
|
|
|
|
for neglen, suffix, mode, mtype in suffixes:
|
|
|
|
if filename[neglen:] == suffix:
|
2008-01-10 23:04:50 -04:00
|
|
|
return ModuleInfo(filename[:neglen], suffix, mode, mtype)
|
2001-04-10 08:43:00 -03:00
|
|
|
|
|
|
|
def getmodulename(path):
|
|
|
|
"""Return the module name for a given file, or None."""
|
|
|
|
info = getmoduleinfo(path)
|
|
|
|
if info: return info[0]
|
|
|
|
|
2001-03-01 22:08:53 -04:00
|
|
|
def getsourcefile(object):
|
|
|
|
"""Return the Python source file an object was defined in, if it exists."""
|
|
|
|
filename = getfile(object)
|
2005-02-06 02:57:08 -04:00
|
|
|
if string.lower(filename[-4:]) in ('.pyc', '.pyo'):
|
2001-03-01 22:08:53 -04:00
|
|
|
filename = filename[:-4] + '.py'
|
2001-03-02 01:50:34 -04:00
|
|
|
for suffix, mode, kind in imp.get_suffixes():
|
|
|
|
if 'b' in mode and string.lower(filename[-len(suffix):]) == suffix:
|
|
|
|
# Looks like a binary file. We want to only return a text file.
|
|
|
|
return None
|
2006-04-30 12:59:26 -03:00
|
|
|
if os.path.exists(filename):
|
|
|
|
return filename
|
2006-07-10 16:03:29 -03:00
|
|
|
# only return a non-existent filename if the module has a PEP 302 loader
|
|
|
|
if hasattr(getmodule(object, filename), '__loader__'):
|
2001-03-01 22:08:53 -04:00
|
|
|
return filename
|
|
|
|
|
2006-07-10 16:03:29 -03:00
|
|
|
def getabsfile(object, _filename=None):
|
2001-03-02 01:50:34 -04:00
|
|
|
"""Return an absolute path to the source or compiled file for an object.
|
2001-03-01 22:08:53 -04:00
|
|
|
|
2001-03-02 01:50:34 -04:00
|
|
|
The idea is for each object to have a unique origin, so this routine
|
|
|
|
normalizes the result as much as possible."""
|
2006-07-20 12:54:16 -03:00
|
|
|
if _filename is None:
|
|
|
|
_filename = getsourcefile(object) or getfile(object)
|
|
|
|
return os.path.normcase(os.path.abspath(_filename))
|
2001-03-01 22:08:53 -04:00
|
|
|
|
2001-02-27 10:43:21 -04:00
|
|
|
modulesbyfile = {}
|
2006-09-07 07:50:34 -03:00
|
|
|
_filesbymodname = {}
|
2001-02-27 10:43:21 -04:00
|
|
|
|
2006-07-10 16:03:29 -03:00
|
|
|
def getmodule(object, _filename=None):
|
2001-03-02 01:50:34 -04:00
|
|
|
"""Return the module an object was defined in, or None if not found."""
|
2001-04-13 06:15:08 -03:00
|
|
|
if ismodule(object):
|
|
|
|
return object
|
2004-09-11 12:53:22 -03:00
|
|
|
if hasattr(object, '__module__'):
|
2001-03-01 09:56:16 -04:00
|
|
|
return sys.modules.get(object.__module__)
|
2006-09-07 07:50:34 -03:00
|
|
|
# Try the filename to modulename cache
|
|
|
|
if _filename is not None and _filename in modulesbyfile:
|
|
|
|
return sys.modules.get(modulesbyfile[_filename])
|
|
|
|
# Try the cache again with the absolute file name
|
2001-02-27 10:43:21 -04:00
|
|
|
try:
|
2006-07-10 16:03:29 -03:00
|
|
|
file = getabsfile(object, _filename)
|
2001-02-27 10:43:21 -04:00
|
|
|
except TypeError:
|
|
|
|
return None
|
2002-06-01 11:18:47 -03:00
|
|
|
if file in modulesbyfile:
|
2003-03-28 12:29:50 -04:00
|
|
|
return sys.modules.get(modulesbyfile[file])
|
2006-09-07 07:50:34 -03:00
|
|
|
# Update the filename to module name cache and check yet again
|
|
|
|
# Copy sys.modules in order to cope with changes while iterating
|
|
|
|
for modname, module in sys.modules.items():
|
2006-04-10 22:07:43 -03:00
|
|
|
if ismodule(module) and hasattr(module, '__file__'):
|
2006-09-07 07:50:34 -03:00
|
|
|
f = module.__file__
|
|
|
|
if f == _filesbymodname.get(modname, None):
|
|
|
|
# Have already mapped this module, so skip it
|
|
|
|
continue
|
|
|
|
_filesbymodname[modname] = f
|
2006-07-10 16:03:29 -03:00
|
|
|
f = getabsfile(module)
|
2006-09-07 07:50:34 -03:00
|
|
|
# Always map to the name the module knows itself by
|
2006-07-10 16:03:29 -03:00
|
|
|
modulesbyfile[f] = modulesbyfile[
|
|
|
|
os.path.realpath(f)] = module.__name__
|
2002-06-01 11:18:47 -03:00
|
|
|
if file in modulesbyfile:
|
2003-03-28 12:29:50 -04:00
|
|
|
return sys.modules.get(modulesbyfile[file])
|
2006-09-07 07:50:34 -03:00
|
|
|
# Check the main module
|
2001-02-27 10:43:21 -04:00
|
|
|
main = sys.modules['__main__']
|
2003-06-15 19:33:28 -03:00
|
|
|
if not hasattr(object, '__name__'):
|
|
|
|
return None
|
2001-03-02 01:50:34 -04:00
|
|
|
if hasattr(main, object.__name__):
|
2001-02-27 10:43:21 -04:00
|
|
|
mainobject = getattr(main, object.__name__)
|
2001-03-02 01:50:34 -04:00
|
|
|
if mainobject is object:
|
|
|
|
return main
|
2006-09-07 07:50:34 -03:00
|
|
|
# Check builtins
|
2001-02-27 10:43:21 -04:00
|
|
|
builtin = sys.modules['__builtin__']
|
2001-03-02 01:50:34 -04:00
|
|
|
if hasattr(builtin, object.__name__):
|
2001-02-27 10:43:21 -04:00
|
|
|
builtinobject = getattr(builtin, object.__name__)
|
2001-03-02 01:50:34 -04:00
|
|
|
if builtinobject is object:
|
|
|
|
return builtin
|
2001-02-27 10:43:21 -04:00
|
|
|
|
|
|
|
def findsource(object):
|
|
|
|
"""Return the entire source file and starting line number for an object.
|
|
|
|
|
|
|
|
The argument may be a module, class, method, function, traceback, frame,
|
|
|
|
or code object. The source code is returned as a list of all the lines
|
|
|
|
in the file and the line number indexes a line in that list. An IOError
|
|
|
|
is raised if the source code cannot be retrieved."""
|
2002-03-23 19:51:04 -04:00
|
|
|
file = getsourcefile(object) or getfile(object)
|
2006-09-07 07:50:34 -03:00
|
|
|
module = getmodule(object, file)
|
2006-04-30 14:42:26 -03:00
|
|
|
if module:
|
|
|
|
lines = linecache.getlines(file, module.__dict__)
|
|
|
|
else:
|
|
|
|
lines = linecache.getlines(file)
|
2002-03-23 19:51:04 -04:00
|
|
|
if not lines:
|
2003-06-27 15:41:20 -03:00
|
|
|
raise IOError('could not get source code')
|
2001-02-27 10:43:21 -04:00
|
|
|
|
|
|
|
if ismodule(object):
|
|
|
|
return lines, 0
|
|
|
|
|
|
|
|
if isclass(object):
|
|
|
|
name = object.__name__
|
2006-10-12 06:20:33 -03:00
|
|
|
pat = re.compile(r'^(\s*)class\s*' + name + r'\b')
|
|
|
|
# make some effort to find the best matching class definition:
|
|
|
|
# use the one with the least indentation, which is the one
|
|
|
|
# that's most probably not inside a function definition.
|
|
|
|
candidates = []
|
2001-02-27 10:43:21 -04:00
|
|
|
for i in range(len(lines)):
|
2006-10-12 06:20:33 -03:00
|
|
|
match = pat.match(lines[i])
|
|
|
|
if match:
|
|
|
|
# if it's at toplevel, it's already the best one
|
|
|
|
if lines[i][0] == 'c':
|
|
|
|
return lines, i
|
|
|
|
# else add whitespace to candidate list
|
|
|
|
candidates.append((match.group(1), i))
|
|
|
|
if candidates:
|
|
|
|
# this will sort by whitespace, and by line number,
|
|
|
|
# less whitespace first
|
|
|
|
candidates.sort()
|
|
|
|
return lines, candidates[0][1]
|
2003-06-27 15:41:20 -03:00
|
|
|
else:
|
|
|
|
raise IOError('could not find class definition')
|
2001-02-27 10:43:21 -04:00
|
|
|
|
|
|
|
if ismethod(object):
|
|
|
|
object = object.im_func
|
|
|
|
if isfunction(object):
|
|
|
|
object = object.func_code
|
|
|
|
if istraceback(object):
|
|
|
|
object = object.tb_frame
|
|
|
|
if isframe(object):
|
|
|
|
object = object.f_code
|
|
|
|
if iscode(object):
|
2001-03-02 01:50:34 -04:00
|
|
|
if not hasattr(object, 'co_firstlineno'):
|
2003-06-27 15:41:20 -03:00
|
|
|
raise IOError('could not find function definition')
|
2001-03-02 01:50:34 -04:00
|
|
|
lnum = object.co_firstlineno - 1
|
2004-12-12 12:46:28 -04:00
|
|
|
pat = re.compile(r'^(\s*def\s)|(.*(?<!\w)lambda(:|\s))|^(\s*@)')
|
2001-03-02 01:50:34 -04:00
|
|
|
while lnum > 0:
|
2001-03-10 05:31:55 -04:00
|
|
|
if pat.match(lines[lnum]): break
|
2001-03-02 01:50:34 -04:00
|
|
|
lnum = lnum - 1
|
|
|
|
return lines, lnum
|
2003-06-27 15:41:20 -03:00
|
|
|
raise IOError('could not find code object')
|
2001-02-27 10:43:21 -04:00
|
|
|
|
|
|
|
def getcomments(object):
|
2002-03-28 19:01:56 -04:00
|
|
|
"""Get lines of comments immediately preceding an object's source code.
|
|
|
|
|
|
|
|
Returns None when source can't be found.
|
|
|
|
"""
|
|
|
|
try:
|
|
|
|
lines, lnum = findsource(object)
|
|
|
|
except (IOError, TypeError):
|
|
|
|
return None
|
2001-02-27 10:43:21 -04:00
|
|
|
|
|
|
|
if ismodule(object):
|
|
|
|
# Look for a comment block at the top of the file.
|
|
|
|
start = 0
|
2001-04-12 10:17:17 -03:00
|
|
|
if lines and lines[0][:2] == '#!': start = 1
|
2005-02-06 02:57:08 -04:00
|
|
|
while start < len(lines) and string.strip(lines[start]) in ('', '#'):
|
2001-02-27 10:43:21 -04:00
|
|
|
start = start + 1
|
2001-04-12 10:17:17 -03:00
|
|
|
if start < len(lines) and lines[start][:1] == '#':
|
2001-02-27 10:43:21 -04:00
|
|
|
comments = []
|
|
|
|
end = start
|
|
|
|
while end < len(lines) and lines[end][:1] == '#':
|
|
|
|
comments.append(string.expandtabs(lines[end]))
|
|
|
|
end = end + 1
|
|
|
|
return string.join(comments, '')
|
|
|
|
|
|
|
|
# Look for a preceding block of comments at the same indentation.
|
|
|
|
elif lnum > 0:
|
|
|
|
indent = indentsize(lines[lnum])
|
|
|
|
end = lnum - 1
|
|
|
|
if end >= 0 and string.lstrip(lines[end])[:1] == '#' and \
|
|
|
|
indentsize(lines[end]) == indent:
|
|
|
|
comments = [string.lstrip(string.expandtabs(lines[end]))]
|
|
|
|
if end > 0:
|
|
|
|
end = end - 1
|
|
|
|
comment = string.lstrip(string.expandtabs(lines[end]))
|
|
|
|
while comment[:1] == '#' and indentsize(lines[end]) == indent:
|
|
|
|
comments[:0] = [comment]
|
|
|
|
end = end - 1
|
|
|
|
if end < 0: break
|
|
|
|
comment = string.lstrip(string.expandtabs(lines[end]))
|
|
|
|
while comments and string.strip(comments[0]) == '#':
|
|
|
|
comments[:1] = []
|
|
|
|
while comments and string.strip(comments[-1]) == '#':
|
|
|
|
comments[-1:] = []
|
|
|
|
return string.join(comments, '')
|
|
|
|
|
2001-06-29 20:51:08 -03:00
|
|
|
class EndOfBlock(Exception): pass
|
|
|
|
|
|
|
|
class BlockFinder:
|
|
|
|
"""Provide a tokeneater() method to detect the end of a code block."""
|
|
|
|
def __init__(self):
|
|
|
|
self.indent = 0
|
2005-03-12 12:37:11 -04:00
|
|
|
self.islambda = False
|
2004-12-12 12:46:28 -04:00
|
|
|
self.started = False
|
|
|
|
self.passline = False
|
2005-09-25 08:45:45 -03:00
|
|
|
self.last = 1
|
2001-06-29 20:51:08 -03:00
|
|
|
|
2008-07-31 22:40:24 -03:00
|
|
|
def tokeneater(self, type, token, srow_scol, erow_ecol, line):
|
|
|
|
srow, scol = srow_scol
|
|
|
|
erow, ecol = erow_ecol
|
2001-06-29 20:51:08 -03:00
|
|
|
if not self.started:
|
2005-09-25 08:45:45 -03:00
|
|
|
# look for the first "def", "class" or "lambda"
|
2004-12-12 12:46:28 -04:00
|
|
|
if token in ("def", "class", "lambda"):
|
2005-03-12 12:37:11 -04:00
|
|
|
if token == "lambda":
|
|
|
|
self.islambda = True
|
2004-12-12 12:46:28 -04:00
|
|
|
self.started = True
|
2005-09-25 08:45:45 -03:00
|
|
|
self.passline = True # skip to the end of the line
|
2001-02-27 10:43:21 -04:00
|
|
|
elif type == tokenize.NEWLINE:
|
2005-09-25 08:45:45 -03:00
|
|
|
self.passline = False # stop skipping when a NEWLINE is seen
|
2001-06-29 20:51:08 -03:00
|
|
|
self.last = srow
|
2005-09-25 08:45:45 -03:00
|
|
|
if self.islambda: # lambdas always end at the first NEWLINE
|
|
|
|
raise EndOfBlock
|
2004-12-12 12:46:28 -04:00
|
|
|
elif self.passline:
|
|
|
|
pass
|
2001-02-27 10:43:21 -04:00
|
|
|
elif type == tokenize.INDENT:
|
2001-06-29 20:51:08 -03:00
|
|
|
self.indent = self.indent + 1
|
2004-12-12 12:46:28 -04:00
|
|
|
self.passline = True
|
2001-02-27 10:43:21 -04:00
|
|
|
elif type == tokenize.DEDENT:
|
2001-06-29 20:51:08 -03:00
|
|
|
self.indent = self.indent - 1
|
2005-09-25 08:45:45 -03:00
|
|
|
# the end of matching indent/dedent pairs end a block
|
|
|
|
# (note that this only works for "def"/"class" blocks,
|
|
|
|
# not e.g. for "if: else:" or "try: finally:" blocks)
|
|
|
|
if self.indent <= 0:
|
|
|
|
raise EndOfBlock
|
|
|
|
elif self.indent == 0 and type not in (tokenize.COMMENT, tokenize.NL):
|
|
|
|
# any other token on the same indentation level end the previous
|
|
|
|
# block as well, except the pseudo-tokens COMMENT and NL.
|
|
|
|
raise EndOfBlock
|
2001-06-29 20:51:08 -03:00
|
|
|
|
|
|
|
def getblock(lines):
|
|
|
|
"""Extract the block of code at the top of the given list of lines."""
|
2005-09-25 08:45:45 -03:00
|
|
|
blockfinder = BlockFinder()
|
2001-06-29 20:51:08 -03:00
|
|
|
try:
|
2005-09-25 08:45:45 -03:00
|
|
|
tokenize.tokenize(iter(lines).next, blockfinder.tokeneater)
|
|
|
|
except (EndOfBlock, IndentationError):
|
|
|
|
pass
|
|
|
|
return lines[:blockfinder.last]
|
2001-02-27 10:43:21 -04:00
|
|
|
|
|
|
|
def getsourcelines(object):
|
|
|
|
"""Return a list of source lines and starting line number for an object.
|
|
|
|
|
|
|
|
The argument may be a module, class, method, function, traceback, frame,
|
|
|
|
or code object. The source code is returned as a list of the lines
|
|
|
|
corresponding to the object and the line number indicates where in the
|
|
|
|
original source file the first line of code was found. An IOError is
|
|
|
|
raised if the source code cannot be retrieved."""
|
|
|
|
lines, lnum = findsource(object)
|
|
|
|
|
|
|
|
if ismodule(object): return lines, 0
|
|
|
|
else: return getblock(lines[lnum:]), lnum + 1
|
|
|
|
|
|
|
|
def getsource(object):
|
|
|
|
"""Return the text of the source code for an object.
|
|
|
|
|
|
|
|
The argument may be a module, class, method, function, traceback, frame,
|
|
|
|
or code object. The source code is returned as a single string. An
|
|
|
|
IOError is raised if the source code cannot be retrieved."""
|
|
|
|
lines, lnum = getsourcelines(object)
|
|
|
|
return string.join(lines, '')
|
|
|
|
|
|
|
|
# --------------------------------------------------- class tree extraction
|
|
|
|
def walktree(classes, children, parent):
|
|
|
|
"""Recursive helper function for getclasstree()."""
|
|
|
|
results = []
|
2005-03-11 02:46:45 -04:00
|
|
|
classes.sort(key=attrgetter('__module__', '__name__'))
|
2001-02-27 10:43:21 -04:00
|
|
|
for c in classes:
|
|
|
|
results.append((c, c.__bases__))
|
2002-06-01 11:18:47 -03:00
|
|
|
if c in children:
|
2001-02-27 10:43:21 -04:00
|
|
|
results.append(walktree(children[c], children, c))
|
|
|
|
return results
|
|
|
|
|
|
|
|
def getclasstree(classes, unique=0):
|
|
|
|
"""Arrange the given list of classes into a hierarchy of nested lists.
|
|
|
|
|
|
|
|
Where a nested list appears, it contains classes derived from the class
|
|
|
|
whose entry immediately precedes the list. Each entry is a 2-tuple
|
|
|
|
containing a class and a tuple of its base classes. If the 'unique'
|
|
|
|
argument is true, exactly one entry appears in the returned structure
|
|
|
|
for each class in the given list. Otherwise, classes using multiple
|
|
|
|
inheritance and their descendants will appear multiple times."""
|
|
|
|
children = {}
|
|
|
|
roots = []
|
|
|
|
for c in classes:
|
|
|
|
if c.__bases__:
|
|
|
|
for parent in c.__bases__:
|
2002-06-01 11:18:47 -03:00
|
|
|
if not parent in children:
|
2001-02-27 10:43:21 -04:00
|
|
|
children[parent] = []
|
|
|
|
children[parent].append(c)
|
|
|
|
if unique and parent in classes: break
|
|
|
|
elif c not in roots:
|
|
|
|
roots.append(c)
|
2002-06-02 15:55:56 -03:00
|
|
|
for parent in children:
|
2001-02-27 10:43:21 -04:00
|
|
|
if parent not in classes:
|
|
|
|
roots.append(parent)
|
|
|
|
return walktree(roots, children, None)
|
|
|
|
|
|
|
|
# ------------------------------------------------ argument list extraction
|
2008-01-10 23:04:50 -04:00
|
|
|
Arguments = namedtuple('Arguments', 'args varargs keywords')
|
|
|
|
|
2001-02-27 10:43:21 -04:00
|
|
|
def getargs(co):
|
|
|
|
"""Get information about the arguments accepted by a code object.
|
|
|
|
|
|
|
|
Three things are returned: (args, varargs, varkw), where 'args' is
|
|
|
|
a list of argument names (possibly containing nested lists), and
|
|
|
|
'varargs' and 'varkw' are the names of the * and ** arguments or None."""
|
2003-06-27 15:14:39 -03:00
|
|
|
|
|
|
|
if not iscode(co):
|
|
|
|
raise TypeError('arg is not a code object')
|
2001-02-27 10:43:21 -04:00
|
|
|
|
|
|
|
nargs = co.co_argcount
|
|
|
|
names = co.co_varnames
|
|
|
|
args = list(names[:nargs])
|
|
|
|
step = 0
|
|
|
|
|
|
|
|
# The following acrobatics are for anonymous (tuple) arguments.
|
|
|
|
for i in range(nargs):
|
2005-02-06 02:57:08 -04:00
|
|
|
if args[i][:1] in ('', '.'):
|
2001-02-27 10:43:21 -04:00
|
|
|
stack, remain, count = [], [], []
|
2007-07-12 05:11:29 -03:00
|
|
|
while step < len(co.co_code):
|
|
|
|
op = ord(co.co_code[step])
|
2001-02-27 10:43:21 -04:00
|
|
|
step = step + 1
|
|
|
|
if op >= dis.HAVE_ARGUMENT:
|
|
|
|
opname = dis.opname[op]
|
2007-07-12 05:11:29 -03:00
|
|
|
value = ord(co.co_code[step]) + ord(co.co_code[step+1])*256
|
2001-02-27 10:43:21 -04:00
|
|
|
step = step + 2
|
2005-02-06 02:57:08 -04:00
|
|
|
if opname in ('UNPACK_TUPLE', 'UNPACK_SEQUENCE'):
|
2001-02-27 10:43:21 -04:00
|
|
|
remain.append(value)
|
|
|
|
count.append(value)
|
|
|
|
elif opname == 'STORE_FAST':
|
|
|
|
stack.append(names[value])
|
2004-08-15 14:04:33 -03:00
|
|
|
|
|
|
|
# Special case for sublists of length 1: def foo((bar))
|
|
|
|
# doesn't generate the UNPACK_TUPLE bytecode, so if
|
|
|
|
# `remain` is empty here, we have such a sublist.
|
|
|
|
if not remain:
|
|
|
|
stack[0] = [stack[0]]
|
|
|
|
break
|
|
|
|
else:
|
2001-02-27 10:43:21 -04:00
|
|
|
remain[-1] = remain[-1] - 1
|
2004-08-15 14:04:33 -03:00
|
|
|
while remain[-1] == 0:
|
|
|
|
remain.pop()
|
|
|
|
size = count.pop()
|
|
|
|
stack[-size:] = [stack[-size:]]
|
|
|
|
if not remain: break
|
|
|
|
remain[-1] = remain[-1] - 1
|
|
|
|
if not remain: break
|
2001-02-27 10:43:21 -04:00
|
|
|
args[i] = stack[0]
|
|
|
|
|
|
|
|
varargs = None
|
|
|
|
if co.co_flags & CO_VARARGS:
|
|
|
|
varargs = co.co_varnames[nargs]
|
|
|
|
nargs = nargs + 1
|
|
|
|
varkw = None
|
|
|
|
if co.co_flags & CO_VARKEYWORDS:
|
|
|
|
varkw = co.co_varnames[nargs]
|
2008-01-10 23:04:50 -04:00
|
|
|
return Arguments(args, varargs, varkw)
|
|
|
|
|
|
|
|
ArgSpec = namedtuple('ArgSpec', 'args varargs keywords defaults')
|
2001-02-27 10:43:21 -04:00
|
|
|
|
|
|
|
def getargspec(func):
|
|
|
|
"""Get the names and default values of a function's arguments.
|
|
|
|
|
|
|
|
A tuple of four things is returned: (args, varargs, varkw, defaults).
|
|
|
|
'args' is a list of the argument names (it may contain nested lists).
|
|
|
|
'varargs' and 'varkw' are the names of the * and ** arguments or None.
|
2003-06-27 15:14:39 -03:00
|
|
|
'defaults' is an n-tuple of the default values of the last n arguments.
|
|
|
|
"""
|
|
|
|
|
|
|
|
if ismethod(func):
|
|
|
|
func = func.im_func
|
|
|
|
if not isfunction(func):
|
|
|
|
raise TypeError('arg is not a Python function')
|
2001-02-27 10:43:21 -04:00
|
|
|
args, varargs, varkw = getargs(func.func_code)
|
2008-01-10 23:04:50 -04:00
|
|
|
return ArgSpec(args, varargs, varkw, func.func_defaults)
|
|
|
|
|
|
|
|
ArgInfo = namedtuple('ArgInfo', 'args varargs keywords locals')
|
2001-02-27 10:43:21 -04:00
|
|
|
|
|
|
|
def getargvalues(frame):
|
|
|
|
"""Get information about arguments passed into a particular frame.
|
|
|
|
|
|
|
|
A tuple of four things is returned: (args, varargs, varkw, locals).
|
|
|
|
'args' is a list of the argument names (it may contain nested lists).
|
|
|
|
'varargs' and 'varkw' are the names of the * and ** arguments or None.
|
|
|
|
'locals' is the locals dictionary of the given frame."""
|
|
|
|
args, varargs, varkw = getargs(frame.f_code)
|
2008-10-21 19:28:54 -03:00
|
|
|
return ArgInfo(args, varargs, varkw, frame.f_locals)
|
2001-02-27 10:43:21 -04:00
|
|
|
|
|
|
|
def joinseq(seq):
|
|
|
|
if len(seq) == 1:
|
|
|
|
return '(' + seq[0] + ',)'
|
|
|
|
else:
|
|
|
|
return '(' + string.join(seq, ', ') + ')'
|
|
|
|
|
|
|
|
def strseq(object, convert, join=joinseq):
|
|
|
|
"""Recursively walk a sequence, stringifying each element."""
|
2005-02-06 02:57:08 -04:00
|
|
|
if type(object) in (list, tuple):
|
2001-02-27 10:43:21 -04:00
|
|
|
return join(map(lambda o, c=convert, j=join: strseq(o, c, j), object))
|
|
|
|
else:
|
|
|
|
return convert(object)
|
|
|
|
|
|
|
|
def formatargspec(args, varargs=None, varkw=None, defaults=None,
|
|
|
|
formatarg=str,
|
|
|
|
formatvarargs=lambda name: '*' + name,
|
|
|
|
formatvarkw=lambda name: '**' + name,
|
|
|
|
formatvalue=lambda value: '=' + repr(value),
|
|
|
|
join=joinseq):
|
|
|
|
"""Format an argument spec from the 4 values returned by getargspec.
|
|
|
|
|
|
|
|
The first four arguments are (args, varargs, varkw, defaults). The
|
|
|
|
other four arguments are the corresponding optional formatting functions
|
|
|
|
that are called to turn names and values into strings. The ninth
|
|
|
|
argument is an optional function to format the sequence of arguments."""
|
|
|
|
specs = []
|
|
|
|
if defaults:
|
|
|
|
firstdefault = len(args) - len(defaults)
|
|
|
|
for i in range(len(args)):
|
|
|
|
spec = strseq(args[i], formatarg, join)
|
|
|
|
if defaults and i >= firstdefault:
|
|
|
|
spec = spec + formatvalue(defaults[i - firstdefault])
|
|
|
|
specs.append(spec)
|
2002-06-01 00:06:31 -03:00
|
|
|
if varargs is not None:
|
2001-02-27 10:43:21 -04:00
|
|
|
specs.append(formatvarargs(varargs))
|
2002-06-01 00:06:31 -03:00
|
|
|
if varkw is not None:
|
2001-02-27 10:43:21 -04:00
|
|
|
specs.append(formatvarkw(varkw))
|
|
|
|
return '(' + string.join(specs, ', ') + ')'
|
|
|
|
|
|
|
|
def formatargvalues(args, varargs, varkw, locals,
|
|
|
|
formatarg=str,
|
|
|
|
formatvarargs=lambda name: '*' + name,
|
|
|
|
formatvarkw=lambda name: '**' + name,
|
|
|
|
formatvalue=lambda value: '=' + repr(value),
|
|
|
|
join=joinseq):
|
|
|
|
"""Format an argument spec from the 4 values returned by getargvalues.
|
|
|
|
|
|
|
|
The first four arguments are (args, varargs, varkw, locals). The
|
|
|
|
next four arguments are the corresponding optional formatting functions
|
|
|
|
that are called to turn names and values into strings. The ninth
|
|
|
|
argument is an optional function to format the sequence of arguments."""
|
|
|
|
def convert(name, locals=locals,
|
|
|
|
formatarg=formatarg, formatvalue=formatvalue):
|
|
|
|
return formatarg(name) + formatvalue(locals[name])
|
|
|
|
specs = []
|
|
|
|
for i in range(len(args)):
|
|
|
|
specs.append(strseq(args[i], convert, join))
|
|
|
|
if varargs:
|
|
|
|
specs.append(formatvarargs(varargs) + formatvalue(locals[varargs]))
|
|
|
|
if varkw:
|
|
|
|
specs.append(formatvarkw(varkw) + formatvalue(locals[varkw]))
|
|
|
|
return '(' + string.join(specs, ', ') + ')'
|
|
|
|
|
|
|
|
# -------------------------------------------------- stack frame extraction
|
2008-01-10 23:04:50 -04:00
|
|
|
|
|
|
|
Traceback = namedtuple('Traceback', 'filename lineno function code_context index')
|
|
|
|
|
2001-02-27 10:43:21 -04:00
|
|
|
def getframeinfo(frame, context=1):
|
|
|
|
"""Get information about a frame or traceback object.
|
|
|
|
|
|
|
|
A tuple of five things is returned: the filename, the line number of
|
|
|
|
the current line, the function name, a list of lines of context from
|
|
|
|
the source code, and the index of the current line within that list.
|
|
|
|
The optional second argument specifies the number of lines of context
|
|
|
|
to return, which are centered around the current line."""
|
|
|
|
if istraceback(frame):
|
2004-06-05 11:11:59 -03:00
|
|
|
lineno = frame.tb_lineno
|
2001-02-27 10:43:21 -04:00
|
|
|
frame = frame.tb_frame
|
2004-06-05 11:11:59 -03:00
|
|
|
else:
|
|
|
|
lineno = frame.f_lineno
|
2001-02-27 10:43:21 -04:00
|
|
|
if not isframe(frame):
|
2003-06-27 15:41:20 -03:00
|
|
|
raise TypeError('arg is not a frame or traceback object')
|
2001-02-27 10:43:21 -04:00
|
|
|
|
2002-03-23 19:51:04 -04:00
|
|
|
filename = getsourcefile(frame) or getfile(frame)
|
2001-02-27 10:43:21 -04:00
|
|
|
if context > 0:
|
2001-09-04 16:14:14 -03:00
|
|
|
start = lineno - 1 - context//2
|
2001-02-27 10:43:21 -04:00
|
|
|
try:
|
|
|
|
lines, lnum = findsource(frame)
|
2001-03-02 01:50:34 -04:00
|
|
|
except IOError:
|
|
|
|
lines = index = None
|
|
|
|
else:
|
2001-02-27 10:43:21 -04:00
|
|
|
start = max(start, 1)
|
2004-06-15 08:22:53 -03:00
|
|
|
start = max(0, min(start, len(lines) - context))
|
2001-02-27 10:43:21 -04:00
|
|
|
lines = lines[start:start+context]
|
2001-02-28 23:55:35 -04:00
|
|
|
index = lineno - 1 - start
|
2001-02-27 10:43:21 -04:00
|
|
|
else:
|
|
|
|
lines = index = None
|
|
|
|
|
2008-01-10 23:04:50 -04:00
|
|
|
return Traceback(filename, lineno, frame.f_code.co_name, lines, index)
|
2001-02-28 23:55:35 -04:00
|
|
|
|
|
|
|
def getlineno(frame):
|
|
|
|
"""Get the line number from a frame object, allowing for optimization."""
|
2002-08-15 11:59:02 -03:00
|
|
|
# FrameType.f_lineno is now a descriptor that grovels co_lnotab
|
|
|
|
return frame.f_lineno
|
2001-02-27 10:43:21 -04:00
|
|
|
|
|
|
|
def getouterframes(frame, context=1):
|
|
|
|
"""Get a list of records for a frame and all higher (calling) frames.
|
|
|
|
|
|
|
|
Each record contains a frame object, filename, line number, function
|
|
|
|
name, a list of lines of context, and index within the context."""
|
|
|
|
framelist = []
|
|
|
|
while frame:
|
|
|
|
framelist.append((frame,) + getframeinfo(frame, context))
|
|
|
|
frame = frame.f_back
|
|
|
|
return framelist
|
|
|
|
|
|
|
|
def getinnerframes(tb, context=1):
|
|
|
|
"""Get a list of records for a traceback's frame and all lower frames.
|
|
|
|
|
|
|
|
Each record contains a frame object, filename, line number, function
|
|
|
|
name, a list of lines of context, and index within the context."""
|
|
|
|
framelist = []
|
|
|
|
while tb:
|
|
|
|
framelist.append((tb.tb_frame,) + getframeinfo(tb, context))
|
|
|
|
tb = tb.tb_next
|
|
|
|
return framelist
|
|
|
|
|
2003-06-27 15:41:20 -03:00
|
|
|
currentframe = sys._getframe
|
2001-02-27 10:43:21 -04:00
|
|
|
|
|
|
|
def stack(context=1):
|
|
|
|
"""Return a list of records for the stack above the caller's frame."""
|
2003-06-27 15:41:20 -03:00
|
|
|
return getouterframes(sys._getframe(1), context)
|
2001-02-27 10:43:21 -04:00
|
|
|
|
|
|
|
def trace(context=1):
|
2001-02-28 04:26:44 -04:00
|
|
|
"""Return a list of records for the stack below the current exception."""
|
2002-04-25 23:29:55 -03:00
|
|
|
return getinnerframes(sys.exc_info()[2], context)
|