Do we always need to write "assert" in the first row of our functions? (this time im talking about q.1 in our HW, but i mean generally). if not in which cases should we do it?
Date: 11 Jan 2012 16:43
Number of posts: 4
RSS: New posts
assert means "I assume the following is True, please shout otherwise".
If your program fails miserably and in a very inexplicable way when the assumption is false, it's in your best interest to have the assert so you know what's gone awry before it wreaks havoc.
Example: if you're about to divide by x, it's not too important to assert it's non-zero, just because the error message is self-explaining. But if you're about to access some list in position i, and negative values of i will make your computation wrong, possibly crashing the code elsewhere, then you'd better assert i >= 0 beforehand.
Real world programs obviously have to deal with bad input in a more robust way than just to drop dead while crying "goodbye, cruel world!"; we leave the (important!) topic of input validation to be dealt with in further courses.
TL;DR — no.
I see… so in our course we can either assume that the input is from the correct type, or put an "assert" command…. but if the input is from the wrong type, we don't have to deal with it…for example, if the input is a string "12" while the correct type of input is integer, we don't have to turn the string into 12. Right?
Moreover, unless the requirements are to support strings as well (like we had in HW #4), it's way better to refuse malformed input than to partially accept it (e.g., if you accepted "12" but not "-12", people using your function would get mad trying to figure out why doesn't it work as they expected it to).
Quoting Guido van Rossum (type import this for more of these):
Explicit is better than implicit.
In the face of ambiguity, refuse the temptation to guess.