#
# This file is part of adzapper
# Copyright 1999 - 2001 Adam Feuer <adamf@pobox.com>
#
# adzapper is free software; you can redistribute it and/or modify
# it under the terms of the Python License, as published by the
# Python Software Foundation.
#
# adzapper is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# Python License for more details.
#
# You should have received a copy of the Python License along
# with adzapper; see the file COPYING.
#
# rudimentary debug module
#

RCS_ID =  '$Id: debug.py,v 1.2 2001/09/02 04:47:16 adamf Exp $'

from types import *

debuglevel = 0
log_info_threshold = 2
log_threshold = 3

def debug(level,message):
    """print a debugging message, depending on what debuglevel has be set to"""
    if (level <= debuglevel):
        if type(message) == StringType :
            print "%s" % message
        elif type(message) == IntType:
            print(message)
        elif type(message) == ListType:
            for item in message:
                print item,
            print
        elif type(message) == TupleType:
            for item in message:
                print item,
            print
        else:
            pass



# used to override the asyncore.dispatcher method
def log_info (self,message, type='info'):
    #if __debug__ or type != 'info':
    #    print '%s: %s' %(type, message)
    debug(log_info_threshold,"%s: %s" % (type,message))


# used to override the asyncore.dispatcher method
def log (message):
    debug(log_threshold,"%s" % message)



import sys
import types

def get_refcounts():
    d = {}
    sys.modules
    # collect all classes
    for m in sys.modules.values():
        for sym in dir(m):
            o = getattr (m, sym)
            if type(o) is types.ClassType:
                d[o] = sys.getrefcount (o)
    # sort by refcount
    pairs = map (lambda x: (x[1],x[0]), d.items())
    pairs.sort()
    pairs.reverse()
    return pairs

def get_top_refcounts(number):
    """return a string with info about objects with highest reference counts--
    useful for debugging memory leaks."""
    s = "Top %d objects with highest reference counts: \n\n" % number
    for n, c in get_refcounts()[:number]:
        s = s + '%10d %s\n' % (n, c.__name__)    
    return s

if __name__ == '__main__':
    top_100()

