How to write verbose scripts

Mensanator mensanator at aol.com
Tue Sep 2 19:52:58 CEST 2008


On Sep 2, 11:55 am, Steven D'Aprano <st... at REMOVE-THIS-
cybersource.com.au> wrote:
> I find myself writing command line tools in Python where I wish to
> include "verbose" output to stdout.
>
> I start with a helper function:
>
> def print_(obj, level=0):
>     if _verbosity >= level:
>         print obj
>
> And then I end up with functions or methods looking like this:
>
> def parrot(x)
>     print_("precondition", level=2)
>     do_something()
>     print_("status is good...", level=1)
>     print_("parrot is squawking strongly now", level=2)
>     do_something_else()
>     print_("squawk squawk squawk", level=3)
>     do_more()
>     print_("postcondition", level=1)
>     return something
>
> That often means that my functions end up with more message printing code
> than actual code. The whole thing seems messy and hard to manage for all
> but the smallest scripts.
>
> Worst of all, sometimes the messages I wish to print may be expensive to
> compute, and I don't want to waste time computing them if they aren't
> going to be printed because the verbosity is too low. But nor do I wish
> to fill my code with this:
>
> if _verbosity >= 3:
>     x = calculate_complicated_thing()
>     print_(x, level=3)
>
> Is there a better way of doing this than the way I am going about it?

I do something like this, although I don't know if it would
be an improvement.

def collatz(a,p):
  """ 3x+1 sequencer, no loop detection

  collatz(a,p)
  a: starting value
  p: print options (binary)
     bit 0 print even numbers (turns off power division)
     bit 1 print  odd numbers
     bit 2 print debug (if any)
  returns: CollatzSequenceParameters [R1count, R2count]
  """
  ONE = gmpy.mpz(1)
  TWO = gmpy.mpz(2)
  TWE = gmpy.mpz(3)
  a = gmpy.mpz(a)
  t = 0
  u = 0
  done = 0

  if (p & 1)==1:
    print_evens = True
  else:
    print_evens = False
  if (p & 2)==2:
    print_odds = True
  else:
    print_odds = False
  if (p & 4)==4:
    print_debug = True
  else:
    print_debug = False

  while done==0:
    f = gmpy.scan1(a,0) # locate LS 1-bit
    if f>0:             # it's even
      if print_evens:
        print a,
        a = a >> 1      # no power division
        u += 1
      else:
        a = a >> f      # power division
        u += f
    else:
      if print_odds:
        print a,
      if a==1:
        done = 1
        seq_end = t + u
      else:
        a = a*TWE + ONE
        t += 1
  return [u,t]



>
> --
> Steven




More information about the Python-list mailing list