Possible Duplicate:
What's the best way to implement an 'enum' in Python?
I’m writing a function that, ideally, I’d like to return one of three states: “yes”, “no”, and “don’t know”.
-
Do any programming languages have a type that has three, and only three states? Like a boolean, but with three states instead of two?
-
In languages that don’t have such a type (like Python), what’s the best type to represent this?
Currently I think I’ll go with an integer (
0for “no”,1for “don’t know” and2for “yes”), but maybe there’s a better way? Integers seem a bit “magic number”.I could return
True,FalseorNone, but asNonewould evaluate toFalsein most comparison contexts it seems a bit ripe for errors.
In Python I’d do that with a wrapper object that holds one of those three values; I’d use
True,False, andNone. Since the implicit truthiness value of a Boolean-like object with three possible values is problematic, we’ll solve that by disallowing that entirely (raising an exception in__nonzero__(), or in Python 3,__bool__()), thus requiring that comparisons always be done explicitly, usingin,==, or!=. We’ll implement equality as identity so that only the specific singleton valuesTrue,False, andNoneare matched.Usage:
When using
Tristateobjects, you must explicitly specify which values to match, i.e.foo == True or bar != None. You can also dofoo in (False, None)to match multiple values (though of courseintwo values is the same as!=with a single value). If there are other logic operations you wish to be able to perform with these objects, you could implement these as methods, or possibly by overriding certain operators (sadly, however, logicalnot,and, andorare not overrideable, though there’s a proposal to add that).Also note that you can’t override
id()in Python, so e.g.Tristate(None) is NoneisFalse; the two objects are in fact different. Since good Python style is to useiswhen comparing against singletons, this is unfortunate, but unavoidable.Edit 4/27/16: Added support for comparing one
Tristateobject to another.