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

7th Nov 2019, 11:29 PM
꧁༺ Jenspi ༻꧂
꧁༺ Jenspi ༻꧂ - avatar
7 Answers
+ 5
Idk. Honestly assertions are not what comes to my mind immediately. I'd rather just use if and raise at first.
7th Nov 2019, 11:35 PM
šŸ‘‘ Prometheus šŸ‡øšŸ‡¬
šŸ‘‘ Prometheus šŸ‡øšŸ‡¬ - avatar
+ 5
I rarely use them.
9th Nov 2019, 2:58 AM
Sonic
Sonic - avatar
+ 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.
8th Nov 2019, 2:13 AM
Jason Stone
Jason Stone - avatar
+ 3
Jason Stone [14 yrs old] oh, so its basically a print statement? thats pretty helpful actually
8th Nov 2019, 2:20 AM
꧁༺ Jenspi ༻꧂
꧁༺ Jenspi ༻꧂ - avatar
+ 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
8th Nov 2019, 2:22 AM
Jason Stone
Jason Stone - avatar
+ 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.
8th Nov 2019, 2:22 AM
šŸ‘‘ Prometheus šŸ‡øšŸ‡¬
šŸ‘‘ Prometheus šŸ‡øšŸ‡¬ - avatar
+ 1
You can use it in a testcase of nose or pytest.
7th Nov 2019, 11:42 PM
o.gak
o.gak - avatar