Basj
Basj

Reputation: 46353

Print function name in the function itself

I have many functions like:

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

    ... the actual code here ...

    print "DBworker_thatdoes_job7 finished."

How to do this without hardcoding the function names? Here is what I want to achieve:

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

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

Note: I've already looked at How to get a function name as a string in Python? but I don't really see a nice way to do it here. Also, this question is close to Determine function name from within that function (without using traceback) but here applied to the specific use case of function-name logging at startup and end, thus not exactly a duplicate.

Upvotes: 2

Views: 1484

Answers (3)

0x5453
0x5453

Reputation: 13599

Perhaps a decorator?

def log_function_start(fn):
    def wrapper(*args, **kwargs):
        print '{} starting...'.format(fn.__name__)
        fn(*args, **kwargs)
    return wrapper

@log_function_start
def DBworker_thatdoes_job7():
    ...

Upvotes: 2

hiro protagonist
hiro protagonist

Reputation: 46921

you could use a decorator:

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

this prints:

starting function
function body
finished function

Upvotes: 8

timgeb
timgeb

Reputation: 78780

You have more leeway to customize your function if you manually implement a callable, i.e. by creating a class with a __call__ method.

>>> class foo(object): # or class foo: in Python 3
...     def __call__(self):
...         # your logic goes here
...         print(type(self).__name__)
... 
>>> foo = foo()
>>> foo()
foo

Upvotes: 0

Related Questions