
12.09.21 17:28, Guido van Rossum пише:
This is cool.
AFAIK pytest does something like this. How does your implementation differ?
What pytest does is awesome. I though about implementing it in the standard compiler since seen it the first time.
What is your argument for making this part of the language? Why not a 3rd party library?
It needs a support in the compiler. The condition expression should be compiled to keep all immediate results of subexpressions on the stack. If the final result is true, immediate results are dropped. If it is false, the second argument of assert is evaluated and its value together with all immediate results of the first expression, together with references to corresponding subexpressions (as strings, ranges or AST nodes) are passed to the special handler. That handler can be implemented in a third-party library, because formatting and outputting a report is a complex task. The default handler can just raise an AttributeError.
What about asserts that are not used for testing, but as classic “unless there’s a bug, this should hold”? Those may not want to incur the extra cost.
The only extra cost is that immediate results are temporary save on stack instead of just be dropped. It increases the size of bytecode and stack, but I don't think it will be significant.