[Python-ideas] Repurpose `assert' into a general-purpose check

Chris Angelico rosuav at gmail.com
Thu Jan 18 01:22:06 EST 2018

On Thu, Jan 18, 2018 at 4:21 PM, Steve Barnes <gadgetsteve at live.co.uk> wrote:
> 1. For asserts that should not be disabled we could have an always
> qualifier optionally added to assert, either as "assert condition
> exception always" or "assert always condition exception", that disables
> the optimisation for that specific exception. This would make it clearer
> that the developer needs this specific check always. Alternatively, we
> could consider a scoped flag, say keep_asserts, that sets the same.

But if they're never to be compiled out, why do they need special syntax?

assert always x >= 0, "x must be positive"

can become

if x < 0: raise ValueError("x must be positive")

I haven't yet seen any justification for syntax here. The nearest I've
seen is that this "ensure" action is more like:

    cond = x >= 0
except BaseException:
    raise AssertionError("x must be positive")
    if not cond:
        raise AssertionError("x must be positive")

Which, IMO, is a bad idea, and I'm not sure anyone was actually
advocating it anyway.


More information about the Python-ideas mailing list