Is there a more elegant way to handle determing fail status?

Steven D'Aprano steve+comp.lang.python at pearwood.info
Tue Jan 15 21:55:52 EST 2013


On Tue, 15 Jan 2013 18:24:44 -0500, J wrote:


> The problem is that my exit determination looks like this:
> 
>     if fail_priority == fail_levels['FAILED_CRITICAL']:
>         if critical_fails:
>             return 1
>     if fail_priority == fail_levels['FAILED_HIGH']:
>         if critical_fails or high_fails:
>             return 1
>     if fail_priority == fail_levels['FAILED_MEDIUM']:
>         if critical_fails or high_fails or medium_fails:
>             return 1
>     if fail_priority == fail_levels['FAILED_LOW']:
>         if critical_fails or high_fails or medium_fails or low_fails:
>             return 1
>     return 0


Here's a general solution that doesn't require the failure levels to be 
numbers, or listed in order, or to support any operation except equality 
testing.

Start with an ordered list of failure severity levels, and an equivalent 
ordered list of failure counts. Find the offset of the requested failure 
level in the FAILURES list. Then inspect the failure counts, up to and 
including that offset, ignoring any failure outside of that range:


failures = [FAILED_CRITICAL, FAILED_HIGH, FAILED_MEDIUM, FAILED_LOW]
counts = [critical_fails, high_fails, medium_fails, low_fails]
i = failures.index(fail_priority)
if any(counts[:i+1]):
    print "Failed"
else:
    print "No failures that we care about"


The actual values for FAILED_CRITICAL etc. can be arbitrary values: 
integers *in any order*, strings, complicated records, anything so long 
as they support equality and are distinct. fail_priority must be set to 
one of those values.


> the variables critical_fails, high_fails, medium_fails, low_fails are
> all counters that are etiher None, or the number of tests that were
> failed.

Why set them to None when no tests failed? If no tests failed, why not 
just use 0?

That is, instead of the counters being "the number of failures, or None", 
they could be "the number of failures".



-- 
Steven



More information about the Python-list mailing list