2

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.

2
  • 2
    Possible duplicate of Determine function name from within that function (without using traceback) Commented Apr 18, 2018 at 14:30
  • 3
    If you use the logging module to produce this type of output, you can use the format string '%(funcName)s ...', and the logged message will include the name of the function. Commented Apr 18, 2018 at 14:40

3 Answers 3

8

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
Sign up to request clarification or add additional context in comments.

1 Comment

Very nice solution! The first time I really see the benefits of decorators and will finally use them :)
2

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

1 Comment

Very nice solution too!
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.