Skip to content

Instantly share code, notes, and snippets.

@dreampuf
Created November 25, 2012 06:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dreampuf/4142565 to your computer and use it in GitHub Desktop.
Save dreampuf/4142565 to your computer and use it in GitHub Desktop.
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