Get Current Function Name Inside That Function Using Python
For my logging purpose i want to log all the names of functions where my code is going Does not matter who is calling the function , i want the the function name in which i declare
Solution 1:
For my logging purpose i want to log all the names of functions where my code is going
Have you considered decorators?
import functools
deflogme(f):
@functools.wraps(f)defwrapped(*args, **kwargs):
print(f.__name__)
return f(*args, **kwargs)
return wrapped
@logmedefmyfunction():
print("Doing some stuff")
Solution 2:
Call sys._getframe()
to get a frame
class instance. The f_code.co_name
member holds the function name.
sys._getframe(0).f_code.co_name
Add a simple helper function func_name()
to wrap the call
import sys
def func_name():
return sys._getframe(1).f_code.co_name
def func1():
print(func_name())
func1() # prints 'func1'
Solution 3:
This simple reusable method returns a name of the caller/parent function:
def current_method_name():
# [0] isthis method's frame, [1] is the parent's frame - which we want
return inspect.stack()[1].function
Example:
def whoami():
print(current_method_name())
whoami()
-> output iswhoami
Solution 4:
Adding an answer here as it can be useful to include the class name as well as the function.
This checks for self
and cls
convention, to include the class name.
defname_of_caller(frame=1):
"""
Return "class.function_name" of the caller or just "function_name".
"""
frame = sys._getframe(frame)
fn_name = frame.f_code.co_name
var_names = frame.f_code.co_varnames
if var_names:
if var_names[0] == "self":
self_obj = frame.f_locals.get("self")
if self_obj isnotNone:
returntype(self_obj).__name__ + "." + fn_name
if var_names[0] == "cls":
cls_obj = frame.f_locals.get("cls")
if cls_obj isnotNone:
return cls_obj.__name__ + "." + fn_name
return fn_name
Post a Comment for "Get Current Function Name Inside That Function Using Python"