Novo curso! Todo programador deveria aprender IA generativa!
Experimente uma aula grƔtis+ 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 Respostas
+ 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.