+ 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 Respuestas
+ 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.