I love assert

Chris Angelico rosuav at gmail.com
Wed Nov 12 17:58:47 EST 2014


On Thu, Nov 13, 2014 at 9:47 AM, Marko Rauhamaa <marko at pacujo.net> wrote:
> Apart from idiomatic style, there is no difference between
>
>     # never reached
>
>     assert False
>
>     raise RuntimeError('Unreachable code reached')
>
>     1 / 0
>
>     print("Hello world")
>
> since, after all, that line is never reached!

If it truly is never reached, there's no difference between any of the
above and "pass". (With the possible exception of 1/0, which might
plausibly be optimized to a constant, which would mean it'd throw an
error at compile time.) But what if, one day, it is reached? What
should happen? RuntimeError implies that there's an error that
couldn't be detected until run time. AssertionError might not get
raised. Printing "Hello world" to standard out will almost certainly
be misinterpreted. ZeroDivisionError makes almost no sense for
"shouldn't happen". Think about what your code ought to do *if it is
reached*, because if you really don't care about that case, you won't
have a line of code at all.

ChrisA



More information about the Python-list mailing list