[Python-ideas] Repurpose `assert' into a general-purpose check
neatnate at gmail.com
Mon Nov 27 22:21:04 EST 2017
On Mon, Nov 27, 2017 at 9:28 PM, Ivan Pozdeev via Python-ideas <
python-ideas at python.org> wrote:
> On 28.11.2017 5:19, Chris Angelico wrote:
> Actually, Python does have a way of disabling assertions (the -O
>> flag), so they should be treated the same way they are in C.
>> Assertions should not be used as shorthands for "if cond: raise Exc"
>> in the general case.
> I'm claiming, and provided evidence, that there are no use cases for this
> in Python, so no-one (of any significance) will suffer when the disabling
> is cut out.
> In any case, we will probably do it with a __future__ statement for a
> transitional period.
I think it would be interesting to investigate how assert statements are
used in the wild. I can think of three kinds of uses:
1) Nonredundant checking: The assertion aims to be a concise way to raise
exceptions under certain conditions that might arise even presuming that
the code is internally correct. (For example, to check that the interface
with another piece of code is as expected, or to validate user input.)
This seems to be the use case the OP is targeting. It is probably not the
use envisioned by the designers of the assert statement. But perhaps assert
is frequently used in this way by people who don't know about the
optimization flag or assume their program won't be run with optimization.
2) Redundant checking: The assertion acts as a test of code correctness. If
the code is correct, it should have no effect; and presuming the code is
well-tested, it can thus be ignored with optimization turned on. But it is
useful as a sanity check of a tricky algorithm, and can help a reader to
understand the implementation. Is it often the case that optimizing these
assertions away brings significant performance savings?
3) Temporary debugging: I often write something like assert False,(x,y,z)
as a quick way to force the program to terminate and print some values.
Unlike print(x,y,z), this has the advantage of being blatantly obvious as
debugging code that does not belong in the final version.
It seems unlikely that one would purposefully turn on optimization in
conjunction with temporary assertions, so this use case may be irrelevant
to the proposal.
-------------- next part --------------
An HTML attachment was scrubbed...
More information about the Python-ideas