New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
"and" operator tests the first argument twice #39578
Comments
When the first operand of "and" results in False, its truth Example: if myBool(0) and myBool(1):
pass will print: The same thing occurs with the "or" operator, when the if myBool(2) and myBool(3):
pass
will print:
testing myBool(2)
testing myBool(2) This can be a problem when the "__nonzero__" function But imagine an object which truth value means "there |
Logged In: YES Ouch! This happens in 2.2 and CVS (I assume 2.3 too). I'll Thanks for the report! |
Logged In: YES Don't panic <wink>. "and" doesn't evaluate anything twice. >>> 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 None of this is going to change, of course. |
Logged In: YES I don't mind the __nonzero__ be called twice, but the test import random
class C:
def __nonzero__(self):
return bool(random.randint(0,1))
if C() and False:
print "Should we really allow this?" There are 25% chances for the condition to be true. I find If this behaviour is expected, it should at least be clearly |
1 similar comment
Logged In: YES I don't mind the __nonzero__ be called twice, but the test import random
class C:
def __nonzero__(self):
return bool(random.randint(0,1))
if C() and False:
print "Should we really allow this?" There are 25% chances for the condition to be true. I find If this behaviour is expected, it should at least be clearly |
Logged In: YES This is clearly not a bug. I'm closing it as "works for me": That the semantics of the if statement (not the "and" If changing zero-ness of objects surprises you: Don't do |
Logged In: YES Just noting that someone who creates objects with insanely if bool(x) and bool(y): instead. I agree with Martin that there's no bug here, so |
Note: these values reflect the state of the issue at the time it was migrated and might not reflect the current state.
Show more details
GitHub fields:
bugs.python.org fields:
The text was updated successfully, but these errors were encountered: