[Python-ideas] Runtime assertion with no overhead when not active

Chris Angelico rosuav at gmail.com
Tue May 8 15:40:44 EDT 2018


On Wed, May 9, 2018 at 5:27 AM, Eloi Gaudry <Eloi.Gaudry at fft.be> wrote:
> My choice of words might not be the best, yes.
> I do see to different meanings and/or context for the historical assert and the one I propose:
>
> 1/
>  the first one would be something saying that, as a developer, when writing
>>>> assert (expr)
>  in my python code, I mean that all my unit tests and real life tests I could think of should succeed the test. I do mean "don't go further, I might not know where you come from or where you intend to go or why you are behaving as such, but you failed to meet this and/or this criteria/condition".
>
> 2/
>  the second one is there to activate some other checks, not while developing, just at runtime when the user uses my extension and want to get some diagnostics/enforcing checks to happen, because he/she is using something I couldn't think of in the first place, something that would not have been checked before.
>
> Yes, those checks might be considered as identical in a language sense, but then : as an extension/interpreter writer, why should I only rely on the debug assert available today? Why would it not make sense to offer another assert, semantically different, aiming at runtime checks issues and this time where control is indeed by the consumer/the extension?
>

No, they're not identical. The first one is an assertion; the second
is simply an 'if' and a 'raise'. It doesn't need any special syntax -
all you need is standard exception creation.

def average(values):
    if not values:
        raise ValueError("Cannot calculate average of empty collection")

This should not be an assertion, "run-time" or otherwise. You never
want to disable it.

ChrisA


More information about the Python-ideas mailing list