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

Nick Coghlan ncoghlan at gmail.com
Thu Jan 18 00:41:17 EST 2018

On 18 January 2018 at 07:46, Steven D'Aprano <steve at pearwood.info> wrote:
> To justify a keyword, it needs to do something special that a built-in
> function can't do, like delayed evaluation (without wrapping the
> expression in a function).

My reaction to these threads for a while has been "We should just add
a function for unconditional assertions in expression form", and I
finally got around to posting that to the issue tracker rather than
leaving it solely in mailing list posts:

The gist of the idea is to add a new ensure() builtin along the lines of:

    class ValidationError(AssertionError):

    _MISSING = object()

    def ensure(condition, msg=_MISSING, exc_type=ValidationError):
        if not condition:
            if msg is _MISSING:
                msg = condition
            raise exc_type(msg)

There's no need to involve the compiler if you're never going to
optimise the code out, and code-rewriters like the one in pytest can
be taught to recognise "ensure(condition)" as being comparable to an
assert statement.


Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia

More information about the Python-ideas mailing list