Home > OS >  Python Optimize multiple if-else based on truthy value
Python Optimize multiple if-else based on truthy value

Time:05-27

I have following code in Python where based on a boolean flag I need to check a list count, wondering if there is a better way to code this in Python?

If var_true:
    if len(something) > 0:
        logger.console (“Something found”)
    else:
        raise AssertionError(“something was not found”)
If not var_true:
    if len(something) == 0:
        logger.console (“Something not expected to be found, was not seen”)
    else:
        raise AssertionError(“something unexpected was found”)

CodePudding user response:

Replace the else: raise AssertionError code with the actual assert statement (which lets it get skipped when run in -O mode, but behaves identically to your current code in normal [debug] mode):

if var_true:
    assert something, "something was not found"  # Also remove len checks; sequences are naturally truthy when non-empty
    logger.console("Something found")
else:
    assert not something, "something unexpected was found"  # Same length check removal
    logger.console("Something not expected to be found, was not seen")

During testing (or all the time, your choice if you never run with -O) you'll be told if your assumption is violated. In release mode, you'll skip the tests that should never be hit and run a little faster.

If this is not a case where the assert case should never occur unless a developer made a mistake, you shouldn't use assert or AssertionError (both of which imply an "impossible" thing has occurred), and should instead raise some other appropriate exception, e.g. ValueError for when an invalid value was supplied.

  • Related