[Python-ideas] Runtime assertion with no overhead when not active
Chris Angelico
rosuav at gmail.com
Thu May 17 04:38:31 EDT 2018
On Thu, May 17, 2018 at 5:46 PM, Eloi Gaudry <Eloi.Gaudry at fft.be> wrote:
>> But the most important reason is that I'm not really interested in
>> adding a new keyword for this. I would much prefer to explore ways
>> to
>> allow ordinary functions to receive arguments and be able to delay
>> evaluation of those arguments until needed.
> What would then be solution for implementing the runtime_assert with
> the current python api ? A lambda ?
if __runtime_assert__ and long_expensive_calculation: raise AssertionError
There's minimal run-time cost, but you lose the convenience of having
the expression shown in the error's message.
There is, however, a lot of text to this. So if it could be wrapped
up, that would be useful. Hence the idea of exploring ways of doing
this:
def rtassert(expr):
if not __runtime_assert__: return
if expr.eval(): return
raise AssertionError(expr.text)
rtassert(&long_expensive_calculation)
where the ampersand (or something of the sort) means "pass this
expression along unevaluated". The only way to do this currently is
with a lambda function, but they don't get their texts captured. It'd
take either syntactic support, or something like MacroPy, to make this
happen.
ChrisA
More information about the Python-ideas
mailing list