[Python-Dev] Assertions

Tim Peters tim.one@home.com
Tue, 21 Nov 2000 20:34:32 -0500

[Tim, objects to abusing assertions]

[Paul Prescod]
> So you prefer
> if __debug__ and node.nodeType!=ELEMENT_TYPE:
>     raise TypeError

I personally prefer

if node.nodeType != ELEMENT_TYPE:
    raise TypeError

if that is in fact a correct test of whatever user-input precondition it is
you're verifying.  An assert would be appropriate if it were "impossible"
for the test to fail.

> Unfortunately there's no way to turn that off at "compile time" so you
> always incur the __debug__ lookup cost. That would send us back to two
> versions of the methods.

Actually, there is:

if __debug__:
    if node.nodeType != ELEMENT_TYPE:
        raise TypeError

Python produces no code for that block under -O (btw, this is the same
mechanism that makes asserts vanish under -O:  it's __debug__ that's magic,
not asserts).

As a user, though, I don't expect -O to turn off argument verification!
Same as the Python implementation in these respects:  public API functions
*always* check their arguments, while some private API functions check only
in Debug builds (and via the C library's assert() function, as it's a bug in
the implementation if a private API is misused).

do-s-right-thing-ly y'rs  - tim