home *** CD-ROM | disk | FTP | other *** search
/ com!online 2005 April / com_0405_1.iso / opensource / BTpp-0.5.4-bin.exe / $INSTDIR / BT++.exe / inspect.pyo (.txt) < prev    next >
Encoding:
Python Compiled Bytecode  |  2003-04-19  |  23.2 KB  |  701 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyo (Python 2.2)
  3.  
  4. __author__ = 'Ka-Ping Yee <ping@lfw.org>'
  5. __date__ = '1 Jan 2001'
  6. import sys
  7. import os
  8. import types
  9. import string
  10. import re
  11. import dis
  12. import imp
  13. import tokenize
  14.  
  15. def ismodule(object):
  16.     return isinstance(object, types.ModuleType)
  17.  
  18.  
  19. def isclass(object):
  20.     if not isinstance(object, types.ClassType):
  21.         pass
  22.     return hasattr(object, '__bases__')
  23.  
  24.  
  25. def ismethod(object):
  26.     return isinstance(object, types.MethodType)
  27.  
  28.  
  29. def ismethoddescriptor(object):
  30.     if hasattr(object, '__get__') and not hasattr(object, '__set__') and not ismethod(object) and not isfunction(object):
  31.         pass
  32.     return not isclass(object)
  33.  
  34.  
  35. def isfunction(object):
  36.     return isinstance(object, types.FunctionType)
  37.  
  38.  
  39. def istraceback(object):
  40.     return isinstance(object, types.TracebackType)
  41.  
  42.  
  43. def isframe(object):
  44.     return isinstance(object, types.FrameType)
  45.  
  46.  
  47. def iscode(object):
  48.     return isinstance(object, types.CodeType)
  49.  
  50.  
  51. def isbuiltin(object):
  52.     return isinstance(object, types.BuiltinFunctionType)
  53.  
  54.  
  55. def isroutine(object):
  56.     if not isbuiltin(object) and isfunction(object) and ismethod(object):
  57.         pass
  58.     return ismethoddescriptor(object)
  59.  
  60.  
  61. def getmembers(object, predicate = None):
  62.     results = []
  63.     for key in dir(object):
  64.         value = getattr(object, key)
  65.         if not predicate or predicate(value):
  66.             results.append((key, value))
  67.         
  68.     
  69.     results.sort()
  70.     return results
  71.  
  72.  
  73. def classify_class_attrs(cls):
  74.     mro = getmro(cls)
  75.     names = dir(cls)
  76.     result = []
  77.     for name in names:
  78.         if name in cls.__dict__:
  79.             obj = cls.__dict__[name]
  80.         else:
  81.             obj = getattr(cls, name)
  82.         homecls = getattr(obj, '__objclass__', None)
  83.         if homecls is None:
  84.             for base in mro:
  85.                 if name in base.__dict__:
  86.                     homecls = base
  87.                     break
  88.                 
  89.             
  90.         
  91.         if homecls is not None and name in homecls.__dict__:
  92.             obj = homecls.__dict__[name]
  93.         
  94.         obj_via_getattr = getattr(cls, name)
  95.         if isinstance(obj, staticmethod):
  96.             kind = 'static method'
  97.         elif isinstance(obj, classmethod):
  98.             kind = 'class method'
  99.         elif isinstance(obj, property):
  100.             kind = 'property'
  101.         elif ismethod(obj_via_getattr) or ismethoddescriptor(obj_via_getattr):
  102.             kind = 'method'
  103.         else:
  104.             kind = 'data'
  105.         result.append((name, kind, homecls, obj))
  106.     
  107.     return result
  108.  
  109.  
  110. def _searchbases(cls, accum):
  111.     if cls in accum:
  112.         return None
  113.     
  114.     accum.append(cls)
  115.     for base in cls.__bases__:
  116.         _searchbases(base, accum)
  117.     
  118.  
  119.  
  120. def getmro(cls):
  121.     if hasattr(cls, '__mro__'):
  122.         return cls.__mro__
  123.     else:
  124.         result = []
  125.         _searchbases(cls, result)
  126.         return tuple(result)
  127.  
  128.  
  129. def indentsize(line):
  130.     expline = string.expandtabs(line)
  131.     return len(expline) - len(string.lstrip(expline))
  132.  
  133.  
  134. def getdoc(object):
  135.     
  136.     try:
  137.         doc = object.__doc__
  138.     except AttributeError:
  139.         return None
  140.  
  141.     if not isinstance(doc, (str, unicode)):
  142.         return None
  143.     
  144.     
  145.     try:
  146.         lines = string.split(string.expandtabs(doc), '\n')
  147.     except UnicodeError:
  148.         return None
  149.  
  150.     margin = None
  151.     for line in lines[1:]:
  152.         content = len(string.lstrip(line))
  153.         if not content:
  154.             continue
  155.         
  156.         indent = len(line) - content
  157.         if margin is None:
  158.             margin = indent
  159.         else:
  160.             margin = min(margin, indent)
  161.     
  162.     if margin is not None:
  163.         for i in range(1, len(lines)):
  164.             lines[i] = lines[i][margin:]
  165.         
  166.     
  167.     return string.join(lines, '\n')
  168.  
  169.  
  170. def getfile(object):
  171.     if ismodule(object):
  172.         if hasattr(object, '__file__'):
  173.             return object.__file__
  174.         
  175.         raise TypeError, 'arg is a built-in module'
  176.     
  177.     if isclass(object):
  178.         object = sys.modules.get(object.__module__)
  179.         if hasattr(object, '__file__'):
  180.             return object.__file__
  181.         
  182.         raise TypeError, 'arg is a built-in class'
  183.     
  184.     if ismethod(object):
  185.         object = object.im_func
  186.     
  187.     if isfunction(object):
  188.         object = object.func_code
  189.     
  190.     if istraceback(object):
  191.         object = object.tb_frame
  192.     
  193.     if isframe(object):
  194.         object = object.f_code
  195.     
  196.     if iscode(object):
  197.         return object.co_filename
  198.     
  199.     raise TypeError, 'arg is not a module, class, method, function, traceback, frame, or code object'
  200.  
  201.  
  202. def getmoduleinfo(path):
  203.     filename = os.path.basename(path)
  204.     suffixes = map((lambda .0: (suffix, mode, mtype) = .0(-len(suffix), suffix, mode, mtype)), imp.get_suffixes())
  205.     suffixes.sort()
  206.     for neglen, suffix, mode, mtype in suffixes:
  207.         if filename[neglen:] == suffix:
  208.             return (filename[:neglen], suffix, mode, mtype)
  209.         
  210.     
  211.  
  212.  
  213. def getmodulename(path):
  214.     info = getmoduleinfo(path)
  215.     if info:
  216.         return info[0]
  217.     
  218.  
  219.  
  220. def getsourcefile(object):
  221.     filename = getfile(object)
  222.     if string.lower(filename[-4:]) in [
  223.         '.pyc',
  224.         '.pyo']:
  225.         filename = filename[:-4] + '.py'
  226.     
  227.     for suffix, mode, kind in imp.get_suffixes():
  228.         if 'b' in mode and string.lower(filename[-len(suffix):]) == suffix:
  229.             return None
  230.         
  231.     
  232.     if os.path.exists(filename):
  233.         return filename
  234.     
  235.  
  236.  
  237. def getabsfile(object):
  238.     if not getsourcefile(object):
  239.         pass
  240.     return os.path.normcase(os.path.abspath(getfile(object)))
  241.  
  242. modulesbyfile = { }
  243.  
  244. def getmodule(object):
  245.     if ismodule(object):
  246.         return object
  247.     
  248.     if isclass(object):
  249.         return sys.modules.get(object.__module__)
  250.     
  251.     
  252.     try:
  253.         file = getabsfile(object)
  254.     except TypeError:
  255.         return None
  256.  
  257.     if modulesbyfile.has_key(file):
  258.         return sys.modules[modulesbyfile[file]]
  259.     
  260.     for module in sys.modules.values():
  261.         if hasattr(module, '__file__'):
  262.             modulesbyfile[getabsfile(module)] = module.__name__
  263.         
  264.     
  265.     if modulesbyfile.has_key(file):
  266.         return sys.modules[modulesbyfile[file]]
  267.     
  268.     main = sys.modules['__main__']
  269.     if hasattr(main, object.__name__):
  270.         mainobject = getattr(main, object.__name__)
  271.         if mainobject is object:
  272.             return main
  273.         
  274.     
  275.     builtin = sys.modules['__builtin__']
  276.     if hasattr(builtin, object.__name__):
  277.         builtinobject = getattr(builtin, object.__name__)
  278.         if builtinobject is object:
  279.             return builtin
  280.         
  281.     
  282.  
  283.  
  284. def findsource(object):
  285.     
  286.     try:
  287.         file = open(getsourcefile(object))
  288.     except (TypeError, IOError):
  289.         raise IOError, 'could not get source code'
  290.  
  291.     lines = file.readlines()
  292.     file.close()
  293.     if ismodule(object):
  294.         return (lines, 0)
  295.     
  296.     if isclass(object):
  297.         name = object.__name__
  298.         pat = re.compile('^\\s*class\\s*' + name + '\\b')
  299.         for i in range(len(lines)):
  300.             if pat.match(lines[i]):
  301.                 return (lines, i)
  302.             
  303.         else:
  304.             raise IOError, 'could not find class definition'
  305.     
  306.     if ismethod(object):
  307.         object = object.im_func
  308.     
  309.     if isfunction(object):
  310.         object = object.func_code
  311.     
  312.     if istraceback(object):
  313.         object = object.tb_frame
  314.     
  315.     if isframe(object):
  316.         object = object.f_code
  317.     
  318.     if iscode(object):
  319.         if not hasattr(object, 'co_firstlineno'):
  320.             raise IOError, 'could not find function definition'
  321.         
  322.         lnum = object.co_firstlineno - 1
  323.         pat = re.compile('^\\s*def\\s')
  324.         while lnum > 0:
  325.             if pat.match(lines[lnum]):
  326.                 break
  327.             
  328.             lnum = lnum - 1
  329.         return (lines, lnum)
  330.     
  331.     raise IOError, 'could not find code object'
  332.  
  333.  
  334. def getcomments(object):
  335.     
  336.     try:
  337.         (lines, lnum) = findsource(object)
  338.     except IOError:
  339.         return None
  340.  
  341.     if ismodule(object):
  342.         start = 0
  343.         if lines and lines[0][:2] == '#!':
  344.             start = 1
  345.         
  346.         while start < len(lines) and string.strip(lines[start]) in [
  347.             '',
  348.             '#']:
  349.             start = start + 1
  350.         if start < len(lines) and lines[start][:1] == '#':
  351.             comments = []
  352.             end = start
  353.             while end < len(lines) and lines[end][:1] == '#':
  354.                 comments.append(string.expandtabs(lines[end]))
  355.                 end = end + 1
  356.             return string.join(comments, '')
  357.         
  358.     elif lnum > 0:
  359.         indent = indentsize(lines[lnum])
  360.         end = lnum - 1
  361.         if end >= 0 and string.lstrip(lines[end])[:1] == '#' and indentsize(lines[end]) == indent:
  362.             comments = [
  363.                 string.lstrip(string.expandtabs(lines[end]))]
  364.             if end > 0:
  365.                 end = end - 1
  366.                 comment = string.lstrip(string.expandtabs(lines[end]))
  367.                 while comment[:1] == '#' and indentsize(lines[end]) == indent:
  368.                     comments[:0] = [
  369.                         comment]
  370.                     end = end - 1
  371.                     if end < 0:
  372.                         break
  373.                     
  374.                     comment = string.lstrip(string.expandtabs(lines[end]))
  375.             
  376.             while comments and string.strip(comments[0]) == '#':
  377.                 comments[:1] = []
  378.             while comments and string.strip(comments[-1]) == '#':
  379.                 comments[-1:] = []
  380.             return string.join(comments, '')
  381.         
  382.     
  383.  
  384.  
  385. class ListReader:
  386.     
  387.     def __init__(self, lines):
  388.         self.lines = lines
  389.         self.index = 0
  390.  
  391.     
  392.     def readline(self):
  393.         i = self.index
  394.         if i < len(self.lines):
  395.             self.index = i + 1
  396.             return self.lines[i]
  397.         else:
  398.             return ''
  399.  
  400.  
  401.  
  402. class EndOfBlock(Exception):
  403.     pass
  404.  
  405.  
  406. class BlockFinder:
  407.     
  408.     def __init__(self):
  409.         self.indent = 0
  410.         self.started = 0
  411.         self.last = 0
  412.  
  413.     
  414.     def tokeneater(self, type, token, .6, .8, line):
  415.         (srow, scol) = .6
  416.         (erow, ecol) = .8
  417.         if not (self.started):
  418.             if type == tokenize.NAME:
  419.                 self.started = 1
  420.             
  421.         elif type == tokenize.NEWLINE:
  422.             self.last = srow
  423.         elif type == tokenize.INDENT:
  424.             self.indent = self.indent + 1
  425.         elif type == tokenize.DEDENT:
  426.             self.indent = self.indent - 1
  427.             if self.indent == 0:
  428.                 raise EndOfBlock, self.last
  429.             
  430.         
  431.  
  432.  
  433.  
  434. def getblock(lines):
  435.     
  436.     try:
  437.         tokenize.tokenize(ListReader(lines).readline, BlockFinder().tokeneater)
  438.     except EndOfBlock:
  439.         eob = None
  440.         return lines[:eob.args[0]]
  441.  
  442.  
  443.  
  444. def getsourcelines(object):
  445.     (lines, lnum) = findsource(object)
  446.     if ismodule(object):
  447.         return (lines, 0)
  448.     else:
  449.         return (getblock(lines[lnum:]), lnum + 1)
  450.  
  451.  
  452. def getsource(object):
  453.     (lines, lnum) = getsourcelines(object)
  454.     return string.join(lines, '')
  455.  
  456.  
  457. def walktree(classes, children, parent):
  458.     results = []
  459.     classes.sort((lambda a, b: cmp(a.__name__, b.__name__)))
  460.     for c in classes:
  461.         results.append((c, c.__bases__))
  462.         if children.has_key(c):
  463.             results.append(walktree(children[c], children, c))
  464.         
  465.     
  466.     return results
  467.  
  468.  
  469. def getclasstree(classes, unique = 0):
  470.     children = { }
  471.     roots = []
  472.     for c in classes:
  473.         if c.__bases__:
  474.             for parent in c.__bases__:
  475.                 if not children.has_key(parent):
  476.                     children[parent] = []
  477.                 
  478.                 children[parent].append(c)
  479.                 if unique and parent in classes:
  480.                     break
  481.                 
  482.             
  483.         elif c not in roots:
  484.             roots.append(c)
  485.         
  486.     
  487.     for parent in children.keys():
  488.         if parent not in classes:
  489.             roots.append(parent)
  490.         
  491.     
  492.     return walktree(roots, children, None)
  493.  
  494. (CO_OPTIMIZED, CO_NEWLOCALS, CO_VARARGS, CO_VARKEYWORDS) = (1, 2, 4, 8)
  495.  
  496. def getargs(co):
  497.     if not iscode(co):
  498.         raise TypeError, 'arg is not a code object'
  499.     
  500.     code = co.co_code
  501.     nargs = co.co_argcount
  502.     names = co.co_varnames
  503.     args = list(names[:nargs])
  504.     step = 0
  505.     for i in range(nargs):
  506.         if args[i][:1] in [
  507.             '',
  508.             '.']:
  509.             (stack, remain, count) = ([], [], [])
  510.             while step < len(code):
  511.                 op = ord(code[step])
  512.                 step = step + 1
  513.                 if op >= dis.HAVE_ARGUMENT:
  514.                     opname = dis.opname[op]
  515.                     value = ord(code[step]) + ord(code[step + 1]) * 256
  516.                     step = step + 2
  517.                     if opname in [
  518.                         'UNPACK_TUPLE',
  519.                         'UNPACK_SEQUENCE']:
  520.                         remain.append(value)
  521.                         count.append(value)
  522.                     elif opname == 'STORE_FAST':
  523.                         stack.append(names[value])
  524.                         remain[-1] = remain[-1] - 1
  525.                         while remain[-1] == 0:
  526.                             remain.pop()
  527.                             size = count.pop()
  528.                             stack[-size:] = [
  529.                                 stack[-size:]]
  530.                             if not remain:
  531.                                 break
  532.                             
  533.                             remain[-1] = remain[-1] - 1
  534.                         if not remain:
  535.                             break
  536.                         
  537.                     
  538.                 
  539.             args[i] = stack[0]
  540.         
  541.     
  542.     varargs = None
  543.     if co.co_flags & CO_VARARGS:
  544.         varargs = co.co_varnames[nargs]
  545.         nargs = nargs + 1
  546.     
  547.     varkw = None
  548.     if co.co_flags & CO_VARKEYWORDS:
  549.         varkw = co.co_varnames[nargs]
  550.     
  551.     return (args, varargs, varkw)
  552.  
  553.  
  554. def getargspec(func):
  555.     if not isfunction(func):
  556.         raise TypeError, 'arg is not a Python function'
  557.     
  558.     (args, varargs, varkw) = getargs(func.func_code)
  559.     return (args, varargs, varkw, func.func_defaults)
  560.  
  561.  
  562. def getargvalues(frame):
  563.     (args, varargs, varkw) = getargs(frame.f_code)
  564.     return (args, varargs, varkw, frame.f_locals)
  565.  
  566.  
  567. def joinseq(seq):
  568.     if len(seq) == 1:
  569.         return '(' + seq[0] + ',)'
  570.     else:
  571.         return '(' + string.join(seq, ', ') + ')'
  572.  
  573.  
  574. def strseq(object, convert, join = joinseq):
  575.     if type(object) in [
  576.         types.ListType,
  577.         types.TupleType]:
  578.         return join(map((lambda o, c = convert, j = join: strseq(o, c, j)), object))
  579.     else:
  580.         return convert(object)
  581.  
  582.  
  583. 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):
  584.     specs = []
  585.     if defaults:
  586.         firstdefault = len(args) - len(defaults)
  587.     
  588.     for i in range(len(args)):
  589.         spec = strseq(args[i], formatarg, join)
  590.         if defaults and i >= firstdefault:
  591.             spec = spec + formatvalue(defaults[i - firstdefault])
  592.         
  593.         specs.append(spec)
  594.     
  595.     if varargs:
  596.         specs.append(formatvarargs(varargs))
  597.     
  598.     if varkw:
  599.         specs.append(formatvarkw(varkw))
  600.     
  601.     return '(' + string.join(specs, ', ') + ')'
  602.  
  603.  
  604. def formatargvalues(args, varargs, varkw, locals, formatarg = str, formatvarargs = (lambda name: '*' + name), formatvarkw = (lambda name: '**' + name), formatvalue = (lambda value: '=' + repr(value)), join = joinseq):
  605.     
  606.     def convert(name, locals = locals, formatarg = formatarg, formatvalue = formatvalue):
  607.         return formatarg(name) + formatvalue(locals[name])
  608.  
  609.     specs = []
  610.     for i in range(len(args)):
  611.         specs.append(strseq(args[i], convert, join))
  612.     
  613.     if varargs:
  614.         specs.append(formatvarargs(varargs) + formatvalue(locals[varargs]))
  615.     
  616.     if varkw:
  617.         specs.append(formatvarkw(varkw) + formatvalue(locals[varkw]))
  618.     
  619.     return '(' + string.join(specs, ', ') + ')'
  620.  
  621.  
  622. def getframeinfo(frame, context = 1):
  623.     if istraceback(frame):
  624.         frame = frame.tb_frame
  625.     
  626.     if not isframe(frame):
  627.         raise TypeError, 'arg is not a frame or traceback object'
  628.     
  629.     filename = getsourcefile(frame)
  630.     lineno = getlineno(frame)
  631.     if context > 0:
  632.         start = lineno - 1 - context // 2
  633.         
  634.         try:
  635.             (lines, lnum) = findsource(frame)
  636.         except IOError:
  637.             lines = index = None
  638.  
  639.         start = max(start, 1)
  640.         start = min(start, len(lines) - context)
  641.         lines = lines[start:start + context]
  642.         index = lineno - 1 - start
  643.     else:
  644.         lines = index = None
  645.     return (filename, lineno, frame.f_code.co_name, lines, index)
  646.  
  647.  
  648. def getlineno(frame):
  649.     lineno = frame.f_lineno
  650.     code = frame.f_code
  651.     if hasattr(code, 'co_lnotab'):
  652.         table = code.co_lnotab
  653.         lineno = code.co_firstlineno
  654.         addr = 0
  655.         for i in range(0, len(table), 2):
  656.             addr = addr + ord(table[i])
  657.             if addr > frame.f_lasti:
  658.                 break
  659.             
  660.             lineno = lineno + ord(table[i + 1])
  661.         
  662.     
  663.     return lineno
  664.  
  665.  
  666. def getouterframes(frame, context = 1):
  667.     framelist = []
  668.     while frame:
  669.         framelist.append((frame,) + getframeinfo(frame, context))
  670.         frame = frame.f_back
  671.     return framelist
  672.  
  673.  
  674. def getinnerframes(tb, context = 1):
  675.     framelist = []
  676.     while tb:
  677.         framelist.append((tb.tb_frame,) + getframeinfo(tb, context))
  678.         tb = tb.tb_next
  679.     return framelist
  680.  
  681.  
  682. def currentframe():
  683.     
  684.     try:
  685.         raise 'catch me'
  686.     except:
  687.         return sys.exc_traceback.tb_frame.f_back
  688.  
  689.  
  690. if hasattr(sys, '_getframe'):
  691.     currentframe = sys._getframe
  692.  
  693.  
  694. def stack(context = 1):
  695.     return getouterframes(currentframe().f_back, context)
  696.  
  697.  
  698. def trace(context = 1):
  699.     return getinnerframes(sys.exc_traceback, context)
  700.  
  701.