Does 'and' short circuit? 
Author Message
 Does 'and' short circuit?

Does the 'and' statement short-circuit?
For example are the following statements safe?

    x={'notfoo':1}
    if x.has_key('foo') and x.get('foo') == 1:
        print 'bar'

It seems to work under the interpreter, but I
have not been able to find a confirmation to this
in the online documentation or tutorial.

Thanks,
Noah

Sent via Deja.com
http://www.*-*-*.com/



Fri, 04 Jul 2003 05:40:52 GMT  
 Does 'and' short circuit?

Quote:

> Does the 'and' statement short-circuit?

Yes.

Quote:
>    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'

Quote:
> 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



Fri, 04 Jul 2003 06:11:36 GMT  
 
 [ 2 post ] 

 Relevant Pages 

1. MkDir(*CSTRING),SHORT,RAW,NAME('_mkdir')

2. New version of 'short' available

3. errors when doing 'make test'

4. Have you ever done 'namespace delete ::'?

5. long = short*short ; (short,short) = long/short

6. Scientific puzzle of formal circuit verification at next week's DAC

7. Does RB use short-circuit boolean evaluation?

8. Short circuit boolean operators...

9. Short circuit boolean operators...

10. Short Circuits and Linked Lists

11. Short-circuiting conditionals

12. short-circuit logic in PL/I compiler, or lack thereof

 

 
Powered by phpBB® Forum Software