pythonpython-2.7short-circuiting

Can anyone explain the "guardian pattern" to me


Tried searching for guardian pattern but I couldn't find anything that answered my question so here I am again. In the book I am reading the author uses a line of code that he calls, "the guardian pattern" and I don't really understand how it works. here is the example and I would be grateful if someone could explain it to me.

while True:
    line = raw_input('> ')
    if len(line) > 0 and line[0] == '#' :
        continue
    if line == 'done':
        break
    print line
print "done!"

so why, if the length of the line > 0 and line[0] == '#' : does it not error if I just hit enter with nothing there. Wouldn't the line be 0 and thus line isn't > 0? if you put the orig code in which is

if line[0] == '#' : 

it errors out when you just hit enter.


Solution

  • so why, if the length of the line > 0 and line[0] == '#' : does it not error if I just hit enter with nothing there.

    No, it does not throw an error. Python uses lazy evaluation, which enables short circuiting with the and operator. See the docs.

    In other words, the second part of the boolean expression, i.e., line[0] == '#', only gets evaluated if the first part is True.

    I believe this is the reason why that author calls this the guardian pattern, so that the first part of the expression avoids (guards) a possible error in the second part of the expression.

    If you remove that first part, like in the example you show, then you would be trying to access the first element of line (line[0]), when there are none elements in line.