+ 4
Anyone actually use assertions?
Iâm going through notes I took and see that I wrote things down about assertions and realized I havenât seen them in lessons since. Someone explained that theyâre like the try/except statement but for your own errors so I get that, but does anyone actually use them? Iâm finding it hard to think of any times I would implement an assertion.
7 Answers
+ 5
Idk. Honestly assertions are not what comes to my mind immediately. I'd rather just use if and raise at first.
+ 5
I rarely use them.
+ 3
I see you are talking about python, but I am only familiar with the Lua assert() function, so I will be talking about that. The python version probably isnât too different.
One use is for debugging. For example, in Lua, you can do something like
assert(1 == 1, âif this error message displays, then something is clearly wrongâ)
You can also use it to raise errors that arenât for debugging
function sqrt(n)
assert(type(n) != ânumberâ, âuh oh, looks like you didnât pass a number to this function!â)
return math.sqrt(n)
end
however, it just so happens that Lua has extra functionality in the error() function not supported by the assert() function that makes it more desirable for a case like this, but I wonât get into that.
+ 3
Jason Stone [14 yrs old] oh, so its basically a print statement? thats pretty helpful actually
+ 2
well, not quite. It raises an error, just conditionally. Think of it as shorthand for
if condition:
#whatever you do to raise an error in python
+ 2
Just a little background, Python assertion works like:
assert (boolean) (error message)
Jason Stone [14 yrs old] ê§àŒșJennyàŒ»ê§
The error message will look like:
AssertionError: (error message)
Error message is optional btw.
+ 1
You can use it in a testcase of nose or pytest.