pythonboolean-expression

Odd boolean expression


I'm trying to debug (rewrite?) someone else's Python/cherrypy web app, and I ran across the following 'if' statement:

if not filename.endswith(".dat") and (
    filename.endswith(".dat") or not filename.endswith(".cup")
):
    raise RuntimeError(
        "Waypoint file {} has an unsupported format.".format(
            waypoint_file.filename
        )
    )

I think this is the same as:

if not A and (A or not B):

If so, then:

I'm pretty sure that the intent of the if block is to warn the user that the extension of the file in question is neither .DAT nor .CUP, but it doesn't look to me that it actually executes that intent.

I think the if block should be:

if(not .DAT and not .CUP) = if not(.DAT or .CUP)

Is that correct?


Solution

  • As you have two variables which could only have one of two values you can easily test each case, for example by doing

    for a in [False, True]:
        for b in [False, True]:
            print(a, b)
            if not a and (a or not b):
                print("Condition hold")
            else:
                print("Condition does not hold")
    

    which gives output

    False False
    Condition hold
    False True
    Condition does not hold
    True False
    Condition does not hold
    True True
    Condition does not hold
    

    As you can see it does only hold when both are False, therefore it is equivalent to

    if not a and not b:
    

    However in this particular case you do not even needs 2 conditions, as endswith argument

    can also be a tuple of suffixes to look for

    therefore you can write

    if not filename.endswith((".dat", ".cup")):
        print("Unsupported format")