Python Forum
Thread Rating:
  • 1 Vote(s) - 2 Average
  • 1
  • 2
  • 3
  • 4
  • 5
dppvzz.py
#1
this is the code that originated the pv() function that was the subject of the UnboundLocalError (that thread is here) exceptions i was getting that didn't match the descriptions of UnboundLocalError (in python documentation and other places google found).  these functions are inserted into the code (not imported) during debugging to make it easier to (add temporary debug code to) print out additional state messages to in the debugging.  i have modified this code to include code to block these messages based on the setting of environment variable "nodebug" done in a way to avoid the UnboundLocalError exception.  the test and definition of the donothing function is done in the same namespace as where the original functions are defined.

pv() takes a variable number of positional arguments, each of which is a string naming a variable in the caller's local namespace, or a variable in the global namespace.  it prints out which space the name was found in, the name itself, and the value.  attributes appended to the name are supported, so pv('self.foo') would look in "self" for "foo".  if the name is not found in either namespace, this is reported.

dp() acts like print, except that it can be suppressed by the "nodebug" environment variable like pv() is.

zz() is a sleep tool (the "nodebug" environment variable makes it not sleep) to pause the program where desired to make it easier to read the other messages.  it is given the number of seconds to sleep.  it also flushes sys.stdout so other buffered output is not held back during the delay.

all output is to sys.stderr unless the file= named option is used on the call to output elsewhere.  other options are also passed along to the print() call.

when done debugging, set debug = False until you get all the dp(), pv() and zz() calls removed from your code.

#-------#-------#-------#-------#-------#-------#-------#-------#-------#-------#
# Copyright © 2017, by Phil D. Howard - all other rights reserved
# 
# Permission to use, copy, modify, and/or distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
# 
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
# WHATSOEVER RESULTING FROM LOSS OF USE, DATA, OR PROFITS, WHETHER IN AN
# ACTION OF CONTRACT, NEGLIGENCE, OR OTHER TORTIOUS ACTION, ARISING OUT OF
# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
# 
# The author may be contacted by decoding the number
# 10054452614123394844460370234029112340408691
# (provu igi la numeron al duuma)
#
# these comments do not need to be inserted into the code file(s) being debugged.
#-------#-------#-------#-------#-------#-------#-------#-------#-------#-------#
# these functions do nothing if the lower case 'nodebug' environment variable is
# set, else dp() does printing, pv() prints a named variable and zz() sleeps some
# seconds.  remove this code and the embedded calls when done debugging.
# remove or trim the imports below for modules already globally imported.
#-------#-------#-------#-------#-------#-------#-------#-------#-------#-------#
#        111111111122222222223333333333444444444455555555556666666666777777777788
#23456789012345678901234567890123456789012345678901234567890123456789012345678901
#-------#-------#-------#-------#-------#-------#-------#-------#-------#-------#
import os,sys,time
nodebug = os.environ.get('nodebug',False)
ex = BrokenPipeError if sys.version_info.major > 2 else IOError
stderr = sys.stderr

if nodebug:
   def dp(*msg,**opt):
       """Do nothing if 'nodebug' environment variable is set"""
       return 0
else:
   def dp(*out,**opt):
       """Print whatever if 'nodebug' environment variable is not set"""
       opt['file'] = opt.get('file',stderr)
       try:
           rc = print(*out,**opt)
           opt['file'].flush()
       except ex:
           pass
       return rc

if nodebug:
   def pv(*names,**opt):
       """Do nothing if 'nodebug' environment variable is set"""
       return
else:
   def pv(*names,**opt):
       """Print a named variable if 'nodebug' environment variable is not set"""
       from inspect import currentframe
       try:
           opt['file'] = opt.get('file',sys.stderr)
           f = currentframe().f_back
           l, g = f.f_locals, f.f_globals
           for name in names:
               s = name.split('.')
               n = s.pop(0)
               if n in l:
                   o, v = '... local var:', l[n]
               elif n in g:
                   o, v = '.. global var:', g[n]
               else:
                   print('............. ',
                         str(name),
                         'not assigned in local or global namespace',
                         **opt)
                   opt['file'].flush()
                   continue
               while s:
                   m = s.pop(0)
                   if m in dir(v):
                       v, n = getattr(v,m), n + '.' + m
                   else:
                       break
               print(o,repr(n),'=',repr(v),**opt)
               opt['file'].flush()
               continue
       except ex:
           pass
       return

if nodebug:
   def zz(secs):
       """Do nothing if 'nodebug' environment variable is set"""
       return 0
else:
   def zz(secs):
       """sleep some seconds if 'nodebug' environment variable is not set"""
       opt.get('file',stdout).flush()
       return time.sleep(secs)

#        111111111122222222223333333333444444444455555555556666666666777777777788
#23456789012345678901234567890123456789012345678901234567890123456789012345678901
#-------#-------#-------#-------#-------#-------#-------#-------#-------#-------#
# EOF
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020