I love assert

Ian Kelly ian.g.kelly at gmail.com
Thu Nov 13 00:05:46 CET 2014


On Wed, Nov 12, 2014 at 3:47 PM, Marko Rauhamaa <marko at pacujo.net> wrote:
> Ian Kelly <ian.g.kelly at gmail.com>:
>
>> Although to be honest I'd rather use something like "raise
>> RuntimeError('Unreachable code reached')" than "assert False" here. If
>> the expectation is that the code will never be executed, then there's
>> no reason to ever optimize it out.
>
> Asserts have nothing to do with them being optimized out. Asserts are
> communication.
>
> Apart from idiomatic style, there is no difference between
>
>     # never reached
>
>     assert False
>
>     raise RuntimeError('Unreachable code reached')

If the purpose is communication, then the comment is most effective,
as it can easily convey anything you want. If the purpose is to detect
programming errors, then the RuntimeError is most effective, as it
will always raise an error in the event it is reached.

assert False is a strange hybrid of the two that is less effective at
both purposes.



More information about the Python-list mailing list