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 like using a function decorator. I added a class, which also times the function time. Assume gLog is a standard python logger:
class EnterExitLog():
def __init__(self, funcName):
self.funcName = funcName
def __enter__(self):
gLog.debug('Started: %s' % self.funcName)
self.init_time = datetime.datetime.now()
return self
def __exit__(self, type, value, tb):
gLog.debug('Finished: %s in: %s seconds' % (self.funcName, datetime.datetime.now() - self.init_time))
def func_timer_decorator(func):
def func_wrapper(*args, **kwargs):
with EnterExitLog(func.__name__):
return func(*args, **kwargs)
return func_wrapper
so now all you have to do with your function is decorate it and voila
@func_timer_decorator
def my_func():