889 lines · 34.9 KB · Python
RawDownload
# -*- coding: iso-8859-1 -*-"""Get useful information from live Python objects. This module encapsulates the interface provided by the internal specialattributes (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:     ismodule(), isclass(), ismethod(), isfunction(), istraceback(),        isframe(), iscode(), isbuiltin(), isroutine() - check object types    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. __author__ = 'Ka-Ping Yee <ping@lfw.org>'__date__ = '1 Jan 2001' import sys, os, types, string, re, dis, imp, tokenize, linecachefrom operator import attrgetter # ----------------------------------------------------------- type-checkingdef 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)"""    return isinstance(object, types.ModuleType) 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"""    return isinstance(object, types.ClassType) or hasattr(object, '__bases__') 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"""    return isinstance(object, types.MethodType) def ismethoddescriptor(object):    """Return true if the object is a method descriptor.     But not if ismethod() or isclass() or isfunction() are true.     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.     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()."""    return (hasattr(object, "__get__")            and not hasattr(object, "__set__") # else it's a data descriptor            and not ismethod(object)           # mutual exclusion            and not isfunction(object)            and not isclass(object)) 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__")) 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 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__)"""    return isinstance(object, types.FunctionType) 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)"""    return isinstance(object, types.TracebackType) 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"""    return isinstance(object, types.FrameType) 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"""    return isinstance(object, types.CodeType) 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"""    return isinstance(object, types.BuiltinFunctionType) def isroutine(object):    """Return true if the object is any kind of function or method."""    return (isbuiltin(object)            or isfunction(object)            or ismethod(object)            or ismethoddescriptor(object)) 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 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:            # search the dicts.            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"         result.append((name, kind, homecls, obj))     return result # ----------------------------------------------------------- class helpersdef _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) # -------------------------------------------------- source code extractiondef 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."""    try:        doc = object.__doc__    except AttributeError:        return None    if not isinstance(doc, types.StringTypes):        return None    try:        lines = string.split(string.expandtabs(doc), '\n')    except UnicodeError:        return None    else:        # Find minimum indentation of any non-blank lines after first line.        margin = sys.maxint        for line in lines[1:]:            content = len(string.lstrip(line))            if content:                indent = len(line) - content                margin = min(margin, indent)        # Remove indentation.        if lines:            lines[0] = lines[0].lstrip()        if margin < sys.maxint:            for i in range(1, len(lines)): lines[i] = lines[i][margin:]        # Remove any trailing or leading blank lines.        while lines and not lines[-1]:            lines.pop()        while lines and not lines[0]:            lines.pop(0)        return string.join(lines, '\n') def getfile(object):    """Work out which source or compiled file an object was defined in."""    if ismodule(object):        if hasattr(object, '__file__'):            return object.__file__        raise TypeError('arg is a built-in module')    if isclass(object):        object = sys.modules.get(object.__module__)        if hasattr(object, '__file__'):            return object.__file__        raise TypeError('arg is a built-in class')    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    raise TypeError('arg is not a module, class, method, '                    'function, traceback, frame, or code object') def getmoduleinfo(path):    """Get the module name, suffix, mode, and module type for a given file."""    filename = os.path.basename(path)    suffixes = map(lambda (suffix, mode, mtype):                   (-len(suffix), suffix, mode, mtype), imp.get_suffixes())    suffixes.sort() # try longest suffixes first, in case they overlap    for neglen, suffix, mode, mtype in suffixes:        if filename[neglen:] == suffix:            return filename[:neglen], suffix, mode, mtype def getmodulename(path):    """Return the module name for a given file, or None."""    info = getmoduleinfo(path)    if info: return info[0] def getsourcefile(object):    """Return the Python source file an object was defined in, if it exists."""    filename = getfile(object)    if string.lower(filename[-4:]) in ('.pyc', '.pyo'):        filename = filename[:-4] + '.py'    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    if os.path.exists(filename):        return filename    # only return a non-existent filename if the module has a PEP 302 loader    if hasattr(getmodule(object, filename), '__loader__'):        return filename def getabsfile(object, _filename=None):    """Return an absolute path to the source or compiled file for an object.     The idea is for each object to have a unique origin, so this routine    normalizes the result as much as possible."""    if _filename is None:        _filename = getsourcefile(object) or getfile(object)    return os.path.normcase(os.path.abspath(_filename)) modulesbyfile = {}_filesbymodname = {} def getmodule(object, _filename=None):    """Return the module an object was defined in, or None if not found."""    if ismodule(object):        return object    if hasattr(object, '__module__'):        return sys.modules.get(object.__module__)    # 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    try:        file = getabsfile(object, _filename)    except TypeError:        return None    if file in modulesbyfile:        return sys.modules.get(modulesbyfile[file])    # 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():        if ismodule(module) and hasattr(module, '__file__'):            f = module.__file__            if f == _filesbymodname.get(modname, None):                # Have already mapped this module, so skip it                continue            _filesbymodname[modname] = f            f = getabsfile(module)            # Always map to the name the module knows itself by            modulesbyfile[f] = modulesbyfile[                os.path.realpath(f)] = module.__name__    if file in modulesbyfile:        return sys.modules.get(modulesbyfile[file])    # Check the main module    main = sys.modules['__main__']    if not hasattr(object, '__name__'):        return None    if hasattr(main, object.__name__):        mainobject = getattr(main, object.__name__)        if mainobject is object:            return main    # Check builtins    builtin = sys.modules['__builtin__']    if hasattr(builtin, object.__name__):        builtinobject = getattr(builtin, object.__name__)        if builtinobject is object:            return builtin 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."""    file = getsourcefile(object) or getfile(object)    module = getmodule(object, file)    if module:        lines = linecache.getlines(file, module.__dict__)    else:        lines = linecache.getlines(file)    if not lines:        raise IOError('could not get source code')     if ismodule(object):        return lines, 0     if isclass(object):        name = object.__name__        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 = []        for i in range(len(lines)):            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]        else:            raise IOError('could not find class definition')     if ismethod(object):        object = object.im_func    if isfunction(object):        object = object.func_code    if istraceback(object):

Lines 1–500 of 889.