I have a 3-valued Logical class in my dbf module.
It implements False
/True
/Unknown
as singleton values Falsth
/Truth
/Unknown
. It implements all the comparison operators, and also allows comparison with the Python singletons False
/True
/None
(None
taken to mean unknown). Any comparison with an Unknown
value results in Unknown
, and an attempt to implicitly use an Unknown
value in an if
statement (or other bool
context) will raise a TypeError
, although Truth
and Falsth
can be used in boolean contexts, and Unknown
can be compared against directly.
Because it is not possible to override the and
, or
, and not
behavior the type overrides the bitwise operators &
, |
, and ~
.
It also implements __index__
with Unknown
having the value of 2
.
Example:
from dbf import Logical, Truth, Falsth, Unknown
middle_name = raw_input("What is the middle name? ['?' if unknown] ").strip()
if middle_name == '?':
middle_name = ''
middle_exists = Unknown
elif middle_name:
middle_exists = Truth
else:
middle_exists = Falsth
.
.
.
if middle_exists is Unknown:
print "The middle name is unknown."
elif middle_exists:
print "The middle name is %s." % middle_name
else:
print "This person does not have a middle name."