from types import FunctionType, MethodType
import sys

class reporter(type):
	'''
		a metaclass to use during debugging
		I will print out the methods and their arguments as objects are being used...
		
		TO USE:
			>>> class YourClass(object):
			...	if __debug__:
			...		__metaclass__ = reporter
			...	def test (self, arg):
			...		print arg
			...
			>>> x = YourClass()
			>>> x.test()
		
		CUSTOMIZATION:
			+ if you want to report on private methods (those starting with '_'), then
				set SHOWPRIVATE to 1		
			+ if you want the base classes to also be reported on, set WRAPBASES to
				anything greater than 0
			+ if you want to change the way things are printed out, alter the MAX and
				MAXARG attributes	
	'''
	MAX=60  #  max line length of method args
	MAXARG = 24  #  max length of individual arg
	SHOWPRIVATE = 0  #  set true to wrap methods starting with '_'
	WRAPBASES = 0  #  set true to wrap the class' bases, too
	LOGGER = sys.stdout
	
	def __init__ (klass, name, bases, d):
		if reporter.WRAPBASES:
			def wrapBase (base, depth=0):
				reporter.wrapKlass(klass, base, base.__name__, base.__bases__, base.__dict__)
			#	XXX -- this doesn't work right now...
			#	for b in base.__bases__:
			#		if depth <= reporter.WRAPBASES:
			#			wrapBase(b, depth+1)
			for b in bases:
				wrapBase(b, 1)
		super(reporter, klass).__init__ (klass, name, bases, d)
		reporter.wrapKlass(klass, klass, name, bases, d)

	def wrapKlass (me, klass, name, bases, d):
		'''wrap each of the functions in klass with a modified version of the function'''
		for attr, value in d.items():
			if type(value) in (FunctionType, MethodType) and \
					(reporter.SHOWPRIVATE or not attr.startswith('_')):
				reporter.wrapFunction(me, value)
				reporter.LOGGER.write( '''reporter --> watching %s's %s method.\n''' % (name, attr) )
	
	def wrapFunction(klass, f, prefix='_f_'):
		'''wrap a given function with a prefix within the given class'''
		setattr(klass, prefix+f.func_name, f)
		def call(self, *args, **kw):
			x = str((args, kw))
			if len(x) > reporter.MAX:
				x = reporter.buildShortArgs(klass, *args, **kw)
			reporter.LOGGER.write( '''reporter ---> %s.%s%s\n''' % (klass.__name__, f.func_name, x) )
			return getattr(klass, prefix+f.func_name)(self, *args, **kw)
		call.__doc__ = '''[wrapped '%s%s']\n\t%s''' % (prefix, f.func_name, f.__doc__)
		setattr(klass, f.func_name, call)
	
	def buildShortArgs(klass, *args, **kw):
		'''return a short/pretty version of args and kw'''
		output = []
		for item in args:
			item = `item`
			if len(item) > reporter.MAXARG:
				item = item[:(reporter.MAXARG-3)]+'...'+item[-1]
			output.append(item)
		for key, value in kw.items():
			value = `value`
			if len(value) > reporter.MAXARG:
				value = value[:(reporter.MAXARG-3)]+'...'+item[-1]
			output.append('%s=%s' % (key, value))
		return '(%s)' % ', '.join(output)


test = '''\
x = YourClass('me!')
x.test('hello')
x.test('hello', there='there!')
x.test('hello')
#
# -- subclassing older classes...
#
reporter.SHOWPRIVATE = 1
reporter.WRAPBASES = 1
#
from httplib import HTTPConnection as H
class MyHTTP(H, object): __metaclass__ = reporter
conn = MyHTTP('www.python.org')
conn.request('GET', '/index.html')
r = conn.getresponse()
print r.status, r.reason
data = r.read()
conn.close()
print data[:100]'''

if __name__ == '__main__':

	class YourClass:
		'''test class'''
		__metaclass__ = reporter
		def __init__ (self, name):
			self.name = name
		def test(self, arg, **kw):
			print arg, kw.get('there', '?')

	for line in test.split('\n'):
		print '>>>', line
		exec line in globals()

