Skip to content

Commit 5141e12

Browse files
committed
Add require() to compliment assert()
1 parent 8f1d982 commit 5141e12

1 file changed

Lines changed: 31 additions & 1 deletion

File tree

src/bd2k/util/exceptions.py

Lines changed: 31 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,37 @@ def __enter__( self ):
3131
self.exc_info = sys.exc_info( )
3232

3333
def __exit__( self, *exc_info ):
34-
if self.log is not None and exc_info and exc_info[0]:
34+
if self.log is not None and exc_info and exc_info[ 0 ]:
3535
self.log.warn( "Exception during panic", exc_info=exc_info )
3636
exc_type, exc_value, traceback = self.exc_info
3737
raise exc_type, exc_value, traceback
38+
39+
40+
class RequirementError( Exception ):
41+
"""
42+
The expcetion raised bye require(). Where AssertionError is raised when there is likely an
43+
internal problem within the code base, i.e. a bug, an instance of this class is raised when
44+
the cause lies outside the code base, e.g. with the user or caller.
45+
"""
46+
pass
47+
48+
49+
def require( value, message ):
50+
"""
51+
Raise RequirementError with the given message if the given value is considered false. See
52+
https://docs.python.org/2/library/stdtypes.html#truth-value-testing for a defintiion of which
53+
values are false. This function is commonly used for validating user input. It is meant to be
54+
complimentary to assert. See RequirementError for more on that.
55+
56+
:param Any value: the value to be tested
57+
:param message:
58+
:return:
59+
60+
>>> require(1 + 1 == 2, 'You made a terrible mistake')
61+
>>> require(1 + 1 == 3, 'You made a terrible mistake')
62+
Traceback (most recent call last):
63+
...
64+
RequirementError: You made a terrible mistake
65+
"""
66+
if not value:
67+
raise RequirementError( message )

0 commit comments

Comments
 (0)