[ python-Bugs-846564 ] "and" operator tests the first argument twice
SourceForge.net
noreply at sourceforge.net
Fri Nov 21 14:29:24 EST 2003
Bugs item #846564, was opened at 2003-11-21 08:08
Message generated for change (Comment added) made by tim_one
You can respond by visiting:
https://sourceforge.net/tracker/?func=detail&atid=105470&aid=846564&group_id=5470
Category: Python Interpreter Core
Group: None
Status: Open
Resolution: None
Priority: 5
Submitted By: Amaury Forgeot d'Arc (amauryf)
Assigned to: Nobody/Anonymous (nobody)
Summary: "and" operator tests the first argument twice
Initial Comment:
When the first operand of "and" results in False, its truth
value is calculated again.
Example:
class myBool:
def __init__(self,value):
self.value = value
def __nonzero__(self):
print 'testing myBool(%s)' % self.value
return bool(self.value)
if myBool(0) and myBool(1):
pass
will print:
testing myBool(0)
testing myBool(0)
The same thing occurs with the "or" operator, when the
first argument has a True truth value:
if myBool(2) and myBool(3):
pass
will print:
testing myBool(2)
testing myBool(2)
This can be a problem when the "__nonzero__" function
is slow or has side-effects. I agree this is not often the
case...
But imagine an object which truth value means "there
are more data to read in a stream". If python evaluates
__nonzero__ twice, the expression: "stream and
otherTest()" can become True *without* evaluating the
otherTest!
----------------------------------------------------------------------
>Comment By: Tim Peters (tim_one)
Date: 2003-11-21 14:29
Message:
Logged In: YES
user_id=31435
Don't panic <wink>. "and" doesn't evaluate anything twice.
The subtlety here is that "and" and "or" return one of their
arguments. If x evaluates to false in "x and y", then "x and y"
returns x:
>>> class C:
... def __nonzero__(self): return False
...
>>> x, y = C(), C()
>>> (x and y) is x
True
>>> (x or y) is y
True
>>>
The second evaluation occurs because "if expr:" has to
evaluate expr. That part's got nothing to do with "and", it's
entirely to do with "if".
None of this is going to change, of course.
----------------------------------------------------------------------
Comment By: Neal Norwitz (nnorwitz)
Date: 2003-11-21 14:07
Message:
Logged In: YES
user_id=33168
Ouch! This happens in 2.2 and CVS (I assume 2.3 too). I'll
look into this. Fixing this should be a good way to improve
performance. :-)
Thanks for the report!
----------------------------------------------------------------------
You can respond by visiting:
https://sourceforge.net/tracker/?func=detail&atid=105470&aid=846564&group_id=5470
More information about the Python-bugs-list
mailing list