home *** CD-ROM | disk | FTP | other *** search
/ Maximum CD 2009 June / maximum-cd-2009-06.iso / DiscContents / digsby_setup.exe / lib / util / introspect.pyo (.txt) < prev    next >
Encoding:
Python Compiled Bytecode  |  2009-02-26  |  30.1 KB  |  979 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyo (Python 2.5)
  3.  
  4. from __future__ import with_statement
  5. import sys
  6. import time
  7. import threading
  8. import string
  9. import logging
  10. import re
  11. import keyword
  12. import types
  13. import inspect
  14. import primitives
  15. from weakref import ref
  16. from types import GeneratorType
  17. from path import path
  18. from collections import defaultdict
  19. from traceback import print_exc
  20. import warnings
  21. log = logging.getLogger('util.introspect')
  22. oldvars = vars
  23.  
  24. def uncollectable(clz):
  25.     import gc
  26.     gc.collect()
  27.     return _[1]
  28.  
  29.  
  30. class debug_property(object):
  31.     
  32.     def __init__(self, fget = None, fset = None, fdel = None, doc = None):
  33.         self._debug_property__get = fget
  34.         self._debug_property__set = fset
  35.         self._debug_property__del = fdel
  36.         self.__doc__ = doc
  37.  
  38.     
  39.     def __get__(self, inst, type = None):
  40.         if inst is None:
  41.             return self
  42.         
  43.         if self._debug_property__get is None:
  44.             raise AttributeError, 'unreadable attribute'
  45.         
  46.         
  47.         try:
  48.             return self._debug_property__get(inst)
  49.         except AttributeError:
  50.             e = None
  51.             print_exc()
  52.             raise AssertionError('attribute error during __get__')
  53.  
  54.  
  55.     
  56.     def __set__(self, inst, value):
  57.         if self._debug_property__set is None:
  58.             raise AttributeError, "can't set attribute"
  59.         
  60.         
  61.         try:
  62.             return self._debug_property__set(inst, value)
  63.         except AttributeError:
  64.             e = None
  65.             print_exc()
  66.             raise AssertionError('attribute error during __set__')
  67.  
  68.  
  69.     
  70.     def __delete__(self, inst):
  71.         if self._debug_property__del is None:
  72.             raise AttributeError, "can't delete attribute"
  73.         
  74.         
  75.         try:
  76.             return self._debug_property__del(inst)
  77.         except AttributeError:
  78.             e = None
  79.             print_exc()
  80.             raise AssertionErrror('attribute error during __del__')
  81.  
  82.  
  83.  
  84.  
  85. def vars(obj = None):
  86.     res = { }
  87.     if hasattr(obj, '__dict__'):
  88.         return oldvars(obj)
  89.     elif hasattr(obj, '__slots__'):
  90.         return (dict,)((lambda .0: for attr in .0:
  91. (attr, getattr(obj, attr, sentinel)))(obj.__slots__))
  92.     elif hasattr(obj, 'keys'):
  93.         return obj
  94.     else:
  95.         return dict((lambda .0: for x in .0:
  96. (x, sentinel))(obj))
  97.  
  98. version_23 = sys.version_info < (2, 4)
  99.  
  100. def this_list():
  101.     d = inspect.currentframe(1).f_locals
  102.     nestlevel = 1
  103.     while '_[%d]' % nestlevel in d:
  104.         nestlevel += 1
  105.     result = d['_[%d]' % (nestlevel - 1)]
  106.     if version_23:
  107.         return result.__self__
  108.     else:
  109.         return result
  110.  
  111.  
  112. def cannotcompile(f):
  113.     return f
  114.  
  115.  
  116. def stack_trace(level = 1, frame = None):
  117.     
  118.     try:
  119.         if frame is None:
  120.             f = sys._getframe(level)
  121.         else:
  122.             f = frame
  123.         frames = []
  124.         while f is not None:
  125.             c = f.f_code
  126.             frames.insert(0, (c.co_filename, c.co_firstlineno, c.co_name))
  127.             f = f.f_back
  128.         return frames
  129.     finally:
  130.         del f
  131.         del frame
  132.  
  133.  
  134.  
  135. def print_stack_trace(frame = None):
  136.     trace = stack_trace(2, frame)
  137.     for frame in trace:
  138.         print '  File "%s", line %d, in %s' % frame
  139.     
  140.  
  141.  
  142. def print_stack_traces():
  143.     frames = sys._current_frames().items()
  144.     for id, frame in frames:
  145.         print 'Frame %d:' % id
  146.         print_stack_trace(frame)
  147.     
  148.  
  149.  
  150. def is_all(seq, my_types = None):
  151.     if not seq:
  152.         
  153.         try:
  154.             iter(my_types)
  155.         except:
  156.             t = my_types
  157.         else:
  158.             t = my_types[0]
  159.         finally:
  160.             return (True, t)
  161.  
  162.     
  163.     if type(my_types) == type:
  164.         my_types = [
  165.             my_types]
  166.     
  167.     if my_types == None:
  168.         my_types = [
  169.             type(seq[0])]
  170.     
  171.     all = True
  172.     for elem in seq:
  173.         if type(elem) not in my_types:
  174.             all = False
  175.             break
  176.             continue
  177.     
  178.     if all:
  179.         return (all, my_types[0])
  180.     else:
  181.         return (all, None)
  182.  
  183.  
  184. def get_func_name(level = 1):
  185.     return sys._getframe(level).f_code.co_name
  186.  
  187.  
  188. def get_func(obj, command, *params):
  189.     
  190.     try:
  191.         func = getattr(obj, command.lower())
  192.         log.debug('Finding %s.%s%s', obj.__class__.__name__, command.lower(), params)
  193.     except AttributeError:
  194.         obj.__class__.__name__(command.lower(), ', '.join, [], []([ repr(x) for x in params ]))
  195.         func = None
  196.     except:
  197.         '%s has no function to handle: %s(%s)'
  198.  
  199.     return func
  200.  
  201.  
  202. def decormethod(decorator):
  203.     
  204.     def wrapper(method):
  205.         return (lambda self: decorator(self, method, *args, **kw))
  206.  
  207.     return wrapper
  208.  
  209.  
  210. def funcToMethod(func, clas, method_name = None):
  211.     func.im_class = clas
  212.     func.im_func = func
  213.     func.im_self = None
  214.     if not method_name:
  215.         method_name = func.__name__
  216.     
  217.     clas.__dict__[method_name] = func
  218.  
  219.  
  220. def attach_method(obj, func, name = None):
  221.     if not name:
  222.         pass
  223.     name = func.__name__
  224.     cls = obj.__class__
  225.     cls.temp_foo = func
  226.     obj.__setattr__(name, cls.temp_foo)
  227.     del cls.temp_foo
  228.  
  229.  
  230. def isgeneratormethod(object):
  231.     return isinstance(getattr(object, '__self__', None), GeneratorType)
  232.  
  233. CO_VARARGS = 4
  234. CO_VARKEYWORDS = 8
  235.  
  236. def callany(func, *args):
  237.     if not callable(func):
  238.         raise TypeError, "callany's first argument must be callable"
  239.     
  240.     CallLater = CallLater
  241.     CallLaterDelegate = CallLaterDelegate
  242.     CallbackSequence = CallbackSequence
  243.     import util.callbacks
  244.     c = func
  245.     while isinstance(c, CallLater):
  246.         c = c.cb
  247.     if isinstance(c, CallbackSequence):
  248.         c = c.__call__
  249.     
  250.     if hasattr(c, 'im_func'):
  251.         code = c.im_func.func_code
  252.         nargs = code.co_argcount - 1
  253.         codeflags = code.co_flags
  254.     elif hasattr(c, 'func_code'):
  255.         code = c.func_code
  256.         nargs = code.co_argcount
  257.         codeflags = code.co_flags
  258.     else:
  259.         code = None
  260.         codeflags = 0
  261.         nargs = len(args)
  262.     hasargs = codeflags & CO_VARARGS
  263.     haskwargs = codeflags & CO_VARKEYWORDS
  264.     if haskwargs:
  265.         args = []
  266.         msg = 'callany given a kwarg function (%r): no arguments will be passed!' % funcinfo(c)
  267.         warnings.warn(msg)
  268.         if getattr(sys, 'DEV', False):
  269.             raise AssertionError(msg)
  270.         
  271.     
  272.     if not hasargs:
  273.         args = list(args)[:nargs]
  274.         args += [
  275.             None] * (nargs - len(args))
  276.     
  277.     return func(*args)
  278.  
  279.  
  280. def pythonize(s, lower = True):
  281.     if not isinstance(s, basestring):
  282.         raise TypeError, 'Only string/unicode types can be pythonized!'
  283.     
  284.     allowed = string.letters + string.digits + '_'
  285.     s = str(s).strip()
  286.     if s.startswith('__') and s.endswith('__'):
  287.         s = s[2:-2]
  288.     
  289.     s = None if s[0] in string.digits else '' + s
  290.     s = None if keyword.iskeyword(s) else '' + s
  291.     new_s = ''
  292.     for ch in s:
  293.         None += new_s if ch in allowed else '_'
  294.     
  295.     if lower:
  296.         new_s = new_s.lower()
  297.     
  298.     return new_s
  299.  
  300. attached_functions = { }
  301.  
  302. def dyn_dispatch(obj, func_name, *args, **kwargs):
  303.     func_name = pythonize(str(func_name))
  304.     if not hasattr(obj, func_name):
  305.         fn = sys._getframe(1).f_code.co_filename
  306.         d = dict(name = func_name)
  307.         d.update(kwargs)
  308.         code = str(obj.func_templ % d)
  309.         f = open(fn, 'a')
  310.         f.write(code)
  311.         f.close()
  312.         newcode = ''
  313.         code = code.replace('\n    ', '\n')
  314.         exec code
  315.         attach_method(obj, locals()[func_name])
  316.         l = attached_functions.setdefault(obj.__class__, [])
  317.         l.append(func_name)
  318.     
  319.     if func_name in attached_functions.setdefault(obj.__class__, []):
  320.         args = [
  321.             obj] + list(args)
  322.     
  323.     return getattr(obj, func_name)(*args, **kwargs)
  324.  
  325.  
  326. class CallTemplate(string.Template):
  327.     
  328.     def __init__(self, templ):
  329.         string.Template.__init__(self, templ)
  330.         self.placeholders = [ m[1] for m in re.findall(self.pattern, self.template) ]
  331.  
  332.     
  333.     def __call__(self, *args, **kws):
  334.         return self.substitute(**primitives.dictadd(zip(self.placeholders, args), kws))
  335.  
  336.  
  337. _profilers_enabled = False
  338.  
  339. def set_profilers_enabled(val):
  340.     global _profilers_enabled
  341.     _profilers_enabled = val
  342.  
  343.  
  344. def use_profiler(target, callable):
  345.     target.profiler = EnableDisableProfiler()
  346.     
  347.     def cb():
  348.         if not _profilers_enabled:
  349.             target.profiler.disable()
  350.         
  351.         callable()
  352.  
  353.     if sys.platform == 'win32':
  354.         SEHGuard = SEHGuard
  355.         import wx
  356.     else:
  357.         
  358.         SEHGuard = lambda c: c()
  359.     (None, target.profiler.runcall)((lambda : SEHGuard(cb)))
  360.  
  361.  
  362. def all_profilers():
  363.     return dict((lambda .0: for thread in .0:
  364. if hasattr(thread, 'profiler'):
  365. (thread, thread.profiler)continue)(threading.enumerate()))
  366.  
  367.  
  368. def get_profile_report(profiler):
  369.     Stats = Stats
  370.     import pstats
  371.     StringIO = StringIO
  372.     import cStringIO
  373.     io = StringIO()
  374.     stats = Stats(profiler, stream = io)
  375.     io.write('\nby cumulative time:\n\n')
  376.     stats.sort_stats('cumulative').print_stats(25)
  377.     io.write('\nby number of calls:\n\n')
  378.     stats.sort_stats('time').print_stats(25)
  379.     return io.getvalue()
  380.  
  381. from cProfile import Profile
  382. Profile.report = get_profile_report
  383.  
  384. def profilereport():
  385.     s = []
  386.     for thread, profiler in all_profilers().iteritems():
  387.         s.extend([
  388.             repr(thread),
  389.             profiler.report()])
  390.     
  391.     return '\n'.join(s)
  392.  
  393.  
  394. class Memoize(object):
  395.     __slots__ = [
  396.         'func',
  397.         'cache']
  398.     
  399.     def __init__(self, func):
  400.         self.func = func
  401.         self.cache = { }
  402.  
  403.     
  404.     def __repr__(self):
  405.         return '<Memoize for %r (%d items)>' % (funcinfo(self.func), len(self.cache))
  406.  
  407.     
  408.     def __call__(self, *args, **kwargs):
  409.         key = (args, tuple(kwargs.items()))
  410.         cache = self.cache
  411.         
  412.         try:
  413.             return cache[key]
  414.         except KeyError:
  415.             return cache.setdefault(key, self.func(*args, **kwargs))
  416.  
  417.  
  418.  
  419. memoize = Memoize
  420.  
  421. memoizedprop = lambda getter: property(memoize(getter))
  422.  
  423. def print_timing(num_runs = 1):
  424.     
  425.     def wrapper1(func):
  426.         
  427.         def wrapper(*arg, **kwargs):
  428.             t1 = time.clock()
  429.             for i in range(num_runs):
  430.                 res = func(*arg, **kwargs)
  431.             
  432.             t2 = time.clock()
  433.             print '%s took %0.3fms.' % (func.func_name, (t2 - t1) * 1000 / float(num_runs))
  434.             return res
  435.  
  436.         return wrapper
  437.  
  438.     return wrapper1
  439.  
  440.  
  441. class i(int):
  442.     
  443.     def __iter__(self):
  444.         return iter(xrange(self))
  445.  
  446.  
  447.  
  448. def baseclasses(cls):
  449.     if not hasattr(cls, '__bases__'):
  450.         raise TypeError('%r does not have __bases__' % cls)
  451.     
  452.     bases = []
  453.     for c in cls.__bases__:
  454.         bases.append(c)
  455.         bases.extend(baseclasses(c))
  456.     
  457.     return bases
  458.  
  459.  
  460. def reload_(obj):
  461.     for klass in reversed(obj.__class__.__mro__):
  462.         if klass not in __builtins__:
  463.             reload(sys.modules[klass.__module__])
  464.             continue
  465.     
  466.     return reload2_(obj)
  467.  
  468.  
  469. def reload2_(obj):
  470.     m = sys.modules[obj.__class__.__module__]
  471.     m = reload(m)
  472.     cl = getattr(m, obj.__class__.__name__)
  473.     obj.__class__ = cl
  474.     return sys.modules[obj.__class__.__module__]
  475.  
  476.  
  477. def bitflags_enabled(map, flags):
  478.     bits = _[1]
  479.     return _[2]
  480.  
  481.  
  482. def import_module(modulePath):
  483.     aMod = sys.modules.get(modulePath, False)
  484.     if aMod is False or not isinstance(aMod, types.ModuleType):
  485.         if isinstance(modulePath, unicode):
  486.             modulePath = modulePath.encode('filesys')
  487.         
  488.         aMod = __import__(modulePath, globals(), locals(), [
  489.             ''])
  490.         sys.modules[modulePath] = aMod
  491.     
  492.     return aMod
  493.  
  494.  
  495. def import_function(fullFuncName):
  496.     if not isinstance(fullFuncName, basestring):
  497.         raise TypeError('import_function needs a string, you gave a %s' % type(fullFuncName))
  498.     
  499.     lastDot = fullFuncName.rfind(u'.')
  500.     funcName = fullFuncName[lastDot + 1:]
  501.     modPath = fullFuncName[:lastDot]
  502.     aMod = import_module(modPath)
  503.     
  504.     try:
  505.         aFunc = getattr(aMod, funcName)
  506.     except AttributeError:
  507.         e = None
  508.         log.error('%r. Module contents = %r', e, aMod.__dict__)
  509.         raise e
  510.  
  511.     return aFunc
  512.  
  513.  
  514. def base_classes(clazz):
  515.     classes = []
  516.     for cl in clazz.__bases__:
  517.         classes += [
  518.             cl] + base_classes(cl)
  519.     
  520.     return list(set(classes))
  521.  
  522. base_classes = memoize(base_classes)
  523.  
  524. def wrapfunc(obj, name, processor, avoid_doublewrap = True):
  525.     call = getattr(obj, name)
  526.     if avoid_doublewrap and getattr(call, 'processor', None) is processor:
  527.         return None
  528.     
  529.     original_callable = getattr(call, 'im_func', call)
  530.     
  531.     def wrappedfunc(*args, **kwargs):
  532.         return processor(original_callable, *args, **kwargs)
  533.  
  534.     wrappedfunc.original = call
  535.     wrappedfunc.processor = processor
  536.     wrappedfunc.__name__ = getattr(call, '__name__', name)
  537.     if inspect.isclass(obj):
  538.         if hasattr(call, 'im_self'):
  539.             if call.im_self:
  540.                 wrappedfunc = classmethod(wrappedfunc)
  541.             
  542.         else:
  543.             wrappedfunc = staticmethod(wrappedfunc)
  544.     
  545.     setattr(obj, name, wrappedfunc)
  546.  
  547.  
  548. def unwrapfunc(obj, name):
  549.     setattr(obj, name, getattr(obj, name).original)
  550.  
  551.  
  552. def tracing_processor(original_callable, *args, **kwargs):
  553.     r_name = getattr(original_callable, '__name__', '<unknown>')
  554.     r_args = [ (primitives.try_this,)((lambda : repr(a)), '<%s at %s>' % (type(a), id(a))) for None in args ]
  555.     []([ '%s-%r' % x for x in kwargs.iteritems() ])
  556.     print '-> %s(%s)' % (r_name, ', '.join(r_args))
  557.     return original_callable(*args, **kwargs)
  558.  
  559.  
  560. def add_tracing(class_object, method_name):
  561.     wrapfunc(class_object, method_name, tracing_processor)
  562.  
  563.  
  564. def trace(clz):
  565.     for meth, v in inspect.getmembers(clz, inspect.ismethod):
  566.         if not meth.startswith('__'):
  567.             add_tracing(clz, meth)
  568.             continue
  569.     
  570.  
  571.  
  572. def typecounts(contains = None, objs = None):
  573.     import gc
  574.     if objs is None:
  575.         objs = gc.get_objects()
  576.     
  577.     counts = defaultdict(int)
  578.     for obj in objs:
  579.         counts[type(obj).__name__] += 1
  580.     
  581.     if contains is not None:
  582.         
  583.         contains = lambda s, ss = contains: s[0].find(ss) != -1
  584.     
  585.     return filter(contains, sorted(counts.iteritems(), key = (lambda a: a[1]), reverse = True))
  586.  
  587.  
  588. def funcinfo(func):
  589.     if not hasattr(func, 'func_code'):
  590.         return repr(func)
  591.     
  592.     name = getattr(func, '__name__', getattr(getattr(func, '__class__', None), '__name__', '<UNKNOWN OBJECT>'))
  593.     c = func.func_code
  594.     filename = c.co_filename
  595.     if not isinstance(filename, str):
  596.         filename = '??'
  597.     else:
  598.         
  599.         try:
  600.             filepath = path(c.co_filename)
  601.             if filepath.name == '__init__.py':
  602.                 filename = filepath.parent.name + '/' + filepath.name
  603.             else:
  604.                 filename = filepath.name
  605.         except Exception:
  606.             print_exc()
  607.  
  608.     return '<%s (%s:%s)>' % (name, filename, c.co_firstlineno)
  609.  
  610.  
  611. def leakfinder():
  612.     import wx
  613.     pprint = pprint
  614.     import pprint
  615.     typecounts = typecounts
  616.     import util
  617.     import gc
  618.     f = wx.Frame(None, pos = (30, 30), style = wx.DEFAULT_FRAME_STYLE | wx.FRAME_TOOL_WINDOW | wx.STAY_ON_TOP)
  619.     b = wx.Button(f, -1, 'memory stats')
  620.     b2 = wx.Button(f, -1, 'all functions')
  621.     b3 = wx.Button(f, -1, 'all unnamed lambdas')
  622.     sz = f.Sizer = wx.BoxSizer(wx.VERTICAL)
  623.     sz.AddMany([
  624.         b,
  625.         b2,
  626.         b3])
  627.     f.stats = { }
  628.     
  629.     def onstats(e):
  630.         new = typecounts()
  631.         news = dict(new)
  632.         for cname in news.keys():
  633.             if cname in f.stats:
  634.                 diff = news[cname] - f.stats[cname][0]
  635.                 f.stats[cname] = (news[cname], diff)
  636.                 continue
  637.             f.stats[cname] = (news[cname], 0)
  638.         
  639.         print '****' * 10
  640.         pprint(sorted(f.stats.iteritems(), key = (lambda a: a[1])))
  641.  
  642.     
  643.     def on2(e, filterName = ((None, None, None), None)):
  644.         funcs = _[1]
  645.         counts = defaultdict(int)
  646.         for f in funcs:
  647.             pass
  648.         
  649.         print '((Filename, Line Number), Count)'
  650.         pprint(sorted(list(counts.iteritems()), key = (lambda i: i[1])))
  651.  
  652.     b.Bind(wx.EVT_BUTTON, onstats)
  653.     b2.Bind(wx.EVT_BUTTON, on2)
  654.     b3.Bind((wx.EVT_BUTTON,), (lambda e: on2(e, '<lambda>')))
  655.     f.Sizer.Layout()
  656.     f.Fit()
  657.     f.Show()
  658.  
  659.  
  660. def counts(seq, groupby):
  661.     counts = defaultdict(int)
  662.     for obj in seq:
  663.         counts[groupby(obj)] += 1
  664.     
  665.     return sorted((lambda .0: for val, count in .0:
  666. (count, val))(counts.iteritems()), reverse = True)
  667.  
  668.  
  669. class InstanceTracker(object):
  670.     
  671.     def track(self):
  672.         
  673.         try:
  674.             _instances = self.__class__._instances
  675.         except AttributeError:
  676.             self.__class__._instances = [
  677.                 ref(self)]
  678.  
  679.         for wref in _instances:
  680.             if wref() is self:
  681.                 break
  682.                 continue
  683.         
  684.  
  685.     
  686.     def all(cls):
  687.         objs = []
  688.         
  689.         try:
  690.             wrefs = cls._instances
  691.         except AttributeError:
  692.             return []
  693.  
  694.         import wx
  695.         for wref in wrefs[:]:
  696.             obj = wref()
  697.             if obj is not None:
  698.                 if wx.IsDestroyed(obj):
  699.                     wrefs.remove(wref)
  700.                 else:
  701.                     objs.append(obj)
  702.             wx.IsDestroyed(obj)
  703.         
  704.         return objs
  705.  
  706.     all = classmethod(all)
  707.     
  708.     def CallAll(cls, func, *args, **kwargs):
  709.         import wx
  710.         
  711.         try:
  712.             instances = cls._instances
  713.         except AttributeError:
  714.             return None
  715.  
  716.         removeList = []
  717.         for wref in instances:
  718.             obj = wref()
  719.             if obj is not None and not wx.IsDestroyed(obj):
  720.                 
  721.                 try:
  722.                     func(obj, *args, **kwargs)
  723.                 except TypeError:
  724.                     print type(obj), repr(obj)
  725.                     raise 
  726.                 except:
  727.                     None<EXCEPTION MATCH>TypeError
  728.                 
  729.  
  730.             None<EXCEPTION MATCH>TypeError
  731.             removeList.append(wref)
  732.         
  733.         for wref in removeList:
  734.             
  735.             try:
  736.                 instances.remove(wref)
  737.             continue
  738.             except ValueError:
  739.                 continue
  740.             
  741.  
  742.         
  743.  
  744.     CallAll = classmethod(CallAll)
  745.  
  746.  
  747. class DeadObjectError(AttributeError):
  748.     pass
  749.  
  750.  
  751. class DeadObject(object):
  752.     reprStr = 'Placeholder for DELETED %s object! Please unhook all callbacks, observers, and event handlers PROPERLY.'
  753.     attrStr = 'Attribute access no longer allowed - This object has signaled that it is no longer valid!'
  754.     
  755.     def __repr__(self):
  756.         if not hasattr(self, '_name'):
  757.             self._name = '[unknown]'
  758.         
  759.         return self.reprStr % self._name
  760.  
  761.     
  762.     def __getattr__(self, *args):
  763.         if not hasattr(self, '_name'):
  764.             self._name = '[unknown]'
  765.         
  766.         raise DeadObjectError(self.attrStr % self._name)
  767.  
  768.     
  769.     def __nonzero__(self):
  770.         return 0
  771.  
  772.  
  773.  
  774. def gc_diagnostics(stream = None):
  775.     import gc
  776.     import sys
  777.     import linecache
  778.     import locale
  779.     itemgetter = itemgetter
  780.     import operator
  781.     ifilterfalse = ifilterfalse
  782.     imap = imap
  783.     import itertools
  784.     getrefcount = sys.getrefcount
  785.     if stream is None:
  786.         stream = sys.stdout
  787.     
  788.     linecache.clearcache()
  789.     gc.collect()
  790.     
  791.     def w(s):
  792.         stream.write(s + '\n')
  793.  
  794.     filter_objects = ((), '')
  795.     filter_types = (type,)
  796.     objs = _[1]
  797.     itemgetter0 = itemgetter(0)
  798.     itemgetter1 = itemgetter(1)
  799.     objs.sort(key = itemgetter0)
  800.     num_objs = len(objs)
  801.     w('%d objects' % num_objs)
  802.     N = 600
  803.     notallowed = (basestring,)
  804.     import __builtin__
  805.     blacklist = set()
  806.     oldlen = 0
  807.     modlen = len(sys.modules)
  808.     while modlen != oldlen:
  809.         blacklist |= set((lambda .0: for m in .0:
  810. if m:
  811. id(m.__dict__)continue)(sys.modules.itervalues()))
  812.         for m in sys.modules.values():
  813.             if m and hasattr(m, '__docfilter__'):
  814.                 blacklist.add(id(m.__docfilter__._globals))
  815.                 continue
  816.             []
  817.         
  818.         oldlen = modlen
  819.         modlen = len(sys.modules)
  820.         continue
  821.         []
  822.     blacklist.add(id(__builtin__))
  823.     blacklist.add(id(__builtin__.__dict__))
  824.     blacklist.add(id(sys.modules))
  825.     blacklist.add(id(locale.locale_alias))
  826.     if sys.modules.get('stringprep', None) is not None:
  827.         import stringprep
  828.         blacklist.add(id(stringprep.b3_exceptions))
  829.     
  830.     blacklist.add(id(objs))
  831.     
  832.     def blacklisted(z):
  833.         if not isinstance(z, notallowed) and id(z) in blacklist:
  834.             pass
  835.         return z is blacklist
  836.  
  837.     
  838.     def blacklisted_1(z):
  839.         z = z[-1]
  840.         return blacklisted(z)
  841.  
  842.     
  843.     def large_sequence(z):
  844.         
  845.         try:
  846.             if len(z) > 300:
  847.                 pass
  848.             return not blacklisted(z)
  849.         except:
  850.             pass
  851.  
  852.  
  853.     
  854.     def saferepr(obj):
  855.         
  856.         try:
  857.             return repr(obj)
  858.         except Exception:
  859.             e = None
  860.             
  861.             try:
  862.                 return '<%s>' % type(obj).__name__
  863.             return '<??>'
  864.  
  865.  
  866.  
  867.     num_most_reffed = min(int(num_objs * 0.05), 20)
  868.     most_reffed = ifilterfalse(blacklisted_1, reversed(objs))
  869.     w('\n\n')
  870.     w('*** top %d referenced objects' % num_most_reffed)
  871.     w('sys.getrefcount(obj), repr(obj)[:1000]')
  872.     for nil in xrange(num_most_reffed):
  873.         
  874.         try:
  875.             (rcount, obj) = most_reffed.next()
  876.         except StopIteration:
  877.             (((None, None),),)
  878.             (((None, None),),)
  879.             break
  880.         except:
  881.             (((None, None),),)
  882.  
  883.         w('%d %d: %s' % (rcount, id(obj), saferepr(obj)[:1000]))
  884.     
  885.     w('\n\n')
  886.     w('*** objects with __len__ more than %d' % N)
  887.     w('__len__(obj), repr(obj)[:1000]')
  888.     large_objs = [](_[2], key = itemgetter0, reverse = True)
  889.     for count, _id, s in large_objs:
  890.         if _id != id(objs):
  891.             w('count %d id %d: %s' % (count, _id, s))
  892.             continue
  893.         []
  894.     
  895.     w('\n\n')
  896.     _typecounts = typecounts(objs = imap(itemgetter1, objs))
  897.     num_types = 20
  898.     w('*** top %d instantiated types' % num_types)
  899.     builtin_names = set(__builtins__.keys())
  900.     tc_iter = (sorted, ifilterfalse)((lambda _x: builtin_names.__contains__(itemgetter0(_x))), _typecounts)
  901.     for nil in range(num_types):
  902.         
  903.         try:
  904.             (tname, tcount) = tc_iter.next()
  905.         except StopIteration:
  906.             (((None, None),),)
  907.             (((None, None),),)
  908.             break
  909.         except:
  910.             (((None, None),),)
  911.  
  912.         w('%d: %r' % (tcount, tname))
  913.     
  914.     funcinfos = defaultdict(int)
  915.     for refcount, obj in objs:
  916.         if callable(obj):
  917.             
  918.             try:
  919.                 finfo = funcinfo(obj)
  920.             except:
  921.                 (((None, None),),)
  922.                 continue
  923.  
  924.             funcinfos[finfo] += refcount
  925.             continue
  926.         (((None, None),),)
  927.     
  928.     num_infos = min(len(funcinfos), 20)
  929.     funcinfos = funcinfos.items()
  930.     funcinfos.sort(key = itemgetter1, reverse = True)
  931.     w('\n\n')
  932.     w('*** %d most referenced callables' % num_infos)
  933.     for i in range(num_infos):
  934.         (finfo, frcount) = funcinfos[i]
  935.         w('%d: %r' % (frcount, finfo))
  936.     
  937.     
  938.     try:
  939.         import wx
  940.     except ImportError:
  941.         pass
  942.  
  943.     w('\n\n*** top level windows')
  944.     for tlw in wx.GetTopLevelWindows():
  945.         w(' - '.join((saferepr(tlw), saferepr(tlw.Name))))
  946.     
  947.     w('\n\n*** gc.garbage')
  948.     if not gc.garbage:
  949.         w('(none)')
  950.     else:
  951.         for obj in gc.garbage:
  952.             w(saferepr(obj))
  953.         
  954.  
  955. import cProfile
  956. import _lsprof
  957.  
  958. class EnableDisableProfiler(cProfile.Profile):
  959.     
  960.     def __init__(self, *a, **k):
  961.         self.enabled = False
  962.         _lsprof.Profiler.__init__(self, *a, **k)
  963.  
  964.     
  965.     def enable(self):
  966.         self.enabled = True
  967.         return _lsprof.Profiler.enable(self)
  968.  
  969.     
  970.     def disable(self):
  971.         self.enabled = False
  972.         return _lsprof.Profiler.disable(self)
  973.  
  974.  
  975. if __name__ == '__main__':
  976.     from pprint import pprint
  977.     pprint(typecounts('Graphics'))
  978.  
  979.