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

Steve Barnes 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
> wsgiref.validate 
> <https://eur01.safelinks.protection.outlook.com/?url=https%3A%2F%2Fdocs.python.org%2F3.6%2Flibrary%2Fwsgiref.html%23module-wsgiref.validate&data=02%7C01%7C%7Caa26210dce644b49a87508d55dcebb23%7C84df9e7fe9f640afb435aaaaaaaaaaaa%7C1%7C0%7C636518064831624779&sdata=Q9x3Boch1FnCgVnd4SNmR35b0g%2BPHszNJYHrDol2%2BKk%3D&reserved=0> 
> 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 
make sense.

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 mailing list