WayToDoor
WayToDoor

Reputation: 1750

What is the pythonic way to execute multiple conditions, one after the other, while showing to the user which is the first to fail

Let's say I have this working code:

def check_some_conds(args):
    assert (condA(args) or
            condB(args))

    assert condC(args)
    assert condD(args)

    return True

(Yeah, I know that asserts are bad, but please bear with me for a moment)

Now, when I'm calling this function, I can (more or less), retrive the first failed assertion by using a except AssertionError:, and by doing some magic with the traceback module.

However, this is not ideal because:

I'm looking for a way to:

If that's not really possible, please feel free to suggest partial answers to my problem

Upvotes: 1

Views: 92

Answers (1)

Primusa
Primusa

Reputation: 13498

Loop through your conditions and raise errors at the end:

fail = False
for condition in [cond1, cond2, cond3 ...]:

    if not condition(args):
        print(condition.__name__, "failed")
        fail = True
    else:
        print(condition.__name__, "succeeded")
if fail: raise ...

Upvotes: 3

Related Questions