Python Forum
snippet: dp and pv - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: General (https://python-forum.io/forum-1.html)
+--- Forum: Code sharing (https://python-forum.io/forum-5.html)
+--- Thread: snippet: dp and pv (/thread-2764.html)



snippet: dp and pv - Skaperen - Apr-08-2017

i have this saved as dppv,py ready to insert into projects where i need this level of debugging.  the dp() function is just like print except that if environment variable nodebug (lower case) is set it becomes quiet and its different name makes it easier to hunt them down to remove them when you are done with them.  the value of the nodebug environment variable is to get q quick look at the output without the dp() output.  the pv() is to show a variable.  it will output both the name and value given only the name (string) as well as indicating if the variable is local or global.  if it is not assigned, it will say the.

def dp(*msg,**opt):
    """Print for debugging.

function        dp
purpose         print for debugging.
note            if environment variable 'nodebug' is set then no printing
                will happen.
"""
    from os import environ
    if 'nodebug' in environ:
        return 0
    if 'file' not in opt:
        from sys import stderr as default_file
        opt['file']=default_file
    try:
        rc=print(*msg,**opt)
        opt['file'].flush()
    except BrokenPipeError:
        pass
    return rc

def pv(*names,**opt):
    """Print a variable name and value.



function        pv
purpose         print a variable name and value.
arguments       each a string of the variable name to print
note            begin the string with '#' to skip this variable
note            begin the string with '=' to print what follows
"""
    from inspect import currentframe
    if 'file' not in opt:
        from sys import stderr as default_file
        opt['file']=default_file
    for x in names:
        if not isinstance(x,(list,tuple)):
            x=[x]
        for name in x:
            name=str(name)
            if name[0]=='#':
                continue
            if name[0]=='=':
                print('===',name[1:])
            l=currentframe().f_back.f_locals
            g=currentframe().f_back.f_globals
            try:
                if name in l:
                    print('... local var:',str(name),'=',repr(l[name]),**opt)
                elif name in g:
                    print('.. global var:',str(name),'=',repr(g[name]),**opt)
                else:
                    print('............. ',str(name),'not assigned',**opt)
                opt['file'].flush()
            except BrokenPipeError:
                return
    return