home *** CD-ROM | disk | FTP | other *** search
/ Maximum CD 2011 February / maximum-cd-2011-02.iso / DiscContents / digsby_setup85.exe / lib / util / introspect.pyo (.txt) < prev    next >
Encoding:
Python Compiled Bytecode  |  2010-11-24  |  31.6 KB  |  1,041 lines

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