Reputation: 652
I'm trying to simplify the following:
if x < 0:
print('we don't do negative numbers')
else:
NORMAL CODE HERE
I recently learned of the assert
command, and admire its ability to simplify my previous lines into:
assert x > 0, 'errorText'
NORMAL CODE HERE
I don't want errors to give a traceback, though. I only want that single line like the if/else gives.
Is there a way to get an assertionError to return single line like exceptions do, or do I really need to keep running if/else's everywhere?
Upvotes: 4
Views: 4316
Reputation: 1731
The assert
statement in Python is intended for debugging or for testing. It serves the purpose of halting execution of the program when the condition is not True
. When debugging you can include these statements in your code to help track down errors. Then remove them once the bug is fixed. Using assert
in production code is a bad idea.
As you have it written using assert
, your program will terminate if x is less than zero and the code that follows will not run.
You should continue to use if/else method to provide the two desired code paths. One path to log that x is less than zero, the other path to execute the code in the block NORMAL CODE HERE.
If x should never be less than 0 at this point, and the remaining code must not be executed then you should raise an Exception that can be caught in the calling code.
def method_using_positive_numbers(x):
if x < 0:
raise ValueError("we don't do negative numbers")
NORMAL CODE HERE
Another option is to return from the method if the condition is not true.
def method_using_positive_numbers(x):
if x < 0:
print("we don't do negative numbers")
return
NORMAL CODE HERE
Upvotes: 8