Skip to content

Instantly share code, notes, and snippets.

@earonesty
Last active January 6, 2021 16:46
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save earonesty/08e9cbe083a5e0583feb8a34cc538010 to your computer and use it in GitHub Desktop.
Save earonesty/08e9cbe083a5e0583feb8a34cc538010 to your computer and use it in GitHub Desktop.
Python's 'if' statement gets privileged information from conditionals
# python 'if' statement is priviliged to the boolean output of compound conditionals
# other statements are not, and have to double-evaluate the output
# unless the output is "the last one"
class X:
def __init__(self):
self.v = False
self.c = 0
def __bool__(self):
self.c = self.c + 1
print("boolin'", self.c)
self.v = not self.v
return self.v
y = 1
n = 0
# case 1: 'if' gets a bool back from "or"
x = X()
if x or y:
assert x.c == 1
else:
# we never get here, because if doesnt' need to reevaluate x
assert False
# case 2: looks like the same code as above, but z isn't priviliged like 'if'
x = X()
z = x or y
if z:
assert False
else:
# we had to bool twice...
assert x.c == 2
# case 3: 'not' is not priviliged, like 'if;
x = X()
z = not(x or y)
if z:
assert x.c == 2
else:
assert False
# case 4: we don't need to double-evaluate this
x = X()
z = n or x
if z:
assert x.c == 1
else:
assert False
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment