meta-class review

MRAB python at mrabarnett.plus.com
Wed Oct 6 02:16:27 CEST 2010


On 06/10/2010 00:17, Ethan Furman wrote:
 > On one the many mini-reports we use, we have a bunch of counts that
 > are frequently zero; because the other counts can also be low, it
 > becomes easy to miss the non-zero counts.  For example:
 >
 > Code  Description
 >
 >       Conv Errors              :       6
 >
 > 31,N  DPV Failure              :       4
 > 10:   Invalid Address          :       0
 > 11:   Invalid C/S/Z            :       0
 > 12:   Invalid State            :       0
 > 13:   Invalid City             :       0
 > 17:   Insufficient Information :       0
 > 33:   Non-Deliverable          :       0
 > 98:   Non-USPS zip             :       0
 >
 > 21:   Address Not Found        :       0
 > 22:   Multiple Responses       :       3
 > 23:   Error in Primary         :       0
 > 24:   Error in Secondary       :       0
 >
 >
 > So I thought I would print '-' instead...
 >
 > Code  Description
 >
 >       Conv Errors              :       6
 >
 > 31,N  DPV Failure              :       4
 > 10:   Invalid Address          :       -
 > 11:   Invalid C/S/Z            :       -
 > 12:   Invalid State            :       -
 > 13:   Invalid City             :       -
 > 17:   Insufficient Information :       -
 > 33:   Non-Deliverable          :       -
 > 98:   Non-USPS zip             :       -
 >
 > 21:   Address Not Found        :       -
 > 22:   Multiple Responses       :       3
 > 23:   Error in Primary         :       -
 > 24:   Error in Secondary       :       -
 >
 >
 > Much easier to pick out the numbers now.  To support this, the code
 > changed slightly -- it went from
 >
 > '%-25s: %7d' % ('DPV Failure', counts['D'])
 >
 > to
 >
 > '%-25s: %7s' % ('DPV Failure', counts['D'] if counts['D'] else '-'))
 >
 > This became a pain after a dozen lines, prompting my previous
 > question about the difference between %s and %d when printing
 > integers.  With the excellent replies I received I coded a short
 > class:
 >
 > [snip]
 > Any comments appreciated, especially ideas on how to better handle
 > class- and staticmethods
 >
I think that's a bit of overkill. The problem lies in the printing
part, but you're spreading the solution into the rest of the
application! (A case of the tail wagging the dog, perhaps? :-))

IMHO you should just use a simple function when printing:

def dash_zero(x):
     return str(x) if x else '-'

...

'%-25s: %7s' % ('DPV Failure', dash_zero(counts['D']))



More information about the Python-list mailing list