As suggested in the Python wiki assertions are good for
- Checking parameter types, classes, or values
- Checking data structure invariants
- Checking "can't happen" situations (duplicates in a list, contradictory state variables)
- After calling a function, to make sure that its return is reasonable
But where is the edge between using assertions and using an 'if' statement with raising exceptions next?
For example.
def some_domain_operation(user, invoice):
assert isinstance(user, (User, int))
# Do something.
vs
def some_domain_operation(user, invoice):
if not isinstance(user, (User, int)):
raise ValueError()
# Do something.
I think that using assertions is not reliable (could be disabled by the user), so I could not give a good example, when using assertions is better than using explicit an 'if' with raise next
.
What is your opinion about assertions Pn python. Are they crutches?