Search code examples
pythonpython-2.7debuggingprintingverbose

How do I print start and end of function with verbose, Python?


I've written a nice chunk of code, and I'm looking to improve my verbose output. I had the idea of an if verbose: print '**** function_name ****' at the start and end of the function and even defined a function to make it easier to call (I'm using the very sexy verbose print written by kindall here)

def verbwrap(function, side):
    if side=='start':
        verboseprint(' ******  %s  ******' %(function))
    if side=='end': 
        verboseprint(' ^^^^^^  %s  ^^^^^^' %(function))

with the intention of using it like this:

import inspect

def test(lst):
    verbwrap(inspect.currentframe().f_code.co_name,'start')
    for i in lst:
        print i
    verbwrap('test', 'end') #equivalent to above, but easier to write :(

Is there a way for me to only call a re-worked verbwrap() once? No amount of tinkering has led me to the answer!


Solution

  • Considering you want to print something only at the start and end of the function then the best way to do this is to use a decorator.

    def verbwrap(function):
        def wrapper(*args, **kwargs):
            verboseprint(' ******  %s  ******' %(function.__name__))
            result = function(*args, **kwargs)
            verboseprint(' ^^^^^^  %s  ^^^^^^' %(function.__name__))
            return result
        return wrapper
    

    Now use the above decorator with any function you want to debug:

    @verbwrap
    def test(lst):
        for i in lst:
            print i
    

    Demo:

    When verbose is True:

     ******  test  ******
    1
    2
    3
     ^^^^^^  test  ^^^^^^
    

    When verbose is False:

    1
    2
    3
    

    You can make this even more dynamic by calculating the value of verbose inside the wrapper function, using this approach you can decide to debug or not to debug when the function is actually invoked.

    def verbwrap(function):
        def wrapper(*args, **kwargs):
            # Calculate the value of `verbose` here.
            # Say you're reading it from a config etc
            verbose = False
            if verbose:
                print ' ******  %s  ******' %(function.__name__)
                result = function(*args, **kwargs)
                print ' ^^^^^^  %s  ^^^^^^' %(function.__name__)
                return result
            else:
                return function(*args, **kwargs)
        return wrapper