forked from cool-RR/python_toolbox
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathreasoned_bool.py
More file actions
53 lines (35 loc) · 1.3 KB
/
reasoned_bool.py
File metadata and controls
53 lines (35 loc) · 1.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# Copyright 2009-2014 Ram Rachum.
# This program is distributed under the MIT license.
'''
Defines the `ReasonedBool` class.
See its documentation for more details.
'''
class ReasonedBool(object):
'''
A variation on `bool` that also gives a `.reason`.
This is useful when you want to say "This is False because... (reason.)"
Unfortunately this class is not a subclass of `bool`, since Python doesn't
allow subclassing `bool`.
'''
def __init__(self, value, reason=None):
'''
Construct the `ReasonedBool`.
`reason` is the reason *why* it has a value of `True` or `False`. It is
usually a string, but is allowed to be of any type.
'''
self.value = bool(value)
self.reason = reason
def __repr__(self):
if self.reason is not None:
return '<%s because %s>' % (self.value, repr(self.reason))
else: # self.reason is None
return '<%s with no reason>' % self.value
def __eq__(self, other):
return bool(self) == other
def __hash__(self):
return hash(bool(self))
def __neq__(self, other):
return not self.__eq__(other)
def __bool__(self):
return self.value
__nonzero__ = __bool__