Ok, that’s consistent with my understanding of assert. I guess assert is a little funny because it feels like whether assert or raise is used depends a little bit on the developers opinion of how certain they are that the code will behave the way they think it does. I’m still trying to wrap my head around when it’s crystal clear that an assert is appropriate.
assert is appropriate when you might otherwise consider putting a comment there.
def spam(n):
if n > 10: raise DomainError("That's TOO much spam")
if n < 0: raise ValueError("Don't you value spam at all?")
if n >= 3:
spam(n // 2)
spam(n // 2 + n % 2)
elif n % 2:
spam(1)
spam(n - 1)
else:
# n must be 2
print("Spam, spam", end="")
This would be a good use for an assertion. Rather than a comment, you can write assert n == 2 and have Python verify that. It’s fine if this ends up not being checked, because the comment wouldn’t have been checked either.
3 Likes