[Python-ideas] Repurpose `assert' into a general-purpose check
gadgetsteve at live.co.uk
Thu Jan 18 00:21:04 EST 2018
On 17/01/2018 17:19, Nikolas Vanderhoof wrote:
> I think having a means for such validations separate from assertions
> would be helpful.
> However, I agree with Steven that 'validate' would be a bad keyword choice.
> Besides breaking compatibility with programs that use 'validate', it
> would break
> in the standard library.
To me it looks like this discussion has basically split into two
separate use cases:
1. Using assert in a way that it will not (ever) get turned off.
2. The specific case of ensuring that a variable/parameter is an
instance of a specific type.
and I would like to suggest two separate possibly syntaxes that might
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.
2. For the specific, and to me more desirable, use case of ensuring type
compliance how about an ensure keyword, (or possibly function), with a
syntax of "ensure var type" or "ensure(var, type)" which goes a little
further by attempting to convert the type of var to type and only if var
cannot be converted raises a type exception. This second syntax could,
of course, be implemented as a library function rather than a change to
python itself. Either option could have an optional exception to raise,
with the default being a type error.
Steve (Gadget) Barnes
Any opinions in this message are my personal opinions and do not reflect
those of my employer.
More information about the Python-ideas