In Python, how do I get a function name as a string, without calling the function?
def my_function():
pass
print get_function_name_as_string(my_function
I've seen a few answers that utilized decorators, though I felt a few were a bit verbose. Here's something I use for logging function names as well as their respective input and output values. I've adapted it here to just print the info rather than creating a log file and adapted it to apply to the OP specific example.
def debug(func=None):
def wrapper(*args, **kwargs):
try:
function_name = func.__func__.__qualname__
except:
function_name = func.__qualname__
return func(*args, **kwargs, function_name=function_name)
return wrapper
@debug
def my_function(**kwargs):
print(kwargs)
my_function()
Output:
{'function_name': 'my_function'}