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

Steven D'Aprano steve at pearwood.info
Sat May 5 11:30:39 EDT 2018

On Sat, May 05, 2018 at 08:04:45AM +0000, Eloi Gaudry wrote:

> Hi folks,
> I intend to add a runtime assertion feature in python.

I'm very interested in this idea, but I'm afraid your draft PEP isn't 
very clear about this feature. Comments below.

> Rationale
> There is no runtime assert relying on python grammar available. For 
> diagnostics and/or debugging reasons, it would be valuable to add such 
> a feature.

Why not this?


where run_check is an ordinary function. If DEBUG_ENABLED is false, the 
only runtime overhead is the name lookup and bool test, the expression 
is not evaluated.

What features does your suggestion offer over this simple technique?

> A brief example why avoiding evaluating the expression is needed to 
> avoid any overhead in case the runtime assert should be ignored.
> ::
> runtime_assert( 999 in { i:None for i in range( 10000000 ) } )

You say that you have been using this feature in production for two 
years. You should give real-life examples, not fake examples like the 
above. That example would be better written as:


since no part of the test actually depends on either the enormous dict 
or range objects that you build only to throw away.

> Usage
> ::
> runtime_assert( expr )
> #would result in 
> if expr and runtime_assert_active:
>     print RuntimeAssertionError()

Surely the test should be the other way around?

    if runtime_assert_active and expr:

otherwise the expression is evaluated regardless of whether the runtime 
assertions are active or not.

Please use Python 3 syntax for the PEP, as Python 2 is in maintenance 
mode and will absolutely not get any new language features.

Some more observations:

I like the idea of more control over runtime checking, but your PEP 
should justify why this is a good idea and why "just write more unit 
tests" isn't the solution.

What happens if the caller has defined their own function or variable 
called runtime_assert?

Can the caller customise the assertion error message?

If you are changing the grammar, why not make runtime_assert a statement?

Can the caller set an application-wide global across all modules, or do 
they have to set

    runtime_assert_active = True

in every module they want to use runtime_assert?


More information about the Python-ideas mailing list