1

I am trying to design a print function dprint for debugging use. Specifically, this is what I want to achieve:

def func1(a,b,debug=0):
    if debug:
        print(Something) # print something if debug mode

below is how I design the dprint

def func2(a,b,debug=0):
    def dprint(*args):  
        if debug:
            print(*args)  # using the local variable `debug` to detect whether is under debug mood
    dprint(Something) # print something if debug mode

func2 can work but is not nice since I need to insert the dprint function into every other function. I wonder if there is a more decent way to achieve this dprint function.

Garvey
  • 1,197
  • 3
  • 13
  • 26
  • 1
    why dont you use python logging module? – balderman Dec 08 '20 at 16:30
  • 1
    I can't understand your code... Why `func2`, `func1` and `dprint`? And yes, why aren't you using the built-in functionality of [`logging`](https://docs.python.org/3/library/logging.html)? i.e. [`logger.debug`](https://docs.python.org/3/library/logging.html#logging.Logger.debug) – Tomerikoo Dec 08 '20 at 16:34

2 Answers2

1

You can use a global variable debug instead of a parameter and make dprint its own function.

debug = True
def dpring(*args, **kwargs):
    if debug:
        print(*args, **kwargs)

def func2(a, b):
    dprint(Somthing)
# OR
def func2(a, b, debug_=0):
    global debug # not necesary but IMO it makes the code more readable
    debug = bool(debug_)
    dprint(Something)

Roy Cohen
  • 1,540
  • 1
  • 5
  • 22
0

Use the decorator:

def dprint(func):
    def _f(*args, **kwargs):
        if kwargs.get('debug',0) == 1:
            print('Something')
        return func(*args, **kwargs)
    return _f
    
@dprint    
def f(a, b, debug=0):
    print(a, b)   

In this case you only need to add a @dprint on all the functions you want this feature.

Z Li
  • 4,133
  • 1
  • 4
  • 19
  • I feel he only wants to have a function that prints to show this function is running in debug mode. – Z Li Dec 08 '20 at 16:46
  • Oh well the question is not very clear so that might be the case. I will delete my comments and let OP judge – Tomerikoo Dec 08 '20 at 16:48
  • yes I think this is how he plans to use it...in his post he said he was going to add this function in all the functions with a debug kwarg – Z Li Dec 08 '20 at 16:48
  • I don't see any mentioning for a debug `kwarg` in the question... – Tomerikoo Dec 08 '20 at 16:49
  • A nice addition can be to make the debug message an argument to the decorator so each function can have a different message – Tomerikoo Dec 08 '20 at 16:50