Is there a built-in Python value if the truth value is not valid?

I have a set of subclasses that must define the x attribute, which should either evaluate to True or False. In order to catch errors, when I forgot to set this value in a subclass, I would like to set it in my superclass to a value for which evaluating the truth leads to an error. Is there a built-in value in Python with this behavior? I kind of expected NotImplemented to have this behavior, but it evaluates to True .

I could set it to numpy.array([0, 0]) , where if x: raises a ValueError , but that is wrong. Similarly, I could define my own class where __bool__ throws an exception. But is there any built-in value suitable for this purpose?

Other alternatives would be to set the property (abstract or not) or not define it at all (so we get an AttributeError ).

(I use Python 3.4, in case that matters)

+5
python boolean
Aug 15 '14 at 16:04
source share
1 answer

I recently came across the same issue with a slightly different use case:

I had a class with a flag attribute whose value is passed to the caller __init__ . Class objects can be created from two different versions of the data, where the older version of the data does not contain the information necessary to determine whether the True False flag should.

Setting otherwise bool-value to None (which is the usual way of representing missing data) will not work, because None happily evaluates False .

Like you, I did not find a satisfactory built-in solution, so I wrote it myself.

(written for python2.7 but easy to configure fo python3)

 class NotTrueNorFalseType(object): """ A singleton class whose instance can be used in place of True or False, to represent a value which has no true-value nor false-value, eg a boolean flag the value of which is unknown or undefined. """ def __new__(cls, *args, **kwargs): # singleton try: obj = cls._obj except AttributeError: obj = object.__new__(cls, *args, **kwargs) cls._obj = obj return obj def __nonzero__(self): raise TypeError('%s: Value is neither True nor False' % self) def __repr__(self): return 'NotTrueNorFalse' NotTrueNorFalse = NotTrueNorFalseType() 

The constructive (minimal) solutions in this class were inspired by the None singleton (for example, by naming the singleton instance "Foo" and the class "FooType", returning "Foo" from __repr__ , raising TypeError for invalid operations).

+2
Aug 15 '14 at 16:29
source share



All Articles