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
46 lines (30 loc) · 1.11 KB
/
reasoned_bool.py
File metadata and controls
46 lines (30 loc) · 1.11 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
# Copyright 2009-2017 Ram Rachum.
# This program is distributed under the MIT license.
class ReasonedBool:
'''
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 f'<{self.value} because {repr(self.reason)}>'
else: # self.reason is None
return f'<{self.value} with no reason>'
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