在函数本身中打印函数名称

Bas*_*asj 2 python function

我有很多功能,例如:

def DBworker_thatdoes_job7():
    print "DBworker_thatdoes_job7 starting..."

    ... the actual code here ...

    print "DBworker_thatdoes_job7 finished."
Run Code Online (Sandbox Code Playgroud)

如何在不硬编码函数名称的情况下执行此操作?这是我想要实现的目标:

def DBworker_thatdoes_job7():
    print thisfunction.name + " starting..."
    ...

def DBworker_thatdoes_cleaning18():
    print thisfunction.name + " starting..."
    ...
Run Code Online (Sandbox Code Playgroud)

注意:我已经看过如何在 Python 中将函数名作为字符串获取?但我真的没有看到在这里做这件事的好方法。此外,这个问题接近于在该函数内确定函数名称(不使用回溯),但这里适用于启动和结束时函数名日志记录的特定用例,因此不完全是重复的。

hir*_*ist 6

你可以使用装饰器:

def start_finish(f):
    def new_f(*args, **kwargs):
        print("starting", f.__name__)
        f(*args, **kwargs)
        print("finished", f.__name__)
    return new_f

@start_finish
def function():
    print('function body')

function()
Run Code Online (Sandbox Code Playgroud)

这打印:

starting function
function body
finished function
Run Code Online (Sandbox Code Playgroud)