I was playing around with the inspect module the other day trying to write a quick and dirty "smart" logger. By this I mean that writing a message to the global log would also yield some info about the calling scope. If you look at my function "test" below, I'd ideally like log messages:
foo.py:test, "message 1" foo.py:Foo.__init__, "message 2" foo.py:Foo.bar, "message 3" For the life of me I can't figure out how to get this info without resorting to ridiculous things like parsing the source code (available via inspect.stack. Any help would be much appreciated - my unit tests are failing on this at the moment ;-) Cheers, Darran. #------------ foo.py --------------------------------- import inspect class Log: def __init__(self): pass def write(self, msg): print "------------------------------------------------------------" print msg print "------------------------------------------------------------" cframe, cmodule, cline, cfunction, csrc, tmp = inspect.stack()[1] print inspect.stack() # I want to determine if cfunction is a regular function or a class method. # If the latter, what is the name of the class? del cframe def test(): log = Log() log.write('message 1) class Foo: def __init__(self): log.write('message 2') def bar(self): log.write('message 3') f = Foo() f.bar() test() #--------------------- end of foo.py -------------- -- http://mail.python.org/mailman/listinfo/python-list