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

Nick Coghlan ncoghlan at gmail.com
Thu May 10 07:16:55 EDT 2018


On 10 May 2018 at 17:55, Barry Scott <barry at barrys-emacs.org> wrote:

> On 7 May 2018, at 18:52, Guido van Rossum <guido at python.org> wrote:
>
> On Mon, May 7, 2018 at 6:24 AM, Serhiy Storchaka <storchaka at gmail.com>
> wrote:
>
>> I just don't understand why you need a new keyword for writing runtime
>> checks.
>>
>
> Oh, that's pretty clear. The OP wants to be able to turn these checks off
> with some flag he can set/clear at runtime, and when it's off he doesn't
> want to incur the overhead of evaluating the check. The assert statement
> has the latter property, but you have to use -O to turn it off. He
> basically wants a macro so that
>
>   runtime_assert(<expr>)
>
> expands to
>
>   if <controlling flag> and (<expr>):
>       raise AssertionError
>
> In Lisp this would be easy. :-)
>
>
> This idea requires the same sort of machinery in python that I was hoping
> for to implement the short circuit logging.
>
> My logging example would be
>
> log( control_flag, msg_expr )
>
> expanding to:
>
> if <control_flag>:
> log_function( <msg_expr> )
>

Logging is the example that came to mind for me as well -
https://docs.python.org/3/howto/logging.html#optimization discusses the
"logging.isEnabledFor" API, and how it can be used to avoid the overhead of
expensive state queries when the result log message would just be discarded
anyway.

Generally speaking though, the spelling for that kind of lazy evaluation is
to accept a zero-argument callable, which can then be used with "lambda: "
at the call site:

    runtime_assert(lambda: <expr>)

Cheers,
Nick.

-- 
Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20180510/d9424f8c/attachment-0001.html>


More information about the Python-ideas mailing list