Does 'and' short circuit?

Fredrik Lundh fredrik at effbot.org
Sun Jan 14 17:11:36 EST 2001


noahspurrier at my-deja.com wrote:
> Does the 'and' statement short-circuit?

Yes.

>    For example are the following statements safe?
>    x={'notfoo':1}
>    if x.has_key('foo') and x.get('foo') == 1:
>        print 'bar'

Well, that would be safe even if "and" didn't short-circuit
("get" returns None if the key doesn't exist).

I suppose you meant:

    if x.has_key('foo') and x['foo'] == 1:
        print 'bar'

which is probably better written as:

    if x.get('foo') == 1:
        print 'bar'

> I have not been able to find a confirmation to this
> in the online documentation or tutorial.

    http://www.python.org/doc/current/ref/lambda.html
    "Boolean operations"

    "The expression x and y first evaluates x; if x is false,
    its value is returned; otherwise, y is evaluated and the
    resulting value is returned"

Cheers /F





More information about the Python-list mailing list