Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Python True Value Testing
#!/usr/bin/env python
#vi: encoding=utf-8
__author__ = "dreampuf <soddyque@gmail.com>"
"""
Reference : http://docs.python.org/2/library/stdtypes.html#truth-value-testing
"""
class S(object):
def __str__(self):
return "<{0} o={{2}}>".format(self.__class__, self.o)
class A(S):
def __init__(self, o):
self.o = o
def __len__(self):
print "A, len"
return self.o
class B(S):
def __init__(self, o):
self.o = o
def __nonzero__(self):
print "B, nonzero"
return self.o
def __len__(self):
print "B, len"
return self.o
a0, a1 = A(0), A(1)
bT, bF = B(True), B(False)
for i in (None, False, 0, 0L, 0.0, 0j, '', (), [], {}, a0, a1, bT, bF):
if i:
print True, i
else:
print False, i
"""
#output:
False None
False False
False 0
False 0
False 0.0
False 0j
False
False ()
False []
False {}
A, len
False <<class '__main__.A'> o={2}>
A, len
True <<class '__main__.A'> o={2}>
B, nonzero
True <<class '__main__.B'> o={2}>
B, nonzero
False <<class '__main__.B'> o={2}>
"""
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment