Is there a way so that 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()
displays:
f1: hello
cls.f1: hi there
instead of:
f1: hello
f1: hi there
?
I tried to use module 'inspect' but was not successful...
Julien
EDIT:
The point here is for 'log' function to be able to retrieve its caller name on its own (using traceback, inspect, or any mean necessary).
I do not want to pass the class name, or anything else than 'message' to the 'log' function.
Practical Data Science using Python The asterisk (star) operator is used in Python with more than one meaning attached to it. For numeric data types, * is used as multiplication operator >>> a=10;b=20 >>> a*b 200 >>> a=1.5; b=2.5; >>> a*b 3.75 >>> a=2+3j; b=3+2j >>> a*b 13j.
Method 1: Get Function Name in Python using function. func_name.
The __name__ variable (two underscores before and after) is a special Python variable. It gets its value depending on how we execute the containing script. Sometimes you write a script with functions that might be useful in other scripts as well. In Python, you can import that script as a module in another script.
So I finally came up 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)
It needs python3 so that __qualname__ can be used.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With