Is there a way to get the following code:
import traceback def log(message): print "%s: %s" %(traceback.extract_stack()[0:-1][-1][2], message) def f1(): log("hello") class cls(object): def f1(self): log("hi there") f1() mycls = cls() mycls.f1()
displayed:
f1: hello cls.f1: hi there
instead:
f1: hello f1: hi there
?
I tried to use the check module, but was not successful ...
Julien
EDIT:It indicates that the "log" function can retrieve the caller (using tracing, checking, or any average value).I do not want to pass the class name or anything other than a "message" to the "log" function.
EDIT:
It indicates that the "log" function can retrieve the caller (using tracing, checking, or any average value).
I do not want to pass the class name or anything other than a "message" to the "log" function.
So, I finally came up with this method:
#!/usr/bin/env python3 def log(message): import inspect import gc code = inspect.currentframe().f_back.f_code func = [obj for obj in gc.get_referrers(code) if inspect.isfunction(obj)][0] print(func.__qualname__, message)
He needs python3 so that __qualname__ can be used.
inspect , traceback , , . , self, /:
traceback
self
import inspect class cls(object): def f1(self): this_class_name = type(self).__name__ this_func_name = inspect.currentframe().f_code.co_name print(this_class_name, this_func_name) mycls = cls() mycls.f1()