How to get a function name as a string?

后端 未结 12 2083
后悔当初
后悔当初 2020-11-22 04:35

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         


        
12条回答
  •  后悔当初
    2020-11-22 04:50

    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():
    

提交回复
热议问题